Skip to content

Commit

Permalink
deduplicate borshschema inside near_sdk
Browse files Browse the repository at this point in the history
  • Loading branch information
PolyProgrammist committed Mar 1, 2024
1 parent 1b5d476 commit 2d5fb90
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 47 deletions.
6 changes: 2 additions & 4 deletions examples/fungible-token/ft/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,12 @@ use near_contract_standards::fungible_token::{
use near_contract_standards::storage_management::{
StorageBalance, StorageBalanceBounds, StorageManagement,
};
use near_sdk::borsh::BorshSerialize;
use near_sdk::collections::LazyOption;
use near_sdk::json_types::U128;
use near_sdk::{
env, log, near, require, AccountId, BorshStorageKey, NearToken, PanicOnDefault,
PromiseOrValue,
env, log, near, require, AccountId, BorshStorageKey, NearToken, PanicOnDefault, PromiseOrValue,
};
use near_sdk::borsh::BorshSerialize;

#[derive(PanicOnDefault)]
#[near(contract_state)]
Expand All @@ -48,7 +47,6 @@ enum StorageKey {
Metadata,
}


#[near(contract_state)]
impl Contract {
/// Initializes the contract with the given total supply owned by the given `owner_id` with
Expand Down
48 changes: 29 additions & 19 deletions near-sdk-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,7 @@ struct DeriveNearSchema {
borsh: Option<bool>,
}

#[proc_macro_derive(NearSchema, attributes(abi, serde, borsh, schemars, validate))]
#[proc_macro_derive(NearSchema, attributes(abi, serde, borsh, schemars, validate, inside_nearsdk))]
pub fn derive_near_schema(#[allow(unused)] input: TokenStream) -> TokenStream {
#[cfg(not(feature = "abi"))]
{
Expand All @@ -488,6 +488,7 @@ pub fn derive_near_schema(#[allow(unused)] input: TokenStream) -> TokenStream {
use darling::FromDeriveInput;

let derive_input = syn::parse_macro_input!(input as syn::DeriveInput);
let generics = derive_input.generics.clone();
let args = match DeriveNearSchema::from_derive_input(&derive_input) {
Ok(v) => v,
Err(e) => {
Expand All @@ -497,7 +498,7 @@ pub fn derive_near_schema(#[allow(unused)] input: TokenStream) -> TokenStream {

if args.borsh.is_none()
&& args.json.is_none()
&& derive_input.attrs.iter().any(|attr| attr.path().is_ident("abi"))
&& derive_input.clone().attrs.iter().any(|attr| attr.path().is_ident("abi"))
{
return TokenStream::from(
syn::Error::new_spanned(
Expand All @@ -510,7 +511,7 @@ pub fn derive_near_schema(#[allow(unused)] input: TokenStream) -> TokenStream {

// #[abi(json, borsh)]
let (json_schema, borsh_schema) = (args.json.unwrap_or(false), args.borsh.unwrap_or(false));
let mut input = derive_input;
let mut input = derive_input.clone();
input.attrs = args.attrs;

let strip_unknown_attr = |attrs: &mut Vec<syn::Attribute>| {
Expand Down Expand Up @@ -546,22 +547,31 @@ pub fn derive_near_schema(#[allow(unused)] input: TokenStream) -> TokenStream {
}
}

let near_sdk_crate =
if derive_input.attrs.iter().any(|attr| attr.path().is_ident("inside_nearsdk")) {
quote! {crate}
} else {
quote! {::near_sdk}
};
let string_borsh_crate = quote! {#near_sdk_crate::borsh}.to_string();
let string_schemars_crate = quote! {#near_sdk_crate::schemars}.to_string();

// <unspecified> or #[abi(json)]
let json_schema = json_schema || !borsh_schema;

let derive = {
let mut derive = quote! {};
if borsh_schema {
derive = quote! {
#[derive(::near_sdk::borsh::BorshSchema)]
#[borsh(crate = "::near_sdk::borsh")]
#[derive(#near_sdk_crate::borsh::BorshSchema)]
#[borsh(crate = #string_borsh_crate)]
};
}
if json_schema {
derive = quote! {
#derive
#[derive(::near_sdk::schemars::JsonSchema)]
#[schemars(crate = "::near_sdk::schemars")]
#[derive(#near_sdk_crate::schemars::JsonSchema)]
#[schemars(crate = #string_schemars_crate)]
};
}
derive
Expand All @@ -574,13 +584,13 @@ pub fn derive_near_schema(#[allow(unused)] input: TokenStream) -> TokenStream {
let json_impl = if json_schema {
quote! {
#[automatically_derived]
impl ::near_sdk::schemars::JsonSchema for #input_ident_proxy {
impl #generics #near_sdk_crate::schemars::JsonSchema for #input_ident_proxy #generics {
fn schema_name() -> ::std::string::String {
stringify!(#input_ident).to_string()
stringify!(#input_ident #generics).to_string()
}

fn json_schema(gen: &mut ::near_sdk::schemars::gen::SchemaGenerator) -> ::near_sdk::schemars::schema::Schema {
<#input_ident as ::near_sdk::schemars::JsonSchema>::json_schema(gen)
fn json_schema(gen: &mut #near_sdk_crate::schemars::gen::SchemaGenerator) -> #near_sdk_crate::schemars::schema::Schema {
<#input_ident #generics as #near_sdk_crate::schemars::JsonSchema>::json_schema(gen)
}
}
}
Expand All @@ -591,18 +601,18 @@ pub fn derive_near_schema(#[allow(unused)] input: TokenStream) -> TokenStream {
let borsh_impl = if borsh_schema {
quote! {
#[automatically_derived]
impl ::near_sdk::borsh::BorshSchema for #input_ident_proxy {
fn declaration() -> ::near_sdk::borsh::schema::Declaration {
stringify!(#input_ident).to_string()
impl #generics #near_sdk_crate::borsh::BorshSchema for #input_ident_proxy #generics {
fn declaration() -> #near_sdk_crate::borsh::schema::Declaration {
stringify!(#input_ident #generics).to_string()
}

fn add_definitions_recursively(
definitions: &mut ::near_sdk::borsh::__private::maybestd::collections::BTreeMap<
::near_sdk::borsh::schema::Declaration,
::near_sdk::borsh::schema::Definition
definitions: &mut #near_sdk_crate::borsh::__private::maybestd::collections::BTreeMap<
#near_sdk_crate::borsh::schema::Declaration,
#near_sdk_crate::borsh::schema::Definition
>,
) {
<#input_ident as ::near_sdk::borsh::BorshSchema>::add_definitions_recursively(definitions);
<#input_ident #generics as #near_sdk_crate::borsh::BorshSchema>::add_definitions_recursively(definitions);
}
}
}
Expand All @@ -614,7 +624,7 @@ pub fn derive_near_schema(#[allow(unused)] input: TokenStream) -> TokenStream {
#[cfg(not(target_arch = "wasm32"))]
const _: () = {
#[allow(non_camel_case_types)]
type #input_ident_proxy = #input_ident;
type #input_ident_proxy #generics = #input_ident #generics;
{
#derive
#input
Expand Down
16 changes: 4 additions & 12 deletions near-sdk/src/collections/lazy_option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,15 @@ use borsh::{to_vec, BorshDeserialize, BorshSerialize};

use crate::env;
use crate::IntoStorageKey;
#[cfg(feature = "abi")]
use borsh::BorshSchema;
use near_sdk_macros::NearSchema;

const ERR_VALUE_SERIALIZATION: &str = "Cannot serialize value with Borsh";
const ERR_VALUE_DESERIALIZATION: &str = "Cannot deserialize value with Borsh";

/// An persistent lazy option, that stores a value in the storage.
#[cfg(feature = "abi")]
#[derive(BorshSerialize, BorshDeserialize, BorshSchema)]
pub struct LazyOption<T> {
storage_key: Vec<u8>,
#[borsh(skip)]
el: PhantomData<T>,
}

#[cfg(not(feature = "abi"))]
#[derive(BorshSerialize, BorshDeserialize)]
#[derive(BorshSerialize, BorshDeserialize, NearSchema)]
#[inside_nearsdk]
#[abi(borsh)]
pub struct LazyOption<T> {
storage_key: Vec<u8>,
#[borsh(skip)]
Expand Down
16 changes: 4 additions & 12 deletions near-sdk/src/collections/lookup_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,21 @@
//! makes this map more efficient in the number of reads and writes.
use std::marker::PhantomData;

#[cfg(feature = "abi")]
use borsh::BorshSchema;
use borsh::{to_vec, BorshDeserialize, BorshSerialize};

use crate::collections::append_slice;
use crate::{env, IntoStorageKey};
use near_sdk_macros::NearSchema;

const ERR_KEY_SERIALIZATION: &str = "Cannot serialize key with Borsh";
const ERR_VALUE_DESERIALIZATION: &str = "Cannot deserialize value with Borsh";
const ERR_VALUE_SERIALIZATION: &str = "Cannot serialize value with Borsh";

/// An non-iterable implementation of a map that stores its content directly on the trie.
#[cfg(feature = "abi")]
#[derive(BorshSerialize, BorshDeserialize, BorshSchema)]
pub struct LookupMap<K, V> {
key_prefix: Vec<u8>,
#[borsh(skip)]
el: PhantomData<(K, V)>,
}

#[cfg(not(feature = "abi"))]
#[derive(BorshSerialize, BorshDeserialize)]
#[derive(BorshSerialize, BorshDeserialize, NearSchema)]
#[inside_nearsdk]
#[abi(borsh)]
pub struct LookupMap<K, V> {
key_prefix: Vec<u8>,
#[borsh(skip)]
Expand Down

0 comments on commit 2d5fb90

Please sign in to comment.