From 7d18cd052697b69936cc8ec007bd1e99dbcc664b Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Tue, 19 Nov 2024 22:30:50 +0800 Subject: [PATCH 01/30] tmp --- near-sdk-macros/src/lib.rs | 22 ++++++++-- near-sdk/src/lib.rs | 86 +++++++++++++++++++++++++++++++++++++ near-sdk/src/types/error.rs | 1 + 3 files changed, 106 insertions(+), 3 deletions(-) diff --git a/near-sdk-macros/src/lib.rs b/near-sdk-macros/src/lib.rs index 2a9ffaa97..40de3e816 100644 --- a/near-sdk-macros/src/lib.rs +++ b/near-sdk-macros/src/lib.rs @@ -43,9 +43,21 @@ struct NearMacroArgs { inside_nearsdk: Option, } -/// This attribute macro is used to enhance the near_bindgen macro. -/// It is used to add Borsh and Serde derives for serialization and deserialization. -/// It also adds `BorshSchema` and `JsonSchema` if needed +/// This attribute macro is used on a struct and its implementations +/// to generate the necessary code to expose `pub` methods from the contract as well +/// as generating the glue code to be a valid NEAR contract. +/// +/// This macro will generate code to load and deserialize state if the `self` parameter is included +/// as well as saving it back to state if `&mut self` is used. +/// +/// For parameter serialization, this macro will generate a struct with all of the parameters as +/// fields and derive deserialization for it. By default this will be JSON deserialized with `serde` +/// but can be overwritten by using `#[serializer(borsh)]`. +/// +/// `#[near]` will also handle serializing and setting the return value of the +/// function execution based on what type is returned by the function. By default, this will be +/// done through `serde` serialized as JSON, but this can be overwritten using +/// `#[result_serializer(borsh)]`. /// /// If you would like to add Borsh or Serde serialization and deserialization to your contract, /// you can use the abi attribute and pass in the serializers you would like to use. @@ -332,6 +344,10 @@ pub fn near(attr: TokenStream, item: TokenStream) -> TokenStream { /// ))] /// struct Contract {} /// ``` +#[deprecated( + since = "5.7.0", + note = "Use #[near] macro instead which allows to remove boilerplate code" +)] #[proc_macro_attribute] pub fn near_bindgen(attr: TokenStream, item: TokenStream) -> TokenStream { if attr.to_string().contains("event_json") { diff --git a/near-sdk/src/lib.rs b/near-sdk/src/lib.rs index 85da47a82..61dd5bf9b 100644 --- a/near-sdk/src/lib.rs +++ b/near-sdk/src/lib.rs @@ -1,3 +1,89 @@ +//! # `near-sdk` +//! +//! `near-sdk` is a Rust toolkit for developing smart contracts on the [NEAR blockchain](https://near.org). +//! It provides abstractions, macros, and utilities to make building robust and secure contracts easy. +//! More information on how to develop smart contracts can be found in the [NEAR documentation](https://docs.near.org/build/smart-contracts/what-is). +//! With near-sdk you can create DeFi applications, NFTs and marketplaces, DAOs, gaming and metaverse apps, and much more. +//! +//! ## Features +//! +//! - **State Management:** Simplified handling of contract state with serialization via [Borsh](https://borsh.io) or JSON. +//! - **Initialization methods** We can define an initialization method that can be used to initialize the state of the contract. #[init] macro verifies that the contract has not been initialized yet (the contract state doesn't exist) and will panic otherwise. +//! - **Payable methods** We can allow methods to accept token transfer together with the function call with #[payable] macro. +//! - **Private methods** #[private] macro makes it possible to define private methods that can't be called from the outside of the contract. +//! - **Cross-Contract Calls:** Support for asynchronous interactions between contracts. +//! - **Unit Testing:** Built-in support for testing contracts in a Rust environment. +//! - **WASM Compilation:** Compile Rust code to WebAssembly (WASM) for execution on the NEAR runtime. +//! +//! ## Quick Start +//! +//! Add `near-sdk` to your `Cargo.toml`: +//! +//! ```toml +//! [dependencies] +//! near-sdk = "5.6.0" +//! ``` +//! +//! ### Example: Counter Smart Contract +//! +//! Below is an example of a simple counter contract that increments and retrieves a value: +//! +//! ```rust +//! use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; +//! use near_sdk::{env, near_bindgen}; +//! +//! #[near_bindgen] +//! #[derive(Default, BorshDeserialize, BorshSerialize)] +//! pub struct Counter { +//! value: i32, +//! } +//! +//! #[near_bindgen] +//! impl Counter { +//! /// Increment the counter by one. +//! pub fn increment(&mut self) { +//! self.value += 1; +//! env::log_str(&format!("Counter incremented to: {}", self.value)); +//! } +//! +//! /// Get the current value of the counter. +//! pub fn get(&self) -> i32 { +//! self.value +//! } +//! } +//! ``` +//! +//! ### Compiling to WASM +//! +//! Build your contract for the NEAR blockchain: +//! +//! ```bash +//! cargo near build +//! ``` +//! +//! ### Running Unit Tests +//! +//! Use the following testing setup: +//! +//! ```rust +//! #[cfg(test)] +//! mod tests { +//! use super::*; +//! +//! #[test] +//! fn increment_works() { +//! let mut counter = Counter::default(); +//! counter.increment(); +//! assert_eq!(counter.get(), 1); +//! } +//! } +//! ``` +//! +//! Run tests using: +//! ```bash +//! cargo test +//! ``` + //* Clippy is giving false positive warnings for this in 1.57 version. Remove this if fixed. //* https://github.com/rust-lang/rust-clippy/issues/8091 #![allow(clippy::redundant_closure)] diff --git a/near-sdk/src/types/error.rs b/near-sdk/src/types/error.rs index b72be55cd..619c6a743 100644 --- a/near-sdk/src/types/error.rs +++ b/near-sdk/src/types/error.rs @@ -1,6 +1,7 @@ /// Enables contract runtime to panic with the given type. Any error type used in conjunction /// with `#[handle_result]` has to implement this trait. /// +/// Example: /// ``` /// use near_sdk::FunctionError; /// From 3803218bf6cdbb16fa0e8d6255d54657dc3e2ba1 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Wed, 20 Nov 2024 15:39:27 +0800 Subject: [PATCH 02/30] tmp --- near-sdk-macros/src/lib.rs | 207 +++++++++++++++---------------------- 1 file changed, 84 insertions(+), 123 deletions(-) diff --git a/near-sdk-macros/src/lib.rs b/near-sdk-macros/src/lib.rs index 40de3e816..913cede9c 100644 --- a/near-sdk-macros/src/lib.rs +++ b/near-sdk-macros/src/lib.rs @@ -49,8 +49,8 @@ struct NearMacroArgs { /// /// This macro will generate code to load and deserialize state if the `self` parameter is included /// as well as saving it back to state if `&mut self` is used. -/// -/// For parameter serialization, this macro will generate a struct with all of the parameters as +/// +/// If the macro is used with Impl section, for parameter serialization, this macro will generate a struct with all of the parameters as /// fields and derive deserialization for it. By default this will be JSON deserialized with `serde` /// but can be overwritten by using `#[serializer(borsh)]`. /// @@ -58,9 +58,11 @@ struct NearMacroArgs { /// function execution based on what type is returned by the function. By default, this will be /// done through `serde` serialized as JSON, but this can be overwritten using /// `#[result_serializer(borsh)]`. -/// -/// If you would like to add Borsh or Serde serialization and deserialization to your contract, -/// you can use the abi attribute and pass in the serializers you would like to use. +/// +/// If the macro is used with struct or enum, it will make the struct or enum serializable with either +/// Borsh or Json depending on serializers passed. Use #[near(serializers=[borsh])] to make it serializable with Borsh. +/// Or use #[near(serializers=[json])] to make it serializable with Json. By default, borsh is used. +/// You can also specify both and none. BorshSchema or JsonSchema are always generated. /// /// # Example /// @@ -70,42 +72,88 @@ struct NearMacroArgs { /// pub name: String, /// } /// ``` -/// effectively becomes: -/// ```ignore -/// use borsh::{BorshSerialize, BorshDeserialize}; -/// use serde::{Serialize, Deserialize}; -/// use near_sdk_macro::NearSchema; -/// #[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, NearSchema)] -/// #[borsh(crate = "near_sdk::borsh")] -/// #[serde(crate = "near_sdk::serde")] -/// struct MyStruct { -/// pub name: String, -/// } -/// ``` -/// Please note that `BorshSchema` and `JsonSchema` are added inside NearSchema whenever you use near macro for struct or enum. -/// By default, if no serializers are passed, Borsh is used. -/// /// If you want this struct to be a contract state, you can pass in the contract_state argument. -/// /// # Example /// ```ignore +/// use near_sdk::near; +/// /// #[near(contract_state)] -/// struct MyStruct { -/// pub name: String, +/// pub struct Contract { +/// data: i8, +/// } +/// +/// #[near] +/// impl Contract { +/// pub fn some_function(&self) {} /// } /// ``` -/// becomes: +/// As well, the macro supports arguments like `event_json` and `contract_metadata`. +/// +/// Events Standard: +/// +/// By passing `event_json` as an argument `near_bindgen` will generate the relevant code to format events +/// according to NEP-297 +/// +/// For parameter serialization, this macro will generate a wrapper struct to include the NEP-297 standard fields `standard` and `version +/// as well as include serialization reformatting to include the `event` and `data` fields automatically. +/// The `standard` and `version` values must be included in the enum and variant declaration (see example below). +/// By default this will be JSON deserialized with `serde` +/// +/// +/// # Examples +/// /// ```ignore -/// #[near_bindgen] -/// #[derive(BorshSerialize, BorshDeserialize, NearSchema)] -/// #[borsh(crate = "near_sdk::borsh")] -/// struct MyStruct { -/// pub name: String, +/// use near_sdk::near; +/// +/// #[near(event_json(standard = "nepXXX"))] +/// pub enum MyEvents { +/// #[event_version("1.0.0")] +/// Swap { token_in: AccountId, token_out: AccountId, amount_in: u128, amount_out: u128 }, +/// +/// #[event_version("2.0.0")] +/// StringEvent(String), +/// +/// #[event_version("3.0.0")] +/// EmptyEvent +/// } +/// +/// #[near] +/// impl Contract { +/// pub fn some_function(&self) { +/// MyEvents::StringEvent( +/// String::from("some_string") +/// ).emit(); +/// } +/// /// } /// ``` /// -/// As well, the macro supports arguments like `event_json` and `contract_metadata`. +/// Contract Source Metadata Standard: /// +/// By using `contract_metadata` as an argument `near` will populate the contract metadata +/// according to [`NEP-330`]() standard. This still applies even when `#[near]` is used without +/// any arguments. +/// +/// All fields(version, link, standard) are optional and will be populated with defaults from the Cargo.toml file if not specified. +/// +/// The `contract_source_metadata()` view function will be added and can be used to retrieve the source metadata. +/// Also, the source metadata will be stored as a constant, `CONTRACT_SOURCE_METADATA`, in the contract code. +/// +/// # Examples +/// ```ignore +/// use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; +/// use near_sdk::near; +/// +/// #[derive(Default, BorshSerialize, BorshDeserialize)] +/// #[near(contract_metadata( +/// version = "39f2d2646f2f60e18ab53337501370dc02a5661c", +/// link = "https://github.com/near-examples/nft-tutorial", +/// standard(standard = "nep330", version = "1.1.0"), +/// standard(standard = "nep171", version = "1.0.0"), +/// standard(standard = "nep177", version = "2.0.0"), +/// ))] +/// struct Contract {} +/// ``` #[proc_macro_attribute] pub fn near(attr: TokenStream, item: TokenStream) -> TokenStream { if attr.to_string().contains("event_json") { @@ -247,103 +295,16 @@ pub fn near(attr: TokenStream, item: TokenStream) -> TokenStream { TokenStream::from(expanded) } -/// This attribute macro is used on a struct and its implementations -/// to generate the necessary code to expose `pub` methods from the contract as well -/// as generating the glue code to be a valid NEAR contract. -/// -/// This macro will generate code to load and deserialize state if the `self` parameter is included -/// as well as saving it back to state if `&mut self` is used. -/// -/// For parameter serialization, this macro will generate a struct with all of the parameters as -/// fields and derive deserialization for it. By default this will be JSON deserialized with `serde` -/// but can be overwritten by using `#[serializer(borsh)]`. -/// -/// `#[near_bindgen]` will also handle serializing and setting the return value of the -/// function execution based on what type is returned by the function. By default, this will be -/// done through `serde` serialized as JSON, but this can be overwritten using -/// `#[result_serializer(borsh)]`. -/// -/// # Examples -/// +/// This macro is deprecated. Use #[near] instead. The difference between #[near] and #[near_bindgen] is that +/// with #[near_bindgen] you have to manually add boilerplate code for structs and enums so that they become Json- and Borsh-serializable: /// ```ignore -/// use near_sdk::near_bindgen; -/// -/// #[near_bindgen] -/// pub struct Contract { -/// data: i8, -/// } -/// /// #[near_bindgen] -/// impl Contract { -/// pub fn some_function(&self) {} -/// } -/// ``` -/// -/// Events Standard: -/// -/// By passing `event_json` as an argument `near_bindgen` will generate the relevant code to format events -/// according to NEP-297 -/// -/// For parameter serialization, this macro will generate a wrapper struct to include the NEP-297 standard fields `standard` and `version -/// as well as include serialization reformatting to include the `event` and `data` fields automatically. -/// The `standard` and `version` values must be included in the enum and variant declaration (see example below). -/// By default this will be JSON deserialized with `serde` -/// -/// -/// # Examples -/// -/// ```ignore -/// use near_sdk::near_bindgen; -/// -/// #[near_bindgen(event_json(standard = "nepXXX"))] -/// pub enum MyEvents { -/// #[event_version("1.0.0")] -/// Swap { token_in: AccountId, token_out: AccountId, amount_in: u128, amount_out: u128 }, -/// -/// #[event_version("2.0.0")] -/// StringEvent(String), -/// -/// #[event_version("3.0.0")] -/// EmptyEvent -/// } -/// -/// #[near_bindgen] -/// impl Contract { -/// pub fn some_function(&self) { -/// MyEvents::StringEvent( -/// String::from("some_string") -/// ).emit(); -/// } -/// +/// #[derive(BorshSerialize, BorshDeserialize, NearSchema)] +/// #[borsh(crate = "near_sdk::borsh")] +/// struct MyStruct { +/// pub name: String, /// } /// ``` -/// -/// Contract Source Metadata Standard: -/// -/// By using `contract_metadata` as an argument `near_bindgen` will populate the contract metadata -/// according to [`NEP-330`]() standard. This still applies even when `#[near_bindgen]` is used without -/// any arguments. -/// -/// All fields(version, link, standard) are optional and will be populated with defaults from the Cargo.toml file if not specified. -/// -/// The `contract_source_metadata()` view function will be added and can be used to retrieve the source metadata. -/// Also, the source metadata will be stored as a constant, `CONTRACT_SOURCE_METADATA`, in the contract code. -/// -/// # Examples -/// ```ignore -/// use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; -/// use near_sdk::near_bindgen; -/// -/// #[derive(Default, BorshSerialize, BorshDeserialize)] -/// #[near_bindgen(contract_metadata( -/// version = "39f2d2646f2f60e18ab53337501370dc02a5661c", -/// link = "https://github.com/near-examples/nft-tutorial", -/// standard(standard = "nep330", version = "1.1.0"), -/// standard(standard = "nep171", version = "1.0.0"), -/// standard(standard = "nep177", version = "2.0.0"), -/// ))] -/// struct Contract {} -/// ``` #[deprecated( since = "5.7.0", note = "Use #[near] macro instead which allows to remove boilerplate code" From d1015f09439579bbb60efb2d52d3dd4442481ff6 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Wed, 20 Nov 2024 16:57:34 +0800 Subject: [PATCH 03/30] nearschema --- near-sdk-macros/src/lib.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/near-sdk-macros/src/lib.rs b/near-sdk-macros/src/lib.rs index 913cede9c..4e417487f 100644 --- a/near-sdk-macros/src/lib.rs +++ b/near-sdk-macros/src/lib.rs @@ -305,11 +305,18 @@ pub fn near(attr: TokenStream, item: TokenStream) -> TokenStream { /// pub name: String, /// } /// ``` +/// Instead of: +/// ```ignore +/// #[near] +/// struct MyStruct { +/// pub name: String, +/// } +/// ``` +#[proc_macro_attribute] #[deprecated( since = "5.7.0", note = "Use #[near] macro instead which allows to remove boilerplate code" )] -#[proc_macro_attribute] pub fn near_bindgen(attr: TokenStream, item: TokenStream) -> TokenStream { if attr.to_string().contains("event_json") { return core_impl::near_events(attr, item); @@ -530,6 +537,9 @@ struct DeriveNearSchema { borsh: Option, } +/// `NearSchema` is a derive macro that generates `BorshSchema` and / or `JsonSchema` implementations. +/// Use #[abi(json)] attribute to generate code for JsonSchema. And #[abi(borsh)] for BorshSchema. +/// You can use both and none as well. #[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"))] From 245c1c965b0e3934857ddebfdda424d195bf00a9 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Wed, 20 Nov 2024 17:29:55 +0800 Subject: [PATCH 04/30] link for store crate, neargas and neartoken types --- near-sdk/src/store/mod.rs | 2 ++ near-sdk/src/types/mod.rs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/near-sdk/src/store/mod.rs b/near-sdk/src/store/mod.rs index ec724474a..0bffd0d5a 100644 --- a/near-sdk/src/store/mod.rs +++ b/near-sdk/src/store/mod.rs @@ -70,6 +70,8 @@ //! - [`LazyOption`](LazyOption): Lazily loaded, optional type that can be used in //! place of a type [`Option`](Option). Will only be loaded when interacted with and will //! persist on [`Drop`]. +//! +//! More information about collections can be found in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/collections) #[cfg(feature = "unstable")] mod lazy; diff --git a/near-sdk/src/types/mod.rs b/near-sdk/src/types/mod.rs index aeaedfba4..6802be8e1 100644 --- a/near-sdk/src/types/mod.rs +++ b/near-sdk/src/types/mod.rs @@ -8,7 +8,9 @@ mod primitives; pub use self::primitives::*; pub use near_account_id::{AccountId, AccountIdRef}; +/// Same as `NearGas` from crate [`near_gas`](https://docs.rs/near-gas/latest/near_gas/) pub use near_gas::NearGas as Gas; +/// Same as `NearToken` from crate [`near_token`](https://docs.rs/near-token/latest/near_token/) pub use near_token::NearToken; mod error; From 34d774f11a0c8cad98a6336c45c254baa903d898 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Wed, 20 Nov 2024 19:01:09 +0800 Subject: [PATCH 05/30] promises in env --- near-sdk/src/environment/env.rs | 61 +++++++++++++++++++++++++++++++++ near-sdk/src/types/mod.rs | 4 +-- 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index e439318d4..ff3a89b35 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -500,6 +500,8 @@ pub fn alt_bn128_pairing_check(value: &[u8]) -> bool { // ################ /// Creates a promise that will execute a method on account with given arguments and attaches /// the given amount and gas. +/// +/// More info about promises in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/crosscontract#promises) pub fn promise_create( account_id: AccountId, function_name: &str, @@ -557,6 +559,26 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { unsafe { PromiseIndex(sys::promise_and(data.as_ptr() as _, promise_indices.len() as _)) } } +/// Create a NEAR promise which will have multiple promise actions inside. +/// +/// Example: +/// ```ignore +/// let target_account = "example.near".to_string(); +/// let promise_index = env::promise_batch_create(&target_account); + +/// // Adding actions to the promise +/// env::promise_batch_action_transfer(promise_index, 10u128); // Transfer 10 NEAR +/// env::promise_batch_action_function_call( +/// promise_index, +/// "method_name".to_string(), // Target method +/// b"{}".to_vec(), // Arguments +/// 0, // Attached deposit +/// 5_000_000_000_000 // Gas for execution +/// ); +/// ``` +/// All actions in a batch are executed in the order they were added. +/// Batched actions act as a unit: they execute in the same receipt, and if any fails, then they all get reverted. +/// More information about batching actions can be found in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/actions) pub fn promise_batch_create(account_id: &AccountId) -> PromiseIndex { let account_id: &str = account_id.as_ref(); unsafe { @@ -564,6 +586,9 @@ pub fn promise_batch_create(account_id: &AccountId) -> PromiseIndex { } } +/// Attach a callback NEAR promise to a batch of NEAR promise actions. +/// +/// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_then(promise_index: PromiseIndex, account_id: &AccountId) -> PromiseIndex { let account_id: &str = account_id.as_ref(); unsafe { @@ -575,10 +600,16 @@ pub fn promise_batch_then(promise_index: PromiseIndex, account_id: &AccountId) - } } +/// Attach a create account promise action to the NEAR promise index with the provided promise index. +/// +/// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_create_account(promise_index: PromiseIndex) { unsafe { sys::promise_batch_action_create_account(promise_index.0) } } +/// Attach a deploy contract promise action to the NEAR promise index with the provided promise index. +/// +/// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_deploy_contract(promise_index: PromiseIndex, code: &[u8]) { unsafe { sys::promise_batch_action_deploy_contract( @@ -589,6 +620,9 @@ pub fn promise_batch_action_deploy_contract(promise_index: PromiseIndex, code: & } } +/// Attach a function call promise action to the NEAR promise index with the provided promise index. +/// +/// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_function_call( promise_index: PromiseIndex, function_name: &str, @@ -609,6 +643,9 @@ pub fn promise_batch_action_function_call( } } +/// Attach a function call with specific gas weight promise action to the NEAR promise index with the provided promise index. +/// +/// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_function_call_weight( promise_index: PromiseIndex, function_name: &str, @@ -631,6 +668,9 @@ pub fn promise_batch_action_function_call_weight( } } +/// Attach a transfer promise action to the NEAR promise index with the provided promise index. +/// +/// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_transfer(promise_index: PromiseIndex, amount: NearToken) { unsafe { sys::promise_batch_action_transfer( @@ -640,6 +680,9 @@ pub fn promise_batch_action_transfer(promise_index: PromiseIndex, amount: NearTo } } +/// Attach a stake promise action to the NEAR promise index with the provided promise index. +/// +/// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_stake( promise_index: PromiseIndex, amount: NearToken, @@ -654,6 +697,10 @@ pub fn promise_batch_action_stake( ) } } + +/// Attach promise action that adds a full access key to the NEAR promise index with the provided promise index. +/// +/// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_add_key_with_full_access( promise_index: PromiseIndex, public_key: &PublicKey, @@ -670,6 +717,8 @@ pub fn promise_batch_action_add_key_with_full_access( } /// This is a short lived function while we migrate between the Balance and the allowance type +/// +/// More info about batching [here](crate::env::promise_batch_create) pub(crate) fn migrate_to_allowance(allowance: NearToken) -> Allowance { Allowance::limited(allowance).unwrap_or(Allowance::Unlimited) } @@ -694,6 +743,9 @@ pub fn promise_batch_action_add_key_with_function_call( ) } +/// Attach promise action that adds a key with function call with specifi allowance to the NEAR promise index with the provided promise index. +/// +/// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_add_key_allowance_with_function_call( promise_index: PromiseIndex, public_key: &PublicKey, @@ -721,6 +773,10 @@ pub fn promise_batch_action_add_key_allowance_with_function_call( ) } } + +/// Attach promise action that deletes the key to the NEAR promise index with the provided promise index. +/// +/// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_delete_key(promise_index: PromiseIndex, public_key: &PublicKey) { unsafe { sys::promise_batch_action_delete_key( @@ -731,6 +787,9 @@ pub fn promise_batch_action_delete_key(promise_index: PromiseIndex, public_key: } } +/// Attach promise action that deletes the account to the NEAR promise index with the provided promise index. +/// +/// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_delete_account( promise_index: PromiseIndex, beneficiary_id: &AccountId, @@ -978,6 +1037,8 @@ pub fn state_read() -> Option { .unwrap_or_else(|_| panic_str("Cannot deserialize the contract state.")) }) } + +/// Writes the specified state to storage. pub fn state_write(state: &T) { let data = match borsh::to_vec(state) { Ok(serialized) => serialized, diff --git a/near-sdk/src/types/mod.rs b/near-sdk/src/types/mod.rs index 6802be8e1..153ac96ac 100644 --- a/near-sdk/src/types/mod.rs +++ b/near-sdk/src/types/mod.rs @@ -8,9 +8,9 @@ mod primitives; pub use self::primitives::*; pub use near_account_id::{AccountId, AccountIdRef}; -/// Same as `NearGas` from crate [`near_gas`](https://docs.rs/near-gas/latest/near_gas/) +/// Same as `NearGas` from crate [`near_gas`](near_gas) pub use near_gas::NearGas as Gas; -/// Same as `NearToken` from crate [`near_token`](https://docs.rs/near-token/latest/near_token/) +/// Same as `NearToken` from crate [`near_token`](near_token) pub use near_token::NearToken; mod error; From 5f0aeb1b938a6687527e357021c8c65b25c424bd Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Wed, 20 Nov 2024 19:24:17 +0800 Subject: [PATCH 06/30] fmt and env intro --- near-sdk-macros/src/lib.rs | 16 +++++++-------- near-sdk/src/environment/env.rs | 36 ++++++++++++++++----------------- near-sdk/src/lib.rs | 6 +++--- near-sdk/src/store/mod.rs | 2 +- 4 files changed, 30 insertions(+), 30 deletions(-) diff --git a/near-sdk-macros/src/lib.rs b/near-sdk-macros/src/lib.rs index 4e417487f..507750d79 100644 --- a/near-sdk-macros/src/lib.rs +++ b/near-sdk-macros/src/lib.rs @@ -49,7 +49,7 @@ struct NearMacroArgs { /// /// This macro will generate code to load and deserialize state if the `self` parameter is included /// as well as saving it back to state if `&mut self` is used. -/// +/// /// If the macro is used with Impl section, for parameter serialization, this macro will generate a struct with all of the parameters as /// fields and derive deserialization for it. By default this will be JSON deserialized with `serde` /// but can be overwritten by using `#[serializer(borsh)]`. @@ -58,10 +58,10 @@ struct NearMacroArgs { /// function execution based on what type is returned by the function. By default, this will be /// done through `serde` serialized as JSON, but this can be overwritten using /// `#[result_serializer(borsh)]`. -/// -/// If the macro is used with struct or enum, it will make the struct or enum serializable with either -/// Borsh or Json depending on serializers passed. Use #[near(serializers=[borsh])] to make it serializable with Borsh. -/// Or use #[near(serializers=[json])] to make it serializable with Json. By default, borsh is used. +/// +/// If the macro is used with struct or enum, it will make the struct or enum serializable with either +/// Borsh or Json depending on serializers passed. Use #[near(serializers=[borsh])] to make it serializable with Borsh. +/// Or use #[near(serializers=[json])] to make it serializable with Json. By default, borsh is used. /// You can also specify both and none. BorshSchema or JsonSchema are always generated. /// /// # Example @@ -295,7 +295,7 @@ pub fn near(attr: TokenStream, item: TokenStream) -> TokenStream { TokenStream::from(expanded) } -/// This macro is deprecated. Use #[near] instead. The difference between #[near] and #[near_bindgen] is that +/// This macro is deprecated. Use #[near] instead. The difference between #[near] and #[near_bindgen] is that /// with #[near_bindgen] you have to manually add boilerplate code for structs and enums so that they become Json- and Borsh-serializable: /// ```ignore /// #[near_bindgen] @@ -537,8 +537,8 @@ struct DeriveNearSchema { borsh: Option, } -/// `NearSchema` is a derive macro that generates `BorshSchema` and / or `JsonSchema` implementations. -/// Use #[abi(json)] attribute to generate code for JsonSchema. And #[abi(borsh)] for BorshSchema. +/// `NearSchema` is a derive macro that generates `BorshSchema` and / or `JsonSchema` implementations. +/// Use #[abi(json)] attribute to generate code for JsonSchema. And #[abi(borsh)] for BorshSchema. /// You can use both and none as well. #[proc_macro_derive(NearSchema, attributes(abi, serde, borsh, schemars, validate, inside_nearsdk))] pub fn derive_near_schema(#[allow(unused)] input: TokenStream) -> TokenStream { diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index ff3a89b35..d5474837f 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -1,5 +1,5 @@ -//! Blockchain-specific methods available to the smart contract. This is a wrapper around a -//! low-level `BlockchainInterface`. Unless you know what you are doing prefer using `env::*` +//! Blockchain-specific methods available to the smart contract that allow to interact with NEAR runtime. +//! This is a wrapper around a low-level [`near_sys`](near_sys). Unless you know what you are doing prefer using `env::*` //! whenever possible. In case of cross-contract calls prefer using even higher-level API available //! through `callback_args`, `callback_args_vec`, `ext_contract`, `Promise`, and `PromiseOrValue`. @@ -76,7 +76,7 @@ pub(crate) unsafe fn read_register_fixed_64(register_id: u64) -> [u8; 64] { } /// Replaces the current low-level blockchain interface accessible through `env::*` with another -/// low-level blockchain interfacr that implements `BlockchainInterface` trait. In most cases you +/// low-level blockchain interface with builtin functions of the NEAR runtime. In most cases you /// want to use `testing_env!` macro to set it. /// /// ``` @@ -500,7 +500,7 @@ pub fn alt_bn128_pairing_check(value: &[u8]) -> bool { // ################ /// Creates a promise that will execute a method on account with given arguments and attaches /// the given amount and gas. -/// +/// /// More info about promises in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/crosscontract#promises) pub fn promise_create( account_id: AccountId, @@ -560,7 +560,7 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { } /// Create a NEAR promise which will have multiple promise actions inside. -/// +/// /// Example: /// ```ignore /// let target_account = "example.near".to_string(); @@ -586,8 +586,8 @@ pub fn promise_batch_create(account_id: &AccountId) -> PromiseIndex { } } -/// Attach a callback NEAR promise to a batch of NEAR promise actions. -/// +/// Attach a callback NEAR promise to a batch of NEAR promise actions. +/// /// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_then(promise_index: PromiseIndex, account_id: &AccountId) -> PromiseIndex { let account_id: &str = account_id.as_ref(); @@ -601,14 +601,14 @@ pub fn promise_batch_then(promise_index: PromiseIndex, account_id: &AccountId) - } /// Attach a create account promise action to the NEAR promise index with the provided promise index. -/// +/// /// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_create_account(promise_index: PromiseIndex) { unsafe { sys::promise_batch_action_create_account(promise_index.0) } } /// Attach a deploy contract promise action to the NEAR promise index with the provided promise index. -/// +/// /// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_deploy_contract(promise_index: PromiseIndex, code: &[u8]) { unsafe { @@ -621,7 +621,7 @@ pub fn promise_batch_action_deploy_contract(promise_index: PromiseIndex, code: & } /// Attach a function call promise action to the NEAR promise index with the provided promise index. -/// +/// /// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_function_call( promise_index: PromiseIndex, @@ -644,7 +644,7 @@ pub fn promise_batch_action_function_call( } /// Attach a function call with specific gas weight promise action to the NEAR promise index with the provided promise index. -/// +/// /// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_function_call_weight( promise_index: PromiseIndex, @@ -669,7 +669,7 @@ pub fn promise_batch_action_function_call_weight( } /// Attach a transfer promise action to the NEAR promise index with the provided promise index. -/// +/// /// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_transfer(promise_index: PromiseIndex, amount: NearToken) { unsafe { @@ -681,7 +681,7 @@ pub fn promise_batch_action_transfer(promise_index: PromiseIndex, amount: NearTo } /// Attach a stake promise action to the NEAR promise index with the provided promise index. -/// +/// /// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_stake( promise_index: PromiseIndex, @@ -699,7 +699,7 @@ pub fn promise_batch_action_stake( } /// Attach promise action that adds a full access key to the NEAR promise index with the provided promise index. -/// +/// /// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_add_key_with_full_access( promise_index: PromiseIndex, @@ -717,7 +717,7 @@ pub fn promise_batch_action_add_key_with_full_access( } /// This is a short lived function while we migrate between the Balance and the allowance type -/// +/// /// More info about batching [here](crate::env::promise_batch_create) pub(crate) fn migrate_to_allowance(allowance: NearToken) -> Allowance { Allowance::limited(allowance).unwrap_or(Allowance::Unlimited) @@ -744,7 +744,7 @@ pub fn promise_batch_action_add_key_with_function_call( } /// Attach promise action that adds a key with function call with specifi allowance to the NEAR promise index with the provided promise index. -/// +/// /// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_add_key_allowance_with_function_call( promise_index: PromiseIndex, @@ -775,7 +775,7 @@ pub fn promise_batch_action_add_key_allowance_with_function_call( } /// Attach promise action that deletes the key to the NEAR promise index with the provided promise index. -/// +/// /// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_delete_key(promise_index: PromiseIndex, public_key: &PublicKey) { unsafe { @@ -788,7 +788,7 @@ pub fn promise_batch_action_delete_key(promise_index: PromiseIndex, public_key: } /// Attach promise action that deletes the account to the NEAR promise index with the provided promise index. -/// +/// /// More info about batching [here](crate::env::promise_batch_create) pub fn promise_batch_action_delete_account( promise_index: PromiseIndex, diff --git a/near-sdk/src/lib.rs b/near-sdk/src/lib.rs index 61dd5bf9b..036941852 100644 --- a/near-sdk/src/lib.rs +++ b/near-sdk/src/lib.rs @@ -3,14 +3,14 @@ //! `near-sdk` is a Rust toolkit for developing smart contracts on the [NEAR blockchain](https://near.org). //! It provides abstractions, macros, and utilities to make building robust and secure contracts easy. //! More information on how to develop smart contracts can be found in the [NEAR documentation](https://docs.near.org/build/smart-contracts/what-is). -//! With near-sdk you can create DeFi applications, NFTs and marketplaces, DAOs, gaming and metaverse apps, and much more. +//! With near-sdk you can create DeFi applications, NFTs and marketplaces, DAOs, gaming and metaverse apps, and much more. //! //! ## Features //! //! - **State Management:** Simplified handling of contract state with serialization via [Borsh](https://borsh.io) or JSON. //! - **Initialization methods** We can define an initialization method that can be used to initialize the state of the contract. #[init] macro verifies that the contract has not been initialized yet (the contract state doesn't exist) and will panic otherwise. -//! - **Payable methods** We can allow methods to accept token transfer together with the function call with #[payable] macro. -//! - **Private methods** #[private] macro makes it possible to define private methods that can't be called from the outside of the contract. +//! - **Payable methods** We can allow methods to accept token transfer together with the function call with #[payable] macro. +//! - **Private methods** #[private] macro makes it possible to define private methods that can't be called from the outside of the contract. //! - **Cross-Contract Calls:** Support for asynchronous interactions between contracts. //! - **Unit Testing:** Built-in support for testing contracts in a Rust environment. //! - **WASM Compilation:** Compile Rust code to WebAssembly (WASM) for execution on the NEAR runtime. diff --git a/near-sdk/src/store/mod.rs b/near-sdk/src/store/mod.rs index 0bffd0d5a..f3909554e 100644 --- a/near-sdk/src/store/mod.rs +++ b/near-sdk/src/store/mod.rs @@ -70,7 +70,7 @@ //! - [`LazyOption`](LazyOption): Lazily loaded, optional type that can be used in //! place of a type [`Option`](Option). Will only be loaded when interacted with and will //! persist on [`Drop`]. -//! +//! //! More information about collections can be found in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/collections) #[cfg(feature = "unstable")] From ed0bdef336cd7896fe38ef6e9d665f4b57b1786d Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Wed, 20 Nov 2024 20:12:20 +0800 Subject: [PATCH 07/30] promise_index and promise structs --- near-sdk/src/promise.rs | 2 ++ near-sdk/src/types/vm_types.rs | 8 +++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/near-sdk/src/promise.rs b/near-sdk/src/promise.rs index 56f03ec33..c99215f9c 100644 --- a/near-sdk/src/promise.rs +++ b/near-sdk/src/promise.rs @@ -222,6 +222,8 @@ impl PromiseJoint { /// .transfer(NearToken::from_yoctonear(1000)) /// .add_full_access_key(env::signer_account_pk()); /// ``` +/// +/// More information about promises in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/crosscontract#promises) pub struct Promise { subtype: PromiseSubtype, should_return: RefCell, diff --git a/near-sdk/src/types/vm_types.rs b/near-sdk/src/types/vm_types.rs index f26fc0fb0..86fc122d7 100644 --- a/near-sdk/src/types/vm_types.rs +++ b/near-sdk/src/types/vm_types.rs @@ -2,7 +2,13 @@ pub use near_vm_runner::logic::types::{PromiseResult as VmPromiseResult, ReturnData}; //* Types from near_vm_logic -/// Promise index that is computed only once. +/// Promise index that is computed only once. It is an internal index that identifies a specific promise (or a sequence of promises) created during the execution of a smart contract. +/// Returned by [`promise_create`](crate::env::promise_create) and can be used to refer this promise in `promise_then`, `promise_batch_create`, and other functions. +/// Example: +/// ```ignore +/// let promise_id = env::promise_create("a.near", "new", b"{}", 0, 1_000_000_000_000); +/// env::promise_then(promise_id, "b.near", "callback", b"{}", 0, 1_000_000_000_000); +/// ``` #[derive(Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Copy, Clone)] pub struct PromiseIndex(pub(crate) u64); From 589d61c576156fcf1676005218946925e6a1541e Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Wed, 20 Nov 2024 21:06:03 +0800 Subject: [PATCH 08/30] storage and functionerror --- near-sdk/src/types/error.rs | 9 +++++++++ near-sdk/src/utils/storage_key_impl.rs | 2 ++ 2 files changed, 11 insertions(+) diff --git a/near-sdk/src/types/error.rs b/near-sdk/src/types/error.rs index 619c6a743..b74019750 100644 --- a/near-sdk/src/types/error.rs +++ b/near-sdk/src/types/error.rs @@ -20,6 +20,15 @@ /// } /// } /// } +/// +/// #[near] +/// impl Contract { +/// // if the Error does not implement FunctionError, the following will not compile with #[handle_result] +/// #[handle_result] +/// pub fn set(&self, value: String) -> Result { +/// Err(Error::NotFound) +/// } +/// } /// ``` pub trait FunctionError { fn panic(&self) -> !; diff --git a/near-sdk/src/utils/storage_key_impl.rs b/near-sdk/src/utils/storage_key_impl.rs index 843f3070f..7fabd8ff0 100644 --- a/near-sdk/src/utils/storage_key_impl.rs +++ b/near-sdk/src/utils/storage_key_impl.rs @@ -1,6 +1,8 @@ /// Converts Self into a [`Vec`] that is used for a storage key through [`into_storage_key`]. /// /// [`into_storage_key`]: IntoStorageKey::into_storage_key +/// +/// More information about storage is in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/storage). pub trait IntoStorageKey { /// Consumes self and returns [`Vec`] bytes which are used as a storage key. fn into_storage_key(self) -> Vec; From 1911c50d702cdc6004a4005201206edc67e464ee Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Wed, 20 Nov 2024 21:54:54 +0800 Subject: [PATCH 09/30] small --- near-sdk-macros/src/lib.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/near-sdk-macros/src/lib.rs b/near-sdk-macros/src/lib.rs index 507750d79..7affa814c 100644 --- a/near-sdk-macros/src/lib.rs +++ b/near-sdk-macros/src/lib.rs @@ -454,6 +454,8 @@ fn process_impl_block( /// fn sum(&self, a: u128, b: u128) -> u128; /// } /// ``` +/// +/// See more information about role of ext_contract in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/crosscontract) #[proc_macro_attribute] pub fn ext_contract(attr: TokenStream, item: TokenStream) -> TokenStream { if let Ok(mut input) = syn::parse::(item) { @@ -538,7 +540,7 @@ struct DeriveNearSchema { } /// `NearSchema` is a derive macro that generates `BorshSchema` and / or `JsonSchema` implementations. -/// Use #[abi(json)] attribute to generate code for JsonSchema. And #[abi(borsh)] for BorshSchema. +/// Use `#[abi(json)]` attribute to generate code for `JsonSchema`. And `#[abi(borsh)]` for `BorshSchema`. /// You can use both and none as well. #[proc_macro_derive(NearSchema, attributes(abi, serde, borsh, schemars, validate, inside_nearsdk))] pub fn derive_near_schema(#[allow(unused)] input: TokenStream) -> TokenStream { @@ -773,7 +775,9 @@ pub fn derive_no_default(item: TokenStream) -> TokenStream { /// `BorshStorageKey` generates implementation for `BorshIntoStorageKey` trait. /// It allows the type to be passed as a unique prefix for persistent collections. -/// The type should also implement or derive `BorshSerialize` trait. +/// The type should also implement or derive `BorshSerialize` trait. +/// +/// More information about storage keys in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/storage) #[proc_macro_derive(BorshStorageKey)] pub fn borsh_storage_key(item: TokenStream) -> TokenStream { let (name, generics) = if let Ok(input) = syn::parse::(item.clone()) { From b6951e7aebfccdf3e2c0c1ce8944624345c072de Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Fri, 20 Dec 2024 20:32:18 +0700 Subject: [PATCH 10/30] denbite review --- near-sdk-macros/src/lib.rs | 105 +++++++++++++++++++++++++++++-------- near-sdk/src/lib.rs | 5 ++ 2 files changed, 89 insertions(+), 21 deletions(-) diff --git a/near-sdk-macros/src/lib.rs b/near-sdk-macros/src/lib.rs index 7affa814c..c04c4979c 100644 --- a/near-sdk-macros/src/lib.rs +++ b/near-sdk-macros/src/lib.rs @@ -47,33 +47,54 @@ struct NearMacroArgs { /// to generate the necessary code to expose `pub` methods from the contract as well /// as generating the glue code to be a valid NEAR contract. /// +/// ## Example +/// +/// ```ignore +/// #[near(serializers=[borsh, json])] +/// struct MyStruct { +/// pub name: String, +/// } +/// ``` +/// /// This macro will generate code to load and deserialize state if the `self` parameter is included /// as well as saving it back to state if `&mut self` is used. /// +/// # Parameter and result serialization /// If the macro is used with Impl section, for parameter serialization, this macro will generate a struct with all of the parameters as /// fields and derive deserialization for it. By default this will be JSON deserialized with `serde` -/// but can be overwritten by using `#[serializer(borsh)]`. +/// but can be overwritten by using `#[serializer(borsh)]`: +/// ```ignore +/// #[near] +/// impl Adder { +/// #[result_serializer(borsh)] +/// pub fn borsh_parameters(&self, #[serializer(borsh)] a: Pair, #[serializer(borsh)] b: Pair) -> Pair { +/// ... +// } +/// ``` /// /// `#[near]` will also handle serializing and setting the return value of the /// function execution based on what type is returned by the function. By default, this will be /// done through `serde` serialized as JSON, but this can be overwritten using -/// `#[result_serializer(borsh)]`. -/// +/// `#[result_serializer(borsh)]`: +/// ```ignore +/// #[near] +/// impl Adder { +/// #[result_serializer(borsh)] +/// pub fn borsh_parameters(&self) -> Pair { +/// ... +// } +/// ``` +/// +/// # Usage for enum / struct +/// /// If the macro is used with struct or enum, it will make the struct or enum serializable with either -/// Borsh or Json depending on serializers passed. Use #[near(serializers=[borsh])] to make it serializable with Borsh. -/// Or use #[near(serializers=[json])] to make it serializable with Json. By default, borsh is used. +/// Borsh or Json depending on serializers passed. Use `#[near(serializers=[borsh])]` to make it serializable with Borsh. +/// Or use `#[near(serializers=[json])]` to make it serializable with Json. By default, borsh is used. /// You can also specify both and none. BorshSchema or JsonSchema are always generated. /// -/// # Example -/// -/// ```ignore -/// #[near(serializers=[borsh, json])] -/// struct MyStruct { -/// pub name: String, -/// } -/// ``` -/// If you want this struct to be a contract state, you can pass in the contract_state argument. -/// # Example +/// If you want the struct to be a contract state, you can pass in the contract_state argument. +/// +/// ## Example /// ```ignore /// use near_sdk::near; /// @@ -89,7 +110,7 @@ struct NearMacroArgs { /// ``` /// As well, the macro supports arguments like `event_json` and `contract_metadata`. /// -/// Events Standard: +/// # Events Standard: /// /// By passing `event_json` as an argument `near_bindgen` will generate the relevant code to format events /// according to NEP-297 @@ -100,7 +121,7 @@ struct NearMacroArgs { /// By default this will be JSON deserialized with `serde` /// /// -/// # Examples +/// ## Examples /// /// ```ignore /// use near_sdk::near; @@ -128,7 +149,7 @@ struct NearMacroArgs { /// } /// ``` /// -/// Contract Source Metadata Standard: +/// # Contract Source Metadata Standard: /// /// By using `contract_metadata` as an argument `near` will populate the contract metadata /// according to [`NEP-330`]() standard. This still applies even when `#[near]` is used without @@ -139,7 +160,7 @@ struct NearMacroArgs { /// The `contract_source_metadata()` view function will be added and can be used to retrieve the source metadata. /// Also, the source metadata will be stored as a constant, `CONTRACT_SOURCE_METADATA`, in the contract code. /// -/// # Examples +/// ## Examples /// ```ignore /// use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; /// use near_sdk::near; @@ -295,7 +316,7 @@ pub fn near(attr: TokenStream, item: TokenStream) -> TokenStream { TokenStream::from(expanded) } -/// This macro is deprecated. Use #[near] instead. The difference between #[near] and #[near_bindgen] is that +/// This macro is deprecated. Use [#[near]](./attr.near.html) instead. The difference between #[near] and #[near_bindgen] is that /// with #[near_bindgen] you have to manually add boilerplate code for structs and enums so that they become Json- and Borsh-serializable: /// ```ignore /// #[near_bindgen] @@ -443,7 +464,7 @@ fn process_impl_block( /// Each of these static methods takes positional arguments defined by the Trait, /// then the receiver_id, the attached deposit and the amount of gas and returns a new Promise. /// -/// # Examples +/// ## Examples /// /// ```ignore /// use near_sdk::ext_contract; @@ -453,6 +474,16 @@ fn process_impl_block( /// fn mult(&self, a: u64, b: u64) -> u128; /// fn sum(&self, a: u128, b: u128) -> u128; /// } +/// +/// #[near] +/// impl Contract { +/// pub fn multiply_by_five(&mut self, number: u64) -> Promise { +/// ext_calculator::ext(self.calculator_account.clone()) +/// .with_static_gas(Gas::from_tgas(5)) +/// .mult(number, 5) +/// } +/// } +/// /// ``` /// /// See more information about role of ext_contract in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/crosscontract) @@ -542,6 +573,15 @@ struct DeriveNearSchema { /// `NearSchema` is a derive macro that generates `BorshSchema` and / or `JsonSchema` implementations. /// Use `#[abi(json)]` attribute to generate code for `JsonSchema`. And `#[abi(borsh)]` for `BorshSchema`. /// You can use both and none as well. +/// ## Example +/// ```ignore +/// #[derive(NearSchema)] +/// #[abi(borsh)] +/// struct Value { +/// field: InnerValue, +/// } +/// ``` +/// In this example, BorshSchema will be generated for `Value` struct. #[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"))] @@ -778,6 +818,29 @@ pub fn derive_no_default(item: TokenStream) -> TokenStream { /// The type should also implement or derive `BorshSerialize` trait. /// /// More information about storage keys in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/storage) +/// ## Example +/// ```ignore +/// #[derive(BorshSerialize, BorshDeserialize, BorshStorageKey)] +/// #[borsh(crate = "near_sdk::borsh")] +/// pub enum StorageKey { +/// Messages, +/// } +/// +/// // Define the contract structure +/// #[near(contract_state)] +/// pub struct Contract { +/// messages: Vector +/// } +/// +/// // Define the default, which automatically initializes the contract +/// impl Default for Contract { +/// fn default() -> Self { +/// Self { +/// messages: Vector::new(StorageKey::Messages) +/// } +/// } +/// } +/// ``` #[proc_macro_derive(BorshStorageKey)] pub fn borsh_storage_key(item: TokenStream) -> TokenStream { let (name, generics) = if let Ok(input) = syn::parse::(item.clone()) { diff --git a/near-sdk/src/lib.rs b/near-sdk/src/lib.rs index 036941852..be9c7df54 100644 --- a/near-sdk/src/lib.rs +++ b/near-sdk/src/lib.rs @@ -55,6 +55,11 @@ //! //! ### Compiling to WASM //! +//! Install cargo near in case if you don't have it: +//! ```bash +//! cargo install --locked cargo-near +//! ``` +//! //! Build your contract for the NEAR blockchain: //! //! ```bash From feaa1817ec98eaaa2904a7d442a85ee65e9ea512 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Fri, 20 Dec 2024 22:15:19 +0700 Subject: [PATCH 11/30] comments from PR 1259 --- near-sdk/Cargo.toml | 2 +- near-sdk/src/environment/env.rs | 30 +++++++++++++++++++++++++++++- near-sdk/src/promise.rs | 16 ++++++++++++++++ near-sdk/src/utils/mod.rs | 2 ++ 4 files changed, 48 insertions(+), 2 deletions(-) diff --git a/near-sdk/Cargo.toml b/near-sdk/Cargo.toml index 853cc17a0..05fe7b46d 100644 --- a/near-sdk/Cargo.toml +++ b/near-sdk/Cargo.toml @@ -98,4 +98,4 @@ __abi-generate = ["abi", "near-sdk-macros/__abi-generate"] __macro-docs = [] [package.metadata.docs.rs] -features = ["unstable", "legacy", "unit-testing", "__macro-docs"] +features = ["unstable", "legacy", "unit-testing", "__macro-docs", "near-primitives", "near-vm-runner"] diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index d7ee2abad..9d9c164da 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -225,6 +225,7 @@ fn assert_valid_account_id(bytes: Vec) -> AccountId { /// /// assert_eq!(input(), Some(Vec::new())); /// ``` +/// See an example here [here](https://github.com/near-examples/update-migrate-rust/blob/a1a326de73c152831f93fbf6d90932e13a08b89f/self-updates/update/src/update.rs#L19) pub fn input() -> Option> { try_method_into_register!(input) } @@ -753,6 +754,9 @@ pub fn alt_bn128_pairing_check(value: &[u8]) -> bool { /// ``` /// /// More info about promises in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/crosscontract#promises) +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_create`] +/// Example usages of this low-level api are and +/// pub fn promise_create( account_id: AccountId, function_name: &str, @@ -775,7 +779,7 @@ pub fn promise_create( } } -/// Attaches the callback that is executed after promise pointed by `promise_idx` is complete. +/// Attaches the callback (which is a [`near_primitives::action::FunctionCallAction`]) that is executed after promise pointed by `promise_idx` is complete. /// /// # Examples /// ``` @@ -805,6 +809,8 @@ pub fn promise_create( /// Gas::from_tgas(30) /// ); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_then`] +/// Example usages of this low-level api are and pub fn promise_then( promise_idx: PromiseIndex, account_id: AccountId, @@ -860,6 +866,7 @@ pub fn promise_then( /// /// let chained_promise = promise_and(&[promise1, promise2]); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_and`] pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { let mut data = vec![0u8; size_of_val(promise_indices)]; for i in 0..promise_indices.len() { @@ -899,6 +906,8 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { /// All actions in a batch are executed in the order they were added. /// Batched actions act as a unit: they execute in the same receipt, and if any fails, then they all get reverted. /// More information about batching actions can be found in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/actions) +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_batch_create`] +/// See example of usage [here](https://github.com/near/near-sdk-rs/blob/master/examples/factory-contract/low-level/src/lib.rs) pub fn promise_batch_create(account_id: &AccountId) -> PromiseIndex { let account_id: &str = account_id.as_ref(); unsafe { @@ -931,6 +940,7 @@ pub fn promise_batch_create(account_id: &AccountId) -> PromiseIndex { /// Attach a callback NEAR promise to a batch of NEAR promise actions. /// /// More info about batching [here](crate::env::promise_batch_create) +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_batch_then`] pub fn promise_batch_then(promise_index: PromiseIndex, account_id: &AccountId) -> PromiseIndex { let account_id: &str = account_id.as_ref(); unsafe { @@ -957,6 +967,8 @@ pub fn promise_batch_then(promise_index: PromiseIndex, account_id: &AccountId) - /// /// promise_batch_action_create_account(promise); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_batch_action_create_account`] +/// See example of usage [here](https://github.com/near/near-sdk-rs/blob/master/examples/factory-contract/low-level/src/lib.rs) pub fn promise_batch_action_create_account(promise_index: PromiseIndex) { unsafe { sys::promise_batch_action_create_account(promise_index.0) } } @@ -977,6 +989,8 @@ pub fn promise_batch_action_create_account(promise_index: PromiseIndex) { /// let code = [0; 1487]; /// promise_batch_action_deploy_contract(promise, &code); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_batch_action_deploy_contract`] +/// See example of usage [here](https://github.com/near/near-sdk-rs/blob/master/examples/factory-contract/low-level/src/lib.rs) pub fn promise_batch_action_deploy_contract(promise_index: PromiseIndex, code: &[u8]) { unsafe { sys::promise_batch_action_deploy_contract( @@ -1009,6 +1023,7 @@ pub fn promise_batch_action_deploy_contract(promise_index: PromiseIndex, code: & /// Gas::from_tgas(30) /// ); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_batch_action_function_call`] pub fn promise_batch_action_function_call( promise_index: PromiseIndex, function_name: &str, @@ -1052,6 +1067,7 @@ pub fn promise_batch_action_function_call( /// GasWeight(1) /// ); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_batch_action_function_call_weight`] pub fn promise_batch_action_function_call_weight( promise_index: PromiseIndex, function_name: &str, @@ -1092,6 +1108,8 @@ pub fn promise_batch_action_function_call_weight( /// NearToken::from_near(1), /// ); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_batch_action_transfer`] +/// See example of usage [here](https://github.com/near/near-sdk-rs/blob/master/examples/factory-contract/low-level/src/lib.rs) pub fn promise_batch_action_transfer(promise_index: PromiseIndex, amount: NearToken) { unsafe { sys::promise_batch_action_transfer( @@ -1121,6 +1139,7 @@ pub fn promise_batch_action_transfer(promise_index: PromiseIndex, amount: NearTo /// &pk /// ); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_batch_action_stake`] pub fn promise_batch_action_stake( promise_index: PromiseIndex, amount: NearToken, @@ -1158,6 +1177,8 @@ pub fn promise_batch_action_stake( /// nonce /// ); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_batch_action_add_key_with_full_access`] +/// See example of usage [here](https://github.com/near/near-sdk-rs/blob/master/examples/factory-contract/low-level/src/lib.rs) pub fn promise_batch_action_add_key_with_full_access( promise_index: PromiseIndex, public_key: &PublicKey, @@ -1316,6 +1337,7 @@ pub fn promise_batch_action_add_key_allowance_with_function_call( /// &pk /// ); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_batch_action_delete_key`] pub fn promise_batch_action_delete_key(promise_index: PromiseIndex, public_key: &PublicKey) { unsafe { sys::promise_batch_action_delete_key( @@ -1344,6 +1366,7 @@ pub fn promise_batch_action_delete_key(promise_index: PromiseIndex, public_key: /// &AccountId::from_str("beneficiary.near").unwrap() /// ); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_batch_action_delete_account`] pub fn promise_batch_action_delete_account( promise_index: PromiseIndex, beneficiary_id: &AccountId, @@ -1368,6 +1391,7 @@ pub fn promise_batch_action_delete_account( /// /// assert_eq!(promise_results_count(), 0); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_results_count`] pub fn promise_results_count() -> u64 { unsafe { sys::promise_results_count() } } @@ -1396,6 +1420,7 @@ pub fn promise_results_count() -> u64 { /// } /// }; /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_result`] pub fn promise_result(result_idx: u64) -> PromiseResult { match promise_result_internal(result_idx) { Ok(()) => { @@ -1436,6 +1461,7 @@ pub(crate) fn promise_result_internal(result_idx: u64) -> Result<(), PromiseErro /// /// promise_return(promise); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_return`] pub fn promise_return(promise_idx: PromiseIndex) { unsafe { sys::promise_return(promise_idx.0) } } @@ -1486,6 +1512,7 @@ pub fn promise_return(promise_idx: PromiseIndex) { /// }).to_string().into_bytes().as_slice() /// ); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_yield_create`] pub fn promise_yield_create( function_name: &str, arguments: &[u8], @@ -1550,6 +1577,7 @@ pub fn promise_yield_create( /// }).to_string().into_bytes().as_slice() /// ); /// ``` +/// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_yield_resume`] pub fn promise_yield_resume(data_id: &CryptoHash, data: &[u8]) -> bool { unsafe { sys::promise_yield_resume( diff --git a/near-sdk/src/promise.rs b/near-sdk/src/promise.rs index c99215f9c..5862c709f 100644 --- a/near-sdk/src/promise.rs +++ b/near-sdk/src/promise.rs @@ -251,6 +251,7 @@ enum PromiseSubtype { impl Promise { /// Create a promise that acts on the given account. + /// Uses low-level [`crate::env::promise_batch_create`] pub fn new(account_id: AccountId) -> Self { Self { subtype: PromiseSubtype::Single(Rc::new(PromiseSingle { @@ -274,16 +275,19 @@ impl Promise { } /// Create account on which this promise acts. + /// Uses low-level [`crate::env::promise_batch_action_create_account`] pub fn create_account(self) -> Self { self.add_action(PromiseAction::CreateAccount) } /// Deploy a smart contract to the account on which this promise acts. + /// Uses low-level [`crate::env::promise_batch_action_deploy_contract`] pub fn deploy_contract(self, code: Vec) -> Self { self.add_action(PromiseAction::DeployContract { code }) } /// A low-level interface for making a function call to the account that this promise acts on. + /// Uses low-level [`crate::env::promise_batch_action_function_call`] pub fn function_call( self, function_name: String, @@ -297,6 +301,7 @@ impl Promise { /// A low-level interface for making a function call to the account that this promise acts on. /// unlike [`Promise::function_call`], this function accepts a weight to use relative unused gas /// on this function call at the end of the scheduling method execution. + /// Uses low-level [`crate::env::promise_batch_action_function_call_weight`] pub fn function_call_weight( self, function_name: String, @@ -315,21 +320,25 @@ impl Promise { } /// Transfer tokens to the account that this promise acts on. + /// Uses low-level [`crate::env::promise_batch_action_transfer`] pub fn transfer(self, amount: NearToken) -> Self { self.add_action(PromiseAction::Transfer { amount }) } /// Stake the account for the given amount of tokens using the given public key. + /// Uses low-level [`crate::env::promise_batch_action_stake`] pub fn stake(self, amount: NearToken, public_key: PublicKey) -> Self { self.add_action(PromiseAction::Stake { amount, public_key }) } /// Add full access key to the given account. + /// Uses low-level [`crate::env::promise_batch_action_add_key_with_full_access`] pub fn add_full_access_key(self, public_key: PublicKey) -> Self { self.add_full_access_key_with_nonce(public_key, 0) } /// Add full access key to the given account with a provided nonce. + /// Uses low-level [`crate::env::promise_batch_action_add_key_with_full_access`] pub fn add_full_access_key_with_nonce(self, public_key: PublicKey, nonce: u64) -> Self { self.add_action(PromiseAction::AddFullAccessKey { public_key, nonce }) } @@ -337,6 +346,7 @@ impl Promise { /// Add an access key that is restricted to only calling a smart contract on some account using /// only a restricted set of methods. Here `function_names` is a comma separated list of methods, /// e.g. `"method_a,method_b".to_string()`. + /// Uses low-level [`crate::env::promise_batch_action_add_key_with_function_call`] pub fn add_access_key_allowance( self, public_key: PublicKey, @@ -366,6 +376,7 @@ impl Promise { } /// Add an access key with a provided nonce. + /// Uses low-level [`crate::env::promise_batch_action_add_key_with_function_call`] pub fn add_access_key_allowance_with_nonce( self, public_key: PublicKey, @@ -403,11 +414,13 @@ impl Promise { } /// Delete access key from the given account. + /// Uses low-level [`crate::env::promise_batch_action_delete_key`] pub fn delete_key(self, public_key: PublicKey) -> Self { self.add_action(PromiseAction::DeleteKey { public_key }) } /// Delete the given account. + /// Uses low-level [`crate::env::promise_batch_action_delete_account`] pub fn delete_account(self, beneficiary_id: AccountId) -> Self { self.add_action(PromiseAction::DeleteAccount { beneficiary_id }) } @@ -425,6 +438,7 @@ impl Promise { /// let p3 = p1.and(p2); /// // p3.create_account(); /// ``` + /// Uses low-level [`crate::env::promise_and`] pub fn and(self, other: Promise) -> Promise { Promise { subtype: PromiseSubtype::Joint(Rc::new(PromiseJoint { @@ -449,6 +463,7 @@ impl Promise { /// let p4 = Promise::new("eva_near".parse().unwrap()).create_account(); /// p1.then(p2).and(p3).then(p4); /// ``` + /// Uses low-level [`crate::env::promise_batch_then`] pub fn then(self, mut other: Promise) -> Promise { match &mut other.subtype { PromiseSubtype::Single(x) => { @@ -491,6 +506,7 @@ impl Promise { /// } /// } /// ``` + /// Makes the promise to use low-level [`crate::env::promise_return`]. #[allow(clippy::wrong_self_convention)] pub fn as_return(self) -> Self { *self.should_return.borrow_mut() = true; diff --git a/near-sdk/src/utils/mod.rs b/near-sdk/src/utils/mod.rs index 6ae2fbf1a..a1ced05cb 100644 --- a/near-sdk/src/utils/mod.rs +++ b/near-sdk/src/utils/mod.rs @@ -90,6 +90,7 @@ pub fn assert_one_yocto() { /// Returns true if promise was successful. /// Fails if called outside a callback that received 1 promise result. +/// Uses low-level [`crate::env::promise_results_count`]. pub fn is_promise_success() -> bool { require!(env::promise_results_count() == 1, "Contract expected a result on the callback"); env::promise_result_internal(0).is_ok() @@ -97,6 +98,7 @@ pub fn is_promise_success() -> bool { /// Returns the result of the promise if successful. Otherwise returns None. /// Fails if called outside a callback that received 1 promise result. +/// Uses low-level [`crate::env::promise_results_count`] and [`crate::env::promise_result`]. pub fn promise_result_as_success() -> Option> { require!(env::promise_results_count() == 1, "Contract expected a result on the callback"); match env::promise_result(0) { From 8d178bde37c9c418760e832e1d637dea728f786d Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Fri, 20 Dec 2024 22:15:53 +0700 Subject: [PATCH 12/30] fmt --- near-sdk-macros/src/lib.rs | 24 ++++++++++++------------ near-sdk/src/environment/env.rs | 2 +- near-sdk/src/lib.rs | 2 +- near-sdk/src/types/error.rs | 2 +- near-sdk/src/utils/storage_key_impl.rs | 2 +- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/near-sdk-macros/src/lib.rs b/near-sdk-macros/src/lib.rs index c04c4979c..9cd7e4521 100644 --- a/near-sdk-macros/src/lib.rs +++ b/near-sdk-macros/src/lib.rs @@ -55,7 +55,7 @@ struct NearMacroArgs { /// pub name: String, /// } /// ``` -/// +/// /// This macro will generate code to load and deserialize state if the `self` parameter is included /// as well as saving it back to state if `&mut self` is used. /// @@ -84,16 +84,16 @@ struct NearMacroArgs { /// ... // } /// ``` -/// +/// /// # Usage for enum / struct -/// +/// /// If the macro is used with struct or enum, it will make the struct or enum serializable with either /// Borsh or Json depending on serializers passed. Use `#[near(serializers=[borsh])]` to make it serializable with Borsh. /// Or use `#[near(serializers=[json])]` to make it serializable with Json. By default, borsh is used. /// You can also specify both and none. BorshSchema or JsonSchema are always generated. /// /// If you want the struct to be a contract state, you can pass in the contract_state argument. -/// +/// /// ## Example /// ```ignore /// use near_sdk::near; @@ -474,7 +474,7 @@ fn process_impl_block( /// fn mult(&self, a: u64, b: u64) -> u128; /// fn sum(&self, a: u128, b: u128) -> u128; /// } -/// +/// /// #[near] /// impl Contract { /// pub fn multiply_by_five(&mut self, number: u64) -> Promise { @@ -483,9 +483,9 @@ fn process_impl_block( /// .mult(number, 5) /// } /// } -/// +/// /// ``` -/// +/// /// See more information about role of ext_contract in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/crosscontract) #[proc_macro_attribute] pub fn ext_contract(attr: TokenStream, item: TokenStream) -> TokenStream { @@ -815,23 +815,23 @@ pub fn derive_no_default(item: TokenStream) -> TokenStream { /// `BorshStorageKey` generates implementation for `BorshIntoStorageKey` trait. /// It allows the type to be passed as a unique prefix for persistent collections. -/// The type should also implement or derive `BorshSerialize` trait. -/// +/// The type should also implement or derive `BorshSerialize` trait. +/// /// More information about storage keys in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/storage) -/// ## Example +/// ## Example /// ```ignore /// #[derive(BorshSerialize, BorshDeserialize, BorshStorageKey)] /// #[borsh(crate = "near_sdk::borsh")] /// pub enum StorageKey { /// Messages, /// } -/// +/// /// // Define the contract structure /// #[near(contract_state)] /// pub struct Contract { /// messages: Vector /// } -/// +/// /// // Define the default, which automatically initializes the contract /// impl Default for Contract { /// fn default() -> Self { diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index 9d9c164da..2857c1f83 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -755,7 +755,7 @@ pub fn alt_bn128_pairing_check(value: &[u8]) -> bool { /// /// More info about promises in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/crosscontract#promises) /// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_create`] -/// Example usages of this low-level api are and +/// Example usages of this low-level api are and /// pub fn promise_create( account_id: AccountId, diff --git a/near-sdk/src/lib.rs b/near-sdk/src/lib.rs index d167cc010..77ca7eead 100644 --- a/near-sdk/src/lib.rs +++ b/near-sdk/src/lib.rs @@ -59,7 +59,7 @@ //! ```bash //! cargo install --locked cargo-near //! ``` -//! +//! //! Build your contract for the NEAR blockchain: //! //! ```bash diff --git a/near-sdk/src/types/error.rs b/near-sdk/src/types/error.rs index b74019750..77c809143 100644 --- a/near-sdk/src/types/error.rs +++ b/near-sdk/src/types/error.rs @@ -20,7 +20,7 @@ /// } /// } /// } -/// +/// /// #[near] /// impl Contract { /// // if the Error does not implement FunctionError, the following will not compile with #[handle_result] diff --git a/near-sdk/src/utils/storage_key_impl.rs b/near-sdk/src/utils/storage_key_impl.rs index 7fabd8ff0..ff25b5ff0 100644 --- a/near-sdk/src/utils/storage_key_impl.rs +++ b/near-sdk/src/utils/storage_key_impl.rs @@ -1,7 +1,7 @@ /// Converts Self into a [`Vec`] that is used for a storage key through [`into_storage_key`]. /// /// [`into_storage_key`]: IntoStorageKey::into_storage_key -/// +/// /// More information about storage is in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/storage). pub trait IntoStorageKey { /// Consumes self and returns [`Vec`] bytes which are used as a storage key. From aef8c1400a93cd9990ce61e67227d0214038fe04 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Fri, 20 Dec 2024 23:02:06 +0700 Subject: [PATCH 13/30] clippy --- near-sdk/src/environment/env.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index 2857c1f83..51e8e45c7 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -892,7 +892,7 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { /// ```ignore /// let target_account = "example.near".to_string(); /// let promise_index = env::promise_batch_create(&target_account); - +/// /// // Adding actions to the promise /// env::promise_batch_action_transfer(promise_index, 10u128); // Transfer 10 NEAR /// env::promise_batch_action_function_call( @@ -1158,7 +1158,6 @@ pub fn promise_batch_action_stake( /// Attach promise action that adds a full access key to the NEAR promise index with the provided promise index. /// /// More info about batching [here](crate::env::promise_batch_create) - /// # Examples /// ``` /// use near_sdk::env::{promise_batch_action_add_key_with_full_access, promise_batch_create}; @@ -1320,7 +1319,6 @@ pub fn promise_batch_action_add_key_allowance_with_function_call( /// Attach promise action that deletes the key to the NEAR promise index with the provided promise index. /// /// More info about batching [here](crate::env::promise_batch_create) - /// # Examples /// ``` /// use near_sdk::env::{promise_batch_action_delete_key, promise_batch_create}; From 49bc57ba81e47069e3e308510ffb8de5f097d986 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Fri, 20 Dec 2024 23:09:46 +0700 Subject: [PATCH 14/30] fmt --- near-sdk/src/environment/env.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index 51e8e45c7..a86b36424 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -892,7 +892,7 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { /// ```ignore /// let target_account = "example.near".to_string(); /// let promise_index = env::promise_batch_create(&target_account); -/// +/// /// // Adding actions to the promise /// env::promise_batch_action_transfer(promise_index, 10u128); // Transfer 10 NEAR /// env::promise_batch_action_function_call( From f29575c83c7c6b9463d65b018164630fd7af4f17 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Fri, 20 Dec 2024 23:32:28 +0700 Subject: [PATCH 15/30] docs test fix --- .github/workflows/test.yml | 2 +- near-sdk-macros/src/lib.rs | 8 ++++---- near-sdk/src/environment/env.rs | 2 ++ 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 06bda06c8..c2cd0b04d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -123,7 +123,7 @@ jobs: env: RUSTDOCFLAGS: -D warnings run: | - cargo doc -p near-sdk --features unstable,legacy,unit-testing,__macro-docs + cargo doc -p near-sdk --features unstable,legacy,unit-testing,__macro-docs,near-primitives,near-vm-runner cargo doc -p near-sdk-macros cargo doc -p near-contract-standards --no-deps cargo doc -p near-sys diff --git a/near-sdk-macros/src/lib.rs b/near-sdk-macros/src/lib.rs index 9cd7e4521..c94de79e8 100644 --- a/near-sdk-macros/src/lib.rs +++ b/near-sdk-macros/src/lib.rs @@ -68,7 +68,7 @@ struct NearMacroArgs { /// impl Adder { /// #[result_serializer(borsh)] /// pub fn borsh_parameters(&self, #[serializer(borsh)] a: Pair, #[serializer(borsh)] b: Pair) -> Pair { -/// ... +/// /// ... // } /// ``` /// @@ -81,7 +81,7 @@ struct NearMacroArgs { /// impl Adder { /// #[result_serializer(borsh)] /// pub fn borsh_parameters(&self) -> Pair { -/// ... +/// /// ... // } /// ``` /// @@ -316,8 +316,8 @@ pub fn near(attr: TokenStream, item: TokenStream) -> TokenStream { TokenStream::from(expanded) } -/// This macro is deprecated. Use [#[near]](./attr.near.html) instead. The difference between #[near] and #[near_bindgen] is that -/// with #[near_bindgen] you have to manually add boilerplate code for structs and enums so that they become Json- and Borsh-serializable: +/// This macro is deprecated. Use [#[macro@near]](./attr.near.html) instead. The difference between #[macro@near] and #[macro@near_bindgen] is that +/// with #[macro@near_bindgen] you have to manually add boilerplate code for structs and enums so that they become Json- and Borsh-serializable: /// ```ignore /// #[near_bindgen] /// #[derive(BorshSerialize, BorshDeserialize, NearSchema)] diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index a86b36424..b71d901b9 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -1390,6 +1390,7 @@ pub fn promise_batch_action_delete_account( /// assert_eq!(promise_results_count(), 0); /// ``` /// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_results_count`] +/// See example of usage [here](https://github.com/near/near-sdk-rs/blob/master/examples/cross-contract-calls/low-level/src/lib.rs) pub fn promise_results_count() -> u64 { unsafe { sys::promise_results_count() } } @@ -1419,6 +1420,7 @@ pub fn promise_results_count() -> u64 { /// }; /// ``` /// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_result`] +/// Example usages: [one](https://github.com/near/near-sdk-rs/blob/189897180649bce47aefa4e5af03664ee525508d/near-contract-standards/src/fungible_token/core_impl.rs#L178), [two](https://github.com/near/near-sdk-rs/blob/189897180649bce47aefa4e5af03664ee525508d/near-contract-standards/src/non_fungible_token/core/core_impl.rs#L433), [three](https://github.com/near/near-sdk-rs/blob/189897180649bce47aefa4e5af03664ee525508d/examples/factory-contract/low-level/src/lib.rs#L61), [four](https://github.com/near/near-sdk-rs/blob/189897180649bce47aefa4e5af03664ee525508d/examples/cross-contract-calls/low-level/src/lib.rs#L46) pub fn promise_result(result_idx: u64) -> PromiseResult { match promise_result_internal(result_idx) { Ok(()) => { From 48ccae6564598fdf0d422f6ea29f076823d5fbe4 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Fri, 20 Dec 2024 23:39:19 +0700 Subject: [PATCH 16/30] fix doc --- near-sdk-macros/src/lib.rs | 4 ++-- near-sdk/src/environment/env.rs | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/near-sdk-macros/src/lib.rs b/near-sdk-macros/src/lib.rs index c94de79e8..f845cd2a6 100644 --- a/near-sdk-macros/src/lib.rs +++ b/near-sdk-macros/src/lib.rs @@ -69,7 +69,7 @@ struct NearMacroArgs { /// #[result_serializer(borsh)] /// pub fn borsh_parameters(&self, #[serializer(borsh)] a: Pair, #[serializer(borsh)] b: Pair) -> Pair { /// /// ... -// } +/// } /// ``` /// /// `#[near]` will also handle serializing and setting the return value of the @@ -82,7 +82,7 @@ struct NearMacroArgs { /// #[result_serializer(borsh)] /// pub fn borsh_parameters(&self) -> Pair { /// /// ... -// } +/// } /// ``` /// /// # Usage for enum / struct diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index b71d901b9..a4f8a0b37 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -1462,6 +1462,7 @@ pub(crate) fn promise_result_internal(result_idx: u64) -> Result<(), PromiseErro /// promise_return(promise); /// ``` /// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_return`] +/// Example usages: [one](https://github.com/near/near-sdk-rs/tree/master/examples/cross-contract-calls/low-level/src/lib.rs), [two](https://github.com/near/near-sdk-rs/tree/master/examples/factory-contract/low-level/src/lib.rs) pub fn promise_return(promise_idx: PromiseIndex) { unsafe { sys::promise_return(promise_idx.0) } } @@ -1513,6 +1514,7 @@ pub fn promise_return(promise_idx: PromiseIndex) { /// ); /// ``` /// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_yield_create`] +/// See example of usage [here](https://github.com/near/mpc/blob/79ec50759146221e7ad8bb04520f13333b75ca07/chain-signatures/contract/src/lib.rs#L689) pub fn promise_yield_create( function_name: &str, arguments: &[u8], From 4d92375ef39a63c655ceaa9c496fbb481a7a161c Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Fri, 20 Dec 2024 23:53:19 +0700 Subject: [PATCH 17/30] fix docs --- near-sdk-macros/src/lib.rs | 2 ++ near-sdk/src/environment/env.rs | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/near-sdk-macros/src/lib.rs b/near-sdk-macros/src/lib.rs index f845cd2a6..ca7da0e29 100644 --- a/near-sdk-macros/src/lib.rs +++ b/near-sdk-macros/src/lib.rs @@ -70,6 +70,7 @@ struct NearMacroArgs { /// pub fn borsh_parameters(&self, #[serializer(borsh)] a: Pair, #[serializer(borsh)] b: Pair) -> Pair { /// /// ... /// } +/// } /// ``` /// /// `#[near]` will also handle serializing and setting the return value of the @@ -83,6 +84,7 @@ struct NearMacroArgs { /// pub fn borsh_parameters(&self) -> Pair { /// /// ... /// } +/// } /// ``` /// /// # Usage for enum / struct diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index a4f8a0b37..7f3f9beb2 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -1580,6 +1580,7 @@ pub fn promise_yield_create( /// ); /// ``` /// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_yield_resume`] +/// See example of usage [here](https://github.com/near/mpc/blob/79ec50759146221e7ad8bb04520f13333b75ca07/chain-signatures/contract/src/lib.rs#L288) pub fn promise_yield_resume(data_id: &CryptoHash, data: &[u8]) -> bool { unsafe { sys::promise_yield_resume( @@ -1657,6 +1658,7 @@ pub fn validator_total_stake() -> NearToken { /// }).to_string().into_bytes().as_slice() /// ); /// ``` +/// Example of usage [here](https://github.com/near/near-sdk-rs/blob/189897180649bce47aefa4e5af03664ee525508d/examples/cross-contract-calls/low-level/src/lib.rs#L18) pub fn value_return(value: &[u8]) { unsafe { sys::value_return(value.len() as _, value.as_ptr() as _) } } @@ -1731,6 +1733,7 @@ pub fn abort() -> ! { /// let number = 5; /// log_str(format!("Number: {}", number).as_str()); /// ``` +/// Example of usage [here](https://github.com/near/near-sdk-rs/blob/189897180649bce47aefa4e5af03664ee525508d/near-contract-standards/src/event.rs#L29) pub fn log_str(message: &str) { #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] eprintln!("{}", message); @@ -1772,6 +1775,7 @@ pub fn log(message: &[u8]) { /// assert!(storage_write(b"key", b"another_value")); /// assert_eq!(storage_read(b"key").unwrap(), b"another_value"); /// ``` +/// Example of usage [here](https://github.com/near/near-sdk-rs/blob/189897180649bce47aefa4e5af03664ee525508d/near-contract-standards/src/upgrade/mod.rs#L63) pub fn storage_write(key: &[u8], value: &[u8]) -> bool { match unsafe { sys::storage_write( @@ -1823,6 +1827,7 @@ pub fn storage_read(key: &[u8]) -> Option> { /// storage_write(b"key", b"value"); /// assert_eq!(storage_remove(b"key"), true); /// ``` +/// Example of usage [here](https://github.com/near/near-sdk-rs/blob/189897180649bce47aefa4e5af03664ee525508d/near-contract-standards/src/upgrade/mod.rs#L79) pub fn storage_remove(key: &[u8]) -> bool { match unsafe { sys::storage_remove(key.len() as _, key.as_ptr() as _, EVICTED_REGISTER) } { 0 => false, @@ -1905,6 +1910,7 @@ pub fn state_exists() -> bool { /// /// assert_eq!(storage_byte_cost(), NearToken::from_yoctonear(10000000000000000000)); /// ``` +/// Example of usage [here](https://github.com/near/near-sdk-rs/blob/189897180649bce47aefa4e5af03664ee525508d/near-contract-standards/src/fungible_token/storage_impl.rs#L105), [here](https://github.com/near/near-sdk-rs/blob/master/near-contract-standards/src/non_fungible_token/utils.rs) and [here](https://github.com/near/near-sdk-rs/blob/master/examples/fungible-token/tests/workspaces.rs) pub fn storage_byte_cost() -> NearToken { NearToken::from_yoctonear(10_000_000_000_000_000_000u128) } From 63b8b0aba2c88b4d1be13efea34f3b241888052b Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Sat, 21 Dec 2024 00:07:55 +0700 Subject: [PATCH 18/30] fix docs --- near-sdk-macros/src/lib.rs | 4 ++-- near-sdk/src/lib.rs | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/near-sdk-macros/src/lib.rs b/near-sdk-macros/src/lib.rs index ca7da0e29..f02d66d9c 100644 --- a/near-sdk-macros/src/lib.rs +++ b/near-sdk-macros/src/lib.rs @@ -318,8 +318,8 @@ pub fn near(attr: TokenStream, item: TokenStream) -> TokenStream { TokenStream::from(expanded) } -/// This macro is deprecated. Use [#[macro@near]](./attr.near.html) instead. The difference between #[macro@near] and #[macro@near_bindgen] is that -/// with #[macro@near_bindgen] you have to manually add boilerplate code for structs and enums so that they become Json- and Borsh-serializable: +/// This macro is deprecated. Use [#\[near\]](./attr.near.html) instead. The difference between #\[near\] and #\[near_bindgen\] is that +/// with #\[near_bindgen\] you have to manually add boilerplate code for structs and enums so that they become Json- and Borsh-serializable: /// ```ignore /// #[near_bindgen] /// #[derive(BorshSerialize, BorshDeserialize, NearSchema)] diff --git a/near-sdk/src/lib.rs b/near-sdk/src/lib.rs index 77ca7eead..a53160146 100644 --- a/near-sdk/src/lib.rs +++ b/near-sdk/src/lib.rs @@ -8,9 +8,9 @@ //! ## Features //! //! - **State Management:** Simplified handling of contract state with serialization via [Borsh](https://borsh.io) or JSON. -//! - **Initialization methods** We can define an initialization method that can be used to initialize the state of the contract. #[init] macro verifies that the contract has not been initialized yet (the contract state doesn't exist) and will panic otherwise. -//! - **Payable methods** We can allow methods to accept token transfer together with the function call with #[payable] macro. -//! - **Private methods** #[private] macro makes it possible to define private methods that can't be called from the outside of the contract. +//! - **Initialization methods** We can define an initialization method that can be used to initialize the state of the contract. #\[init\] macro verifies that the contract has not been initialized yet (the contract state doesn't exist) and will panic otherwise. +//! - **Payable methods** We can allow methods to accept token transfer together with the function call with #\[payable\] macro. +//! - **Private methods** #\[private\] macro makes it possible to define private methods that can't be called from the outside of the contract. //! - **Cross-Contract Calls:** Support for asynchronous interactions between contracts. //! - **Unit Testing:** Built-in support for testing contracts in a Rust environment. //! - **WASM Compilation:** Compile Rust code to WebAssembly (WASM) for execution on the NEAR runtime. From d46cd16f476784ff0e5ffdd0b1469d345ba076ab Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Sat, 21 Dec 2024 00:11:46 +0700 Subject: [PATCH 19/30] fix --- near-sdk-macros/src/lib.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/near-sdk-macros/src/lib.rs b/near-sdk-macros/src/lib.rs index f02d66d9c..4bd34b247 100644 --- a/near-sdk-macros/src/lib.rs +++ b/near-sdk-macros/src/lib.rs @@ -336,10 +336,6 @@ pub fn near(attr: TokenStream, item: TokenStream) -> TokenStream { /// } /// ``` #[proc_macro_attribute] -#[deprecated( - since = "5.7.0", - note = "Use #[near] macro instead which allows to remove boilerplate code" -)] pub fn near_bindgen(attr: TokenStream, item: TokenStream) -> TokenStream { if attr.to_string().contains("event_json") { return core_impl::near_events(attr, item); From 9bbd19a4703e22ad84ef1258a64a7fa4fdda9385 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Sat, 21 Dec 2024 00:14:17 +0700 Subject: [PATCH 20/30] fix --- near-sdk/src/environment/env.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index 7f3f9beb2..00c99f696 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -1514,7 +1514,7 @@ pub fn promise_return(promise_idx: PromiseIndex) { /// ); /// ``` /// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_yield_create`] -/// See example of usage [here](https://github.com/near/mpc/blob/79ec50759146221e7ad8bb04520f13333b75ca07/chain-signatures/contract/src/lib.rs#L689) +/// See example of usage [here](https://github.com/near/mpc/blob/79ec50759146221e7ad8bb04520f13333b75ca07/chain-signatures/contract/src/lib.rs#L689) and [here](https://github.com/near/near-sdk-rs/pull/1133) pub fn promise_yield_create( function_name: &str, arguments: &[u8], @@ -1580,7 +1580,7 @@ pub fn promise_yield_create( /// ); /// ``` /// More low-level info here: [`near_vm_runner::logic::VMLogic::promise_yield_resume`] -/// See example of usage [here](https://github.com/near/mpc/blob/79ec50759146221e7ad8bb04520f13333b75ca07/chain-signatures/contract/src/lib.rs#L288) +/// See example of usage [here](https://github.com/near/mpc/blob/79ec50759146221e7ad8bb04520f13333b75ca07/chain-signatures/contract/src/lib.rs#L288) and [here](https://github.com/near/near-sdk-rs/pull/1133) pub fn promise_yield_resume(data_id: &CryptoHash, data: &[u8]) -> bool { unsafe { sys::promise_yield_resume( From 99c7e13fe1c373247313771ad371a7a38e5a28b8 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Fri, 27 Dec 2024 04:00:35 +0700 Subject: [PATCH 21/30] fix ci test --- near-sdk/src/types/error.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/near-sdk/src/types/error.rs b/near-sdk/src/types/error.rs index 77c809143..916ad0752 100644 --- a/near-sdk/src/types/error.rs +++ b/near-sdk/src/types/error.rs @@ -2,8 +2,8 @@ /// with `#[handle_result]` has to implement this trait. /// /// Example: -/// ``` -/// use near_sdk::FunctionError; +/// ```ignore +/// use near_sdk::{FunctionError, near}; /// /// enum Error { /// NotFound, @@ -20,6 +20,10 @@ /// } /// } /// } +/// +/// #[near(contract_state)] +/// #[derive(Default)] +/// pub struct Contract; /// /// #[near] /// impl Contract { From 22e4098a6093084acdbe58f73423eb56fc382eb4 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Fri, 27 Dec 2024 04:04:12 +0700 Subject: [PATCH 22/30] fmt --- near-sdk/src/types/error.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/near-sdk/src/types/error.rs b/near-sdk/src/types/error.rs index 916ad0752..e1882b459 100644 --- a/near-sdk/src/types/error.rs +++ b/near-sdk/src/types/error.rs @@ -20,7 +20,7 @@ /// } /// } /// } -/// +/// /// #[near(contract_state)] /// #[derive(Default)] /// pub struct Contract; From c63918da75bff519d89e2db0b518a0ea425c3fc9 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Sat, 28 Dec 2024 01:13:57 +0700 Subject: [PATCH 23/30] ignore to no_run --- near-sdk/src/environment/env.rs | 2 +- near-sdk/src/json_types/vector.rs | 2 +- near-sdk/src/types/error.rs | 2 +- near-sdk/src/types/vm_types.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index 00c99f696..27f78ed21 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -889,7 +889,7 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { /// Create a NEAR promise which will have multiple promise actions inside. /// /// Example: -/// ```ignore +/// ```no_run /// let target_account = "example.near".to_string(); /// let promise_index = env::promise_batch_create(&target_account); /// diff --git a/near-sdk/src/json_types/vector.rs b/near-sdk/src/json_types/vector.rs index b69e484ae..245663a1f 100644 --- a/near-sdk/src/json_types/vector.rs +++ b/near-sdk/src/json_types/vector.rs @@ -28,7 +28,7 @@ impl From for Vec { /// Convenience module to allow anotating a serde structure as base64 bytes. /// /// # Example -/// ```ignore +/// ```no_run /// use serde::{Serialize, Deserialize}; /// use near_sdk::json_types::base64_bytes; /// diff --git a/near-sdk/src/types/error.rs b/near-sdk/src/types/error.rs index e1882b459..33e607fbe 100644 --- a/near-sdk/src/types/error.rs +++ b/near-sdk/src/types/error.rs @@ -2,7 +2,7 @@ /// with `#[handle_result]` has to implement this trait. /// /// Example: -/// ```ignore +/// ```no_run /// use near_sdk::{FunctionError, near}; /// /// enum Error { diff --git a/near-sdk/src/types/vm_types.rs b/near-sdk/src/types/vm_types.rs index 86fc122d7..adf7e7793 100644 --- a/near-sdk/src/types/vm_types.rs +++ b/near-sdk/src/types/vm_types.rs @@ -5,7 +5,7 @@ pub use near_vm_runner::logic::types::{PromiseResult as VmPromiseResult, ReturnD /// Promise index that is computed only once. It is an internal index that identifies a specific promise (or a sequence of promises) created during the execution of a smart contract. /// Returned by [`promise_create`](crate::env::promise_create) and can be used to refer this promise in `promise_then`, `promise_batch_create`, and other functions. /// Example: -/// ```ignore +/// ```no_run /// let promise_id = env::promise_create("a.near", "new", b"{}", 0, 1_000_000_000_000); /// env::promise_then(promise_id, "b.near", "callback", b"{}", 0, 1_000_000_000_000); /// ``` From c2732a2ab19a799322517608c56448eb9e070393 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Sat, 28 Dec 2024 01:20:40 +0700 Subject: [PATCH 24/30] remove unnecessary near-primitives and near-vm-runner for docs --- .github/workflows/test.yml | 2 +- near-sdk/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ce97cb27f..ca9fb1686 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -123,7 +123,7 @@ jobs: env: RUSTDOCFLAGS: -D warnings run: | - cargo doc -p near-sdk --features unstable,legacy,unit-testing,__macro-docs,__abi-generate,near-primitives,near-vm-runner + cargo doc -p near-sdk --features unstable,legacy,unit-testing,__macro-docs,__abi-generate cargo doc -p near-sdk-macros --features __abi-generate cargo doc -p near-contract-standards --no-deps --features abi cargo doc -p near-sys diff --git a/near-sdk/Cargo.toml b/near-sdk/Cargo.toml index 1d88e5d3c..4690d8010 100644 --- a/near-sdk/Cargo.toml +++ b/near-sdk/Cargo.toml @@ -98,4 +98,4 @@ __abi-generate = ["abi", "near-sdk-macros/__abi-generate"] __macro-docs = [] [package.metadata.docs.rs] -features = ["unstable", "legacy", "unit-testing", "__macro-docs", "__abi-generate", "near-primitives", "near-vm-runner"] +features = ["unstable", "legacy", "unit-testing", "__macro-docs", "__abi-generate"] From f0c05da8cbe65d3983b90cf8cf4a91da65130676 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Sat, 28 Dec 2024 13:48:09 +0800 Subject: [PATCH 25/30] fix no-run tests --- near-sdk/src/environment/env.rs | 4 +++- near-sdk/src/json_types/vector.rs | 2 +- near-sdk/src/types/vm_types.rs | 2 ++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index 27f78ed21..f8a5add21 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -878,7 +878,7 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { /// # Examples /// ``` -/// use near_sdk::env::promise_batch_create; +/// /// use near_sdk::AccountId; /// use std::str::FromStr; /// @@ -890,6 +890,8 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { /// /// Example: /// ```no_run +/// use near_sdk::env; +/// /// let target_account = "example.near".to_string(); /// let promise_index = env::promise_batch_create(&target_account); /// diff --git a/near-sdk/src/json_types/vector.rs b/near-sdk/src/json_types/vector.rs index 245663a1f..b69e484ae 100644 --- a/near-sdk/src/json_types/vector.rs +++ b/near-sdk/src/json_types/vector.rs @@ -28,7 +28,7 @@ impl From for Vec { /// Convenience module to allow anotating a serde structure as base64 bytes. /// /// # Example -/// ```no_run +/// ```ignore /// use serde::{Serialize, Deserialize}; /// use near_sdk::json_types::base64_bytes; /// diff --git a/near-sdk/src/types/vm_types.rs b/near-sdk/src/types/vm_types.rs index adf7e7793..c75aaffd4 100644 --- a/near-sdk/src/types/vm_types.rs +++ b/near-sdk/src/types/vm_types.rs @@ -6,6 +6,8 @@ pub use near_vm_runner::logic::types::{PromiseResult as VmPromiseResult, ReturnD /// Returned by [`promise_create`](crate::env::promise_create) and can be used to refer this promise in `promise_then`, `promise_batch_create`, and other functions. /// Example: /// ```no_run +/// use near_sdk::env; +/// /// let promise_id = env::promise_create("a.near", "new", b"{}", 0, 1_000_000_000_000); /// env::promise_then(promise_id, "b.near", "callback", b"{}", 0, 1_000_000_000_000); /// ``` From 8e16e832b522484f9874618c12b6084cea419018 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Sat, 28 Dec 2024 13:51:41 +0800 Subject: [PATCH 26/30] fmt --- near-sdk/src/environment/env.rs | 4 ++-- near-sdk/src/types/vm_types.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index f8a5add21..8360020b2 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -878,7 +878,7 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { /// # Examples /// ``` -/// +/// /// use near_sdk::AccountId; /// use std::str::FromStr; /// @@ -891,7 +891,7 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { /// Example: /// ```no_run /// use near_sdk::env; -/// +/// /// let target_account = "example.near".to_string(); /// let promise_index = env::promise_batch_create(&target_account); /// diff --git a/near-sdk/src/types/vm_types.rs b/near-sdk/src/types/vm_types.rs index c75aaffd4..d22ed9194 100644 --- a/near-sdk/src/types/vm_types.rs +++ b/near-sdk/src/types/vm_types.rs @@ -7,7 +7,7 @@ pub use near_vm_runner::logic::types::{PromiseResult as VmPromiseResult, ReturnD /// Example: /// ```no_run /// use near_sdk::env; -/// +/// /// let promise_id = env::promise_create("a.near", "new", b"{}", 0, 1_000_000_000_000); /// env::promise_then(promise_id, "b.near", "callback", b"{}", 0, 1_000_000_000_000); /// ``` From 916e81d4cea205d75841cb426bc34d0eb3fdf095 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Sat, 28 Dec 2024 14:34:09 +0800 Subject: [PATCH 27/30] fix tests --- near-sdk/src/environment/env.rs | 20 +++++++++++--------- near-sdk/src/types/vm_types.rs | 12 +++++++++--- 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index 8360020b2..b3374f805 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -877,12 +877,13 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { } /// # Examples -/// ``` +/// ```no_run /// +/// use near_sdk::env; /// use near_sdk::AccountId; /// use std::str::FromStr; /// -/// let promise = promise_batch_create( +/// let promise = env::promise_batch_create( /// &AccountId::from_str("receiver.near").unwrap() /// ); /// ``` @@ -890,19 +891,20 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { /// /// Example: /// ```no_run -/// use near_sdk::env; +/// use near_sdk::{env, NearToken, NearGas}; /// -/// let target_account = "example.near".to_string(); -/// let promise_index = env::promise_batch_create(&target_account); +/// let promise_index = env::promise_batch_create( +/// &AccountId::from_str("example.near").unwrap() +/// ); /// /// // Adding actions to the promise -/// env::promise_batch_action_transfer(promise_index, 10u128); // Transfer 10 NEAR +/// env::promise_batch_action_transfer(promise_index, NearToken::fromNear(10u128)); // Transfer 10 NEAR /// env::promise_batch_action_function_call( /// promise_index, -/// "method_name".to_string(), // Target method -/// b"{}".to_vec(), // Arguments +/// "method_name", // Target method +/// b"{}", // Arguments /// 0, // Attached deposit -/// 5_000_000_000_000 // Gas for execution +/// NearGas::from_tgas(5) // Gas for execution /// ); /// ``` /// All actions in a batch are executed in the order they were added. diff --git a/near-sdk/src/types/vm_types.rs b/near-sdk/src/types/vm_types.rs index d22ed9194..b038ee443 100644 --- a/near-sdk/src/types/vm_types.rs +++ b/near-sdk/src/types/vm_types.rs @@ -6,10 +6,16 @@ pub use near_vm_runner::logic::types::{PromiseResult as VmPromiseResult, ReturnD /// Returned by [`promise_create`](crate::env::promise_create) and can be used to refer this promise in `promise_then`, `promise_batch_create`, and other functions. /// Example: /// ```no_run -/// use near_sdk::env; +/// use near_sdk::{env, NearGas}; /// -/// let promise_id = env::promise_create("a.near", "new", b"{}", 0, 1_000_000_000_000); -/// env::promise_then(promise_id, "b.near", "callback", b"{}", 0, 1_000_000_000_000); +/// let promise_id = env::promise_create( +/// &AccountId::from_str("a.near").unwrap(), "new", b"{}", 0, +/// NearGas::from_tgas(1) +/// ); +/// env::promise_then( +/// promise_id, &AccountId::from_str("b.near").unwrap(), "callback", b"{}", 0, +/// NearGas::from_tgas(1) +/// ); /// ``` #[derive(Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Copy, Clone)] pub struct PromiseIndex(pub(crate) u64); From 3d5cb4e54d2c4911d6f34474772a68e21ca5ea99 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Sat, 28 Dec 2024 14:37:45 +0800 Subject: [PATCH 28/30] fmt --- near-sdk/src/types/vm_types.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/near-sdk/src/types/vm_types.rs b/near-sdk/src/types/vm_types.rs index b038ee443..9a241682b 100644 --- a/near-sdk/src/types/vm_types.rs +++ b/near-sdk/src/types/vm_types.rs @@ -9,11 +9,11 @@ pub use near_vm_runner::logic::types::{PromiseResult as VmPromiseResult, ReturnD /// use near_sdk::{env, NearGas}; /// /// let promise_id = env::promise_create( -/// &AccountId::from_str("a.near").unwrap(), "new", b"{}", 0, +/// &AccountId::from_str("a.near").unwrap(), "new", b"{}", 0, /// NearGas::from_tgas(1) /// ); /// env::promise_then( -/// promise_id, &AccountId::from_str("b.near").unwrap(), "callback", b"{}", 0, +/// promise_id, &AccountId::from_str("b.near").unwrap(), "callback", b"{}", 0, /// NearGas::from_tgas(1) /// ); /// ``` From bc34aced4ab9e6277ff2fd564b66bb429057d526 Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Mon, 30 Dec 2024 01:02:08 +0800 Subject: [PATCH 29/30] fix tests --- near-sdk/src/environment/env.rs | 8 ++++---- near-sdk/src/types/vm_types.rs | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index b3374f805..45771ecbe 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -891,20 +891,20 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { /// /// Example: /// ```no_run -/// use near_sdk::{env, NearToken, NearGas}; +/// use near_sdk::{env, NearToken, Gas, AccountId}; /// /// let promise_index = env::promise_batch_create( /// &AccountId::from_str("example.near").unwrap() /// ); /// /// // Adding actions to the promise -/// env::promise_batch_action_transfer(promise_index, NearToken::fromNear(10u128)); // Transfer 10 NEAR +/// env::promise_batch_action_transfer(promise_index, NearToken::from_near(10u128)); // Transfer 10 NEAR /// env::promise_batch_action_function_call( /// promise_index, /// "method_name", // Target method /// b"{}", // Arguments -/// 0, // Attached deposit -/// NearGas::from_tgas(5) // Gas for execution +/// NearToken::from_near(0), // Attached deposit +/// Gas::from_tgas(5) // Gas for execution /// ); /// ``` /// All actions in a batch are executed in the order they were added. diff --git a/near-sdk/src/types/vm_types.rs b/near-sdk/src/types/vm_types.rs index 9a241682b..6d28dd999 100644 --- a/near-sdk/src/types/vm_types.rs +++ b/near-sdk/src/types/vm_types.rs @@ -6,15 +6,15 @@ pub use near_vm_runner::logic::types::{PromiseResult as VmPromiseResult, ReturnD /// Returned by [`promise_create`](crate::env::promise_create) and can be used to refer this promise in `promise_then`, `promise_batch_create`, and other functions. /// Example: /// ```no_run -/// use near_sdk::{env, NearGas}; +/// use near_sdk::{env, Gas}; /// /// let promise_id = env::promise_create( /// &AccountId::from_str("a.near").unwrap(), "new", b"{}", 0, -/// NearGas::from_tgas(1) +/// Gas::from_tgas(1) /// ); /// env::promise_then( /// promise_id, &AccountId::from_str("b.near").unwrap(), "callback", b"{}", 0, -/// NearGas::from_tgas(1) +/// Gas::from_tgas(1) /// ); /// ``` #[derive(Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Copy, Clone)] From b1b185ff8063cdec6df4fcd55877447be31a99cf Mon Sep 17 00:00:00 2001 From: polyprogrammist Date: Tue, 31 Dec 2024 00:30:19 +0800 Subject: [PATCH 30/30] checkj --- near-sdk/src/environment/env.rs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index 45771ecbe..f04121cd3 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -159,7 +159,7 @@ pub fn register_len(register_id: u64) -> Option { /// use near_sdk::AccountId; /// use std::str::FromStr; /// -/// assert_eq!(current_account_id(), AccountId::from_str("alice.near").unwrap()); +/// assert_eq!(current_account_id(), "alice.near".parse().unwrap()); /// ``` pub fn current_account_id() -> AccountId { assert_valid_account_id(method_into_register!(current_account_id)) @@ -174,7 +174,7 @@ pub fn current_account_id() -> AccountId { /// use near_sdk::AccountId; /// use std::str::FromStr; /// -/// assert_eq!(signer_account_id(), AccountId::from_str("bob.near").unwrap()); +/// assert_eq!(signer_account_id(), "bob.near".parse().unwrap()); /// ``` pub fn signer_account_id() -> AccountId { assert_valid_account_id(method_into_register!(signer_account_id)) @@ -203,7 +203,7 @@ pub fn signer_account_pk() -> PublicKey { /// use near_sdk::AccountId; /// use std::str::FromStr; /// -/// assert_eq!(predecessor_account_id(), AccountId::from_str("bob.near").unwrap()); +/// assert_eq!(predecessor_account_id(), "bob.near".parse().unwrap()); /// ``` pub fn predecessor_account_id() -> AccountId { assert_valid_account_id(method_into_register!(predecessor_account_id)) @@ -743,7 +743,7 @@ pub fn alt_bn128_pairing_check(value: &[u8]) -> bool { /// use std::str::FromStr; /// /// let promise = promise_create( -/// AccountId::from_str("counter.near").unwrap(), +/// "counter.near".unwrap(), /// "increment", /// serde_json::json!({ /// "value": 5 @@ -789,7 +789,7 @@ pub fn promise_create( /// use std::str::FromStr; /// /// let promise = promise_create( -/// AccountId::from_str("counter.near").unwrap(), +/// "counter.near".parse().unwrap(), /// "increment", /// serde_json::json!({ /// "value": 5 @@ -800,7 +800,7 @@ pub fn promise_create( /// /// let chained_promise = promise_then( /// promise, -/// AccountId::from_str("greetings.near").unwrap(), +/// "greetings.near".parse().unwrap(), /// "set_greeting", /// serde_json::json!({ /// "text": "Hello World" @@ -845,7 +845,7 @@ pub fn promise_then( /// use std::str::FromStr; /// /// let promise1 = promise_create( -/// AccountId::from_str("counter.near").unwrap(), +/// "counter.near".parse().unwrap(), /// "increment", /// serde_json::json!({ /// "value": 5 @@ -855,7 +855,7 @@ pub fn promise_then( /// ); /// /// let promise2 = promise_create( -/// AccountId::from_str("greetings.near").unwrap(), +/// "greetings.near".parse().unwrap(), /// "set_greeting", /// serde_json::json!({ /// "text": "Hello World" @@ -884,7 +884,7 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { /// use std::str::FromStr; /// /// let promise = env::promise_batch_create( -/// &AccountId::from_str("receiver.near").unwrap() +/// &"receiver.near".parse().unwrap() /// ); /// ``` /// Create a NEAR promise which will have multiple promise actions inside. @@ -894,7 +894,7 @@ pub fn promise_and(promise_indices: &[PromiseIndex]) -> PromiseIndex { /// use near_sdk::{env, NearToken, Gas, AccountId}; /// /// let promise_index = env::promise_batch_create( -/// &AccountId::from_str("example.near").unwrap() +/// &"example.near".parse().unwrap() /// ); /// /// // Adding actions to the promise @@ -927,7 +927,7 @@ pub fn promise_batch_create(account_id: &AccountId) -> PromiseIndex { /// use std::str::FromStr; /// /// let promise = promise_create( -/// AccountId::from_str("counter.near").unwrap(), +/// "counter.near".parse().unwrap(), /// "increment", /// serde_json::json!({ /// "value": 5 @@ -938,7 +938,7 @@ pub fn promise_batch_create(account_id: &AccountId) -> PromiseIndex { /// /// let new_promise = promise_batch_then( /// promise, -/// &AccountId::from_str("receiver.near").unwrap() +/// &"receiver.near".parse().unwrap() /// ); /// ``` /// Attach a callback NEAR promise to a batch of NEAR promise actions.