near_sdk/
lib.rs

1//! # `near-sdk`
2//!
3//! `near-sdk` is a Rust toolkit for developing smart contracts on the [NEAR blockchain](https://near.org).
4//! It provides abstractions, macros, and utilities to make building robust and secure contracts easy.
5//! More information on how to develop smart contracts can be found in the [NEAR documentation](https://docs.near.org/build/smart-contracts/what-is).
6//! With near-sdk you can create DeFi applications, NFTs and marketplaces, DAOs, gaming and metaverse apps, and much more.
7//!
8//! ## Features
9//!
10//! - **State Management:** Simplified handling of contract state with serialization via [Borsh](https://borsh.io) or JSON.
11//! - **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.
12//! - **Payable methods** We can allow methods to accept token transfer together with the function call with #\[payable\] macro.
13//! - **Private methods** #\[private\] macro makes it possible to define private methods that can't be called from the outside of the contract.
14//! - **Cross-Contract Calls:** Support for asynchronous interactions between contracts.
15//! - **Unit Testing:** Built-in support for testing contracts in a Rust environment.
16//! - **WASM Compilation:** Compile Rust code to WebAssembly (WASM) for execution on the NEAR runtime.
17//!
18//! ## Quick Start
19//!
20//! Add `near-sdk` to your `Cargo.toml`:
21//!
22//! ```toml
23//! [dependencies]
24//! near-sdk = "5.6.0"
25//! ```
26//!
27//! ### Example: Counter Smart Contract. For more information, see the [**near** macro](near) documentation.
28//!
29//! Below is an example of a simple counter contract that increments and retrieves a value:
30//!
31//! ```rust
32//! use near_sdk::{env, near};
33//!
34//! #[near(contract_state)]
35//! #[derive(Default)]
36//! pub struct Counter {
37//!     value: i32,
38//! }
39//!
40//! #[near]
41//! impl Counter {
42//!     /// Increment the counter by one.
43//!     pub fn increment(&mut self) {
44//!         self.value += 1;
45//!         env::log_str(&format!("Counter incremented to: {}", self.value));
46//!     }
47//!
48//!     /// Get the current value of the counter.
49//!     pub fn get(&self) -> i32 {
50//!         self.value
51//!     }
52//! }
53//! ```
54//!
55//! ### Compiling to WASM
56//!
57//! Install `cargo-near` in case if you don't have it:
58//! ```bash
59//! cargo install --locked cargo-near
60//! ```
61//!
62//! More installation methods on [cargo-near](https://github.com/near/cargo-near)
63//!
64//! Builds a NEAR smart contract along with its [ABI](https://github.com/near/abi) (while in the directory containing contract's Cargo.toml):
65//!
66//! ```bash
67//! cargo near build
68//! ```
69//!
70//! If you have problems/errors with schema/ABI during build that you cannot figure out quick, you can skip/circumvent them with:
71//!
72//! ```bash
73//! cargo near build non-reproducible-wasm --no-abi
74//! ```
75//!
76//! And return to figuring how to resolve problems with generating ABI of your contract later.
77//!
78//! ### Running Unit Tests
79//!
80//! Use the following testing setup:
81//!
82//! ```rust
83//! #[cfg(test)]
84//! mod tests {
85//!     use super::*;
86//!
87//!     #[test]
88//!     fn increment_works() {
89//!         let mut counter = Counter::default();
90//!         counter.increment();
91//!         assert_eq!(counter.get(), 1);
92//!     }
93//! }
94//! ```
95//!
96//! Run tests using:
97//! ```bash
98//! cargo test
99//! ```
100//* Clippy is giving false positive warnings for this in 1.57 version. Remove this if fixed.
101//* https://github.com/rust-lang/rust-clippy/issues/8091
102#![allow(clippy::redundant_closure)]
103// We want to enable all clippy lints, but some of them generate false positives.
104#![allow(clippy::missing_const_for_fn, clippy::redundant_pub_crate)]
105#![allow(clippy::multiple_bound_locations)]
106#![allow(clippy::needless_lifetimes)]
107
108#[cfg(test)]
109extern crate quickcheck;
110
111/// This attribute macro is used on a struct/enum and its implementations
112/// to generate the necessary code to expose `pub` methods from the contract as well
113/// as generating the glue code to be a valid NEAR contract.
114///
115/// The macro is a syntactic sugar for [**near_bindgen**](near_bindgen) and expands to the [**near_bindgen**](near_bindgen) macro invocations.
116/// Both of them share the same attributes, except for those that are explicitly marked as specific to the [**near**](near) macro. ([1](near#nearcontract_state-annotates-structsenums), [2](near#nearserializers-annotates-structsenums))
117///
118/// # Attributes
119///
120/// ## `#[near(contract_state)]` (annotates structs/enums)
121///
122/// The attribute prepares a struct/enum to be a contract state. Only one contract state is allowed per crate.
123///
124/// A contract type is usually acompanied by an `impl` block, annotated with [`#[near]`](near#near-annotates-impl-blocks).
125///
126/// This attribute is also required to make the [`#[near(contract_metadata(...))]`](near#nearcontract_metadata-annotates-structsenums) attribute work.
127///
128/// `contract_state` is specific to the [near] macro only, not available for [near_bindgen].
129///
130/// ### Basic example
131/// ```rust
132/// use near_sdk::near;
133///
134/// #[near(contract_state)]
135/// pub struct Contract {
136///     greeting: String,
137/// }
138/// ```
139/// which usually comes paired with at least one **impl** block for the contract type,
140/// annotated with a plain `#[near]` attribute:
141///
142/// ### Using SDK collections for storage
143///
144/// If contract state becomes large, collections from following modules can be used:
145///
146/// #### [`store`] module:
147///
148/// ```rust
149/// # use near_sdk_macros::near;
150/// use near_sdk::store::IterableMap;
151///
152/// #[near(contract_state)]
153/// pub struct StatusMessage {
154///    records: IterableMap<String, String>,
155/// }
156/// ```
157///
158/// * list of [**host functions**](store#calls-to-host-functions-used-in-implementation) used for [`store`] implementation
159/// * **FAQ**: mutating state of collections from [`store`] module is only finally persisted on running [`Drop`/`flush`](store#faq-collections-of-this-module-only-persist-on-drop-and-flush)
160///
161/// #### [`collections`] module:
162///
163/// ```rust
164/// # use near_sdk_macros::near;
165/// use near_sdk::collections::LookupMap;
166///
167/// #[near(contract_state)]
168/// pub struct StatusMessage {
169///    records: LookupMap<String, String>,
170/// }
171/// ```
172///
173/// * list of [**host functions**](collections#calls-to-host-functions-used-in-implementation) used for [`collections`] implementation
174///
175/// ### Reference to [Implementation of `#[near(contract_state)]` attribute](near#implementation-of-nearcontract_state-attribute-and-host-functions-calls-used) (How does it work?)
176///
177/// ## `#[near]` (annotates impl blocks)
178///
179/// This macro is used to define the code for view-only and mutating methods for contract types,
180/// annotated by [`#[near(contract_state)]`](near#nearcontract_state-annotates-structsenums).
181///
182/// ### Basic example
183/// ```rust
184/// use near_sdk::{near, log};
185///
186/// # #[near(contract_state)]
187/// # pub struct Contract {
188/// #     greeting: String,
189/// # }
190/// #[near]
191/// impl Contract {
192///     // view method
193///     pub fn get_greeting(&self) -> String {
194///         self.greeting.clone()
195///     }
196///
197///     // mutating method
198///     pub fn set_greeting(&mut self, greeting: String) {
199///         log!("Saving greeting: {greeting}");
200///         self.greeting = greeting;
201///     }
202/// }
203/// ```
204///
205/// ### Reference to [Implementation of `#[near]` macro](near#implementation-of-near-macro-and-host-functions-calls-used) (How does it work?)
206///
207/// ## `#[near(serializers=[...])` (annotates structs/enums)
208///
209/// The attribute makes the struct or enum serializable with either json or borsh. By default, borsh is used.
210///
211/// `serializers` is specific to the [near] macro only, not available for [near_bindgen].
212///
213/// ### Make struct/enum serializable with borsh
214///
215/// ```rust
216/// use near_sdk::near;
217///
218/// #[near(serializers=[borsh])]
219/// pub enum MyEnum {
220///     Variant1,
221/// }
222///
223/// #[near(serializers=[borsh])]
224/// pub struct MyStruct {
225///     pub name: String,
226/// }
227/// ```
228///
229/// ### Make struct/enum serializable with json
230///
231/// ```rust
232/// use near_sdk::near;
233/// #[near(serializers=[json])]
234/// pub enum MyEnum {
235///     Variant1,
236/// }
237///
238/// #[near(serializers=[json])]
239/// pub struct MyStruct {
240///     pub name: String,
241/// }
242/// ```
243///
244/// ### Make struct/enum serializable with both borsh and json
245///
246/// ```rust
247/// use near_sdk::near;
248/// #[near(serializers=[borsh, json])]
249/// pub enum MyEnum {
250///     Variant1,
251/// }
252///
253/// #[near(serializers=[borsh, json])]
254/// pub struct MyStruct {
255///     pub name: String,
256/// }
257/// ```
258///
259/// ## `#[serializer(...)]` (annotates function arguments)
260///
261/// The attribute makes the function argument deserializable from [`Vec`]<[`u8`]> with either json or borsh. By default, json is used.
262/// Please, note that all the arguments of the function should be using the same deserializer.
263///
264/// NOTE: a more correct name for the attribute would be `argument_deserializer`, but it's `serializer` for historic reasons.
265///
266/// ### Basic example
267///
268/// ```rust
269/// use near_sdk::near;
270///# #[near(contract_state)]
271///# pub struct Contract {}
272///
273/// #[near]
274/// impl Contract {
275///     pub fn borsh_arguments(&self, #[serializer(borsh)] a: String, #[serializer(borsh)] b: String) {}
276/// }
277/// ```
278///
279/// ### Implementation of `#[serializer(...)]` attribute and **host functions** calls used
280///
281/// In a nutshell and if the details of [ABI](https://github.com/near/abi) generation layer are put aside,
282///
283/// using the attribute allows to replace default [`serde_json::from_slice`] with [`borsh::from_slice`].
284///
285/// A bit more thoroughly the effect of the attribute is described in (step **3.1**, [`#[near]` on mutating method](near#for-above-mutating-method-near-macro-defines-the-following-function)).
286///
287/// ## `#[init]` (annotates methods of a type in its `impl` block)
288///
289/// Contract initialization method annotation. More details can be found [here](https://docs.near.org/build/smart-contracts/anatomy/storage#initializing-the-state)
290///
291/// By default, the `Default::default()` implementation of a contract will be used to initialize a contract.
292/// There can be a custom initialization function which takes parameters or performs custom logic with the following `#[init]` annotation.
293///
294/// You can provide several initialization functions.
295///
296/// ### Basic example
297///
298/// ```rust
299/// use near_sdk::{log, near};
300///
301/// #[near(contract_state)]
302/// #[derive(Default)]
303/// pub struct Counter {
304///     value: u64,
305/// }
306///
307/// #[near]
308/// impl Counter {
309///     #[init]
310///     pub fn new(value: u64) -> Self {
311///         log!("Custom counter initialization!");
312///         Self { value }
313///     }
314/// }
315/// ```
316///
317/// ## `#[payable]` (annotates methods of a type in its `impl` block)
318///
319/// Specifies that the method can accept NEAR tokens. More details can be found [here](https://docs.near.org/build/smart-contracts/anatomy/functions#payable-functions)
320///
321/// Methods can be annotated with `#[payable]` to allow tokens to be transferred with the method invocation. For more information, see payable methods.
322///
323/// To declare a function as payable, use the `#[payable]` annotation as follows:
324///
325/// ### Basic example
326///
327/// ```rust
328///use near_sdk::near;
329///
330/// #[near(contract_state)]
331/// #[derive(Default)]
332/// pub struct Counter {
333///     val: i8,
334/// }
335///
336/// #[near]
337/// impl Counter {
338///     #[payable]
339///     pub fn my_method(&mut self) {
340///        //...
341///     }
342/// }
343/// ```
344///
345/// ## `#[private]` (annotates methods of a type in its `impl` block)]
346///
347/// The attribute forbids to call the method except from within the contract.
348/// This is useful for internal methods that should not be called from outside the contract.
349///
350/// More details can be found [here](https://docs.near.org/build/smart-contracts/anatomy/functions#private-functions)
351///
352/// ### Basic example
353///
354/// ```rust
355/// use near_sdk::near;
356///
357/// #[near(contract_state)]
358/// #[derive(Default)]
359/// pub struct Counter {
360///     val: u64,
361/// }
362///
363/// #[near]
364/// impl Counter {
365///     #[private]
366///     pub fn my_method(&mut self) {
367///         // ...
368///     }
369/// }
370/// ```
371///
372/// ## `#[deny_unknown_arguments]` (annotates methods of a type in its `impl` block)]
373///
374/// Specifies that the method call should error during deserialization if any unknown fields are present in the input.
375/// This helps ensure data integrity by rejecting potentially malformed input.
376///
377/// Without this attribute, unknown fields are silently ignored during deserialization.
378///
379/// Implementation uses [`deny_unknown_fields`](https://serde.rs/container-attrs.html#deny_unknown_fields) `serde`'s attribute.
380///
381/// In the following example call of `my_method` with
382/// ```json,ignore
383/// {
384///     "description": "value of description"
385/// }
386/// ```
387/// payload works, but call of `my_method` with
388///
389/// ```json,ignore
390/// {
391///     "description": "value of description",
392///     "unknown_field": "what"
393/// }
394/// ```
395/// payload is declined with a `FunctionCallError(ExecutionError("Smart contract panicked: Failed to deserialize input from JSON."))` error.
396///
397/// ### Basic example
398///
399/// ```rust
400/// use near_sdk::near;
401///
402/// #[near(contract_state)]
403/// #[derive(Default)]
404/// pub struct Counter {
405///     val: u64,
406/// }
407///
408/// #[near]
409/// impl Counter {
410///     #[deny_unknown_arguments]
411///     pub fn my_method(&mut self, description: String) {
412///         // ...
413///     }
414/// }
415/// ```
416///
417/// This attribute is not supposed to be used together with [`#[serializer(borsh)]`](`near#serializer-annotates-function-arguments`)
418/// arguments' serializer, and assumes that default `json` is used.
419///
420/// If `borsh` is used on arguments, usage of `deny_unknown_arguments` on method is a no-op.
421///
422///
423/// ## `#[result_serializer(...)]` (annotates methods of a type in its `impl` block)
424///
425/// The attribute defines the serializer for function return serialization.
426/// Only one of `borsh` or `json` can be specified.
427///
428/// ```rust
429/// use near_sdk::near;
430///
431/// # #[near(contract_state)]
432/// # struct MyContract {
433/// #   pub name: String,
434/// # }
435///
436/// #[near]
437/// impl MyContract {
438///    #[result_serializer(borsh)]
439///    pub fn borsh_return_value(&self) -> String {
440///         "hello_world".to_string()
441///    }
442/// }
443/// ```
444///
445/// ### Implementation of `#[result_serializer(...)]` attribute and **host functions** calls used
446///
447/// In a nutshell and if the details of [ABI](https://github.com/near/abi) generation layer are put aside,
448///
449/// using the attribute allows to replace default [`serde_json::to_vec`] with [`borsh::to_vec`].
450///
451/// A bit more thoroughly the effect of the attribute is described in (step **4.1**, [`#[near] on view method`](near#for-above-view-method-near-macro-defines-the-following-function)).
452///
453/// ## `#[handle_result]` (annotates methods of a type in its `impl` block)
454///
455/// Have `#[handle_result]` to Support Result types regardless of how they're referred to
456/// Function marked with `#[handle_result]` should return `Result<T, E>` (where E implements [FunctionError]).
457/// If you're trying to use a type alias for `Result`, try `#[handle_result(aliased)]`
458///
459/// ### Basic error handling with Result
460///
461/// ```rust
462/// use near_sdk::{near, AccountId, Promise, PromiseError};
463///
464/// #[near(contract_state)]
465/// #[derive(Default)]
466/// pub struct Counter {
467///     val: u64,
468/// }
469///
470/// #[near]
471/// impl Counter {
472///     #[handle_result]
473///     pub fn some_function2(
474///         &self,
475///     ) -> Result<(), &'static str> {
476///         Err("error")
477///     }
478/// }
479/// ```
480///
481/// ### Typed error handling
482///
483/// This example shows how to use error handling in a contract when the error are defined in the contract.
484/// This way the contract can utilize result types and panic with the type using its [ToString] implementation
485///
486/// ```rust
487/// use near_sdk::{near, FunctionError};
488///
489/// #[derive(FunctionError)]
490/// pub enum MyError {
491///     SomePanicError,
492/// }
493///
494/// impl std::fmt::Display for MyError {
495///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
496///         match self {
497///             MyError::SomePanicError => write!(f, "Panic error message that would be displayed to the user"),
498///         }
499///     }
500/// }
501///# #[near(contract_state)]
502///# #[derive(Default)]
503///# pub struct Counter {
504///#    val: u64,
505///# }
506///
507/// #[near]
508/// impl Counter {
509///     #[handle_result]
510///     pub fn some_function(&self) -> Result<(), MyError> {
511///         if self.val == 0 {
512///             return Err(MyError::SomePanicError);
513///         }
514///         Ok(())
515///     }
516/// }
517/// ```
518///
519/// ## `#[callback_unwrap]` (annotates function arguments)
520///
521/// Automatically unwraps the successful result of a callback from a cross-contract call.
522/// Used on parameters in callback methods that are invoked as part of a cross-contract call chain.
523/// If the promise fails, the method will panic with the error message.
524///
525/// This attribute is commonly used with [`Promise`] or [`PromiseOrValue<T>`] as the return type of another contract method,
526/// whose return value will be passed as argument to `#[callback_unwrap]`-annotated argument
527///
528/// ### Example with Cross-Contract Factorial:
529///
530/// In the example:
531///   - lower level [`env::promise_create`], [`env::promise_then`] and [`env::promise_return`] are used in
532///     `factorial` method to set up a callback of `factorial_mult` with result of factorial for `(n-1)`
533///   - [`#[private]`](near#private-annotates-methods-of-a-type-in-its-impl-block) on `factorial_mult` is used to
534///     to allow only calling `factorial_mult` from factorial contract method by `CrossContract` itself
535///     and disallow for it to be called externally by users
536///
537/// ```rust
538/// use near_sdk::{near, env, log, NearToken, Gas};
539///
540/// // Prepaid gas for a single (not inclusive of recursion) `factorial` call.
541/// const FACTORIAL_CALL_GAS: Gas = Gas::from_tgas(20);
542///
543/// // Prepaid gas for a single `factorial_mult` call.
544/// const FACTORIAL_MULT_CALL_GAS: Gas = Gas::from_tgas(10);
545///
546/// #[near(contract_state)]
547/// #[derive(Default)]
548/// pub struct CrossContract {}
549///
550/// #[near]
551/// impl CrossContract {
552///     pub fn factorial(&self, n: u32) {
553///         if n <= 1 {
554///             env::value_return(&serde_json::to_vec(&1u32).unwrap());
555///             return;
556///         }
557///         let account_id = env::current_account_id();
558///         let prepaid_gas = env::prepaid_gas().saturating_sub(FACTORIAL_CALL_GAS);
559///         let promise0 = env::promise_create(
560///             account_id.clone(),
561///             "factorial",
562///             &serde_json::to_vec(&(n - 1,)).unwrap(),
563///             NearToken::from_near(0),
564///             prepaid_gas.saturating_sub(FACTORIAL_MULT_CALL_GAS),
565///         );
566///         let promise1 = env::promise_then(
567///             promise0,
568///             account_id,
569///             "factorial_mult",
570///             &serde_json::to_vec(&(n,)).unwrap(),
571///             NearToken::from_near(0),
572///             FACTORIAL_MULT_CALL_GAS,
573///         );
574///         env::promise_return(promise1);
575///     }
576///
577///     #[private]
578///     pub fn factorial_mult(&self, n: u32, #[callback_unwrap] factorial_n_minus_one_result: u32) -> u32 {
579///         log!("Received n: {:?}", n);
580///         log!("Received factorial_n_minus_one_result: {:?}", factorial_n_minus_one_result);
581///
582///         let result = n * factorial_n_minus_one_result;
583///
584///         log!("Multiplied {:?}", result.clone());
585///         result
586///     }
587/// }
588/// ```
589/// which has the following lines in a `factorial`'s view call log:
590///
591/// ```bash,ignore
592/// logs: [
593///     "Received n: 5",
594///     "Received factorial_n_minus_one_result: 24",
595///     "Multiplied 120",
596/// ],
597/// ```
598///
599/// ### Other examples within repo:
600///
601/// - `Cross-Contract Factorial` again [examples/cross-contract-calls](https://github.com/near/near-sdk-rs/blob/9596835369467cac6198e8de9a4b72a38deee4a5/examples/cross-contract-calls/high-level/src/lib.rs?plain=1#L26)
602///   - same example as [above](near#example-with-cross-contract-factorial), but uses [`Promise::then`] instead of [`env`](mod@env) host functions calls to set up a callback of `factorial_mult`
603/// - [examples/callback-results](https://github.com/near/near-sdk-rs/tree/master/examples/callback-results/src/lib.rs?plain=1#L51)
604///
605/// ### Reference to  [Implementation of `#[callback_unwrap]` attribute](near#implementation-of-callback_unwrap-attribute-and-host-functions-calls-used)
606///
607/// ## `#[near(event_json(...))]` (annotates enums)
608///
609/// By passing `event_json` as an argument `near` will generate the relevant code to format events
610/// according to [NEP-297](https://github.com/near/NEPs/blob/master/neps/nep-0297.md)
611///
612/// For parameter serialization, this macro will generate a wrapper struct to include the NEP-297 standard fields `standard` and `version`
613/// as well as include serialization reformatting to include the `event` and `data` fields automatically.
614/// The `standard` and `version` values must be included in the enum and variant declaration (see example below).
615/// By default this will be JSON deserialized with `serde`
616///
617/// The version is required to allow backward compatibility. The older back-end will use the version field to determine if the event is supported.
618///
619/// ### Basic example
620///
621/// ```rust
622/// use near_sdk::{near, AccountId};
623///
624/// # #[near(contract_state)]
625/// # pub struct Contract {
626/// #    data: i8,
627/// # }
628/// #[near(event_json(standard = "nepXXX"))]
629/// pub enum MyEvents {
630///    #[event_version("1.0.0")]
631///    Swap { token_in: AccountId, token_out: AccountId, amount_in: u128, amount_out: u128 },
632///
633///    #[event_version("2.0.0")]
634///    StringEvent(String),
635///
636///    #[event_version("3.0.0")]
637///    EmptyEvent
638/// }
639///
640/// #[near]
641/// impl Contract {
642///     pub fn some_function(&self) {
643///         MyEvents::StringEvent(
644///             String::from("some_string")
645///         ).emit();
646///     }
647///
648/// }
649/// ```
650///
651/// ## `#[near(contract_metadata(...))]` (annotates structs/enums)
652///
653/// By using `contract_metadata` as an argument `near` will populate the contract metadata
654/// according to [`NEP-330`](<https://github.com/near/NEPs/blob/master/neps/nep-0330.md>) standard. This still applies even when `#[near]` is used without
655/// any arguments.
656///
657/// All fields(version, link) are optional and will be populated with defaults from the Cargo.toml file if not specified.
658/// The `standard` will be populated with `nep330` by default.
659///
660/// **Any additional standards can be added and should be specified using the `standard` attribute.**
661///
662/// The `contract_source_metadata()` view function will be added and can be used to retrieve the source metadata.
663/// Also, the source metadata will be stored as a constant, `CONTRACT_SOURCE_METADATA`, in the contract code.
664///
665/// **Please note that the `contract_metadata` will be ignored if [`#[near(contract_state)]`](near#nearcontract_state-annotates-structsenums) is not used**.
666///
667/// ### Basic example
668///
669/// ```rust
670/// use near_sdk::near;
671///
672/// #[near(contract_state, contract_metadata(
673///     version = "39f2d2646f2f60e18ab53337501370dc02a5661c",
674///     link = "https://github.com/near-examples/nft-tutorial",
675///     standard(standard = "nep171", version = "1.0.0"),
676///     standard(standard = "nep177", version = "2.0.0"),
677/// ))]
678/// struct Contract {}
679/// ```
680///
681/// ---
682///
683/// ## Implementation of `#[near(contract_state)]` attribute and **host functions** calls used
684///
685/// This heading describes [`#[near(contract_state)]`](near#nearcontract_state-annotates-structsenums).
686///
687/// In a nutshell and if the details of [ABI](https://github.com/near/abi) generation layer are put aside,
688///
689/// ```rust
690/// # use near_sdk::near;
691/// #[near(contract_state)]
692/// pub struct Contract { /* .. */ }
693/// ```
694///
695/// 1. Macro adds derived implementations of [`borsh::BorshSerialize`]/[`borsh::BorshSerialize`] for `Contract` type
696/// 2. Macro defines a global `CONTRACT_SOURCE_METADATA` variable, which is a string of json serialization of [`near_contract_standards::contract_metadata::ContractSourceMetadata`](https://docs.rs/near-contract-standards/latest/near_contract_standards/contract_metadata/struct.ContractSourceMetadata.html).
697/// 3. Macro defines `contract_source_metadata` function:
698///     ```rust,no_run
699///     #[no_mangle]
700///     pub extern "C" fn contract_source_metadata() { /* .. */ }
701///     ```
702///    which
703///     1. calls [`env::setup_panic_hook`] host function
704///     2. calls [`env::value_return`] host function with bytes of `CONTRACT_SOURCE_METADATA` from step 2.
705///
706/// ##### using [cargo-expand](https://crates.io/crates/cargo-expand) to view actual macro results
707///
708/// The above is an approximate description of what macro performs.
709///
710/// Running the following in a contract's crate is a way to introspect more details of its operation:
711///
712/// ```bash,ignore
713/// cargo expand --lib --target wasm32-unknown-unknown
714/// # this has additional code generated for ABI layer
715/// cargo expand --lib --features near-sdk/__abi-generate
716/// ```
717///
718/// ---
719///
720/// ## Implementation of `#[near]` macro and **host functions** calls used
721///
722/// This heading describes [`#[near]` on impl blocks](near#near-annotates-impl-blocks).
723///
724/// In a nutshell and if the details of [ABI](https://github.com/near/abi) generation layer are put aside,
725///
726/// ```rust
727/// # use near_sdk::near;
728/// # #[near(contract_state)]
729/// # pub struct Contract { /* .. */ }
730/// #[near]
731/// impl Contract {
732///     pub fn view_method(&self) -> String { todo!("method body") }
733///
734///     pub fn mutating_method(&mut self, argument: String) { /* .. */ }
735/// }
736/// ```
737///
738/// ##### for above **view** method `#[near]` macro defines the following function:
739///
740/// ```rust,no_run
741/// #[no_mangle]
742/// pub extern "C" fn view_method() { /* .. */ }
743/// ```
744/// which
745///
746/// 1. calls [`env::setup_panic_hook`] host function
747/// 2. calls [`env::state_read`] host function to load `Contract` into a `state` variable
748///     1. `env::state_read`'s result is unwrapped with [`Option::unwrap_or_default`]
749///     2. [`PanicOnDefault`] may be used to NOT let [implementation of `Default` for `Contract`](Default) value become the outcome `Contract`'s `state`, when [`env::state_read`] returns [`Option::None`]
750/// 3. calls original `Contract::view_method(&state)` as defined in `#[near]` annotated [impl block](near#implementation-of-near-macro-and-host-functions-calls-used) and saves
751///    the returned value into a `result` variable
752/// 4. calls [`serde_json::to_vec`] on obtained `result` and saves returned value to `serialized_result` variable
753///     1. `json` format can be changed to serializing with [`borsh::to_vec`] by using [`#[result_serializer(...)]`](`near#result_serializer-annotates-methods-of-a-type-in-its-impl-block`)
754/// 5. if the `serialized_result` is an [`Result::Err`] error, then [`env::panic_str`] host function is called to signal result serialization error
755/// 6. otherwise, if the `serialized_result` is a [`Result::Ok`], then [`env::value_return`] host function is called with unwrapped `serialized_result`
756///
757/// ##### for above **mutating** method `#[near]` macro defines the following function:
758/// ```rust,no_run
759/// #[no_mangle]
760/// pub extern "C" fn mutating_method() { /* ..*/ }
761/// ```
762/// which
763///
764/// 1. calls [`env::setup_panic_hook`] host function
765/// 2. calls [`env::input`] host function and saves it to `input` variable
766/// 3. deserializes `Contract::mutating_method` arguments by calling [`serde_json::from_slice`] on `input` variable and saves it to `deserialized_input` variable
767///     1. `json` format can be changed to deserializing with [`borsh::from_slice`] by using [`#[serializer(...)]`](`near#serializer-annotates-function-arguments`)
768/// 4. if the `deserialized_input` is an [`Result::Err`] error, then [`env::panic_str`] host function is called to signal input deserialization error
769/// 5. otherwise, if the `deserialized_input` is a [`Result::Ok`], `deserialized_input` is unwrapped and saved to `deserialized_input_success` variable
770/// 6. calls [`env::state_read`] host function to load `Contract` into a `state` variable
771///     1. `env::state_read`'s result is unwrapped with [`Option::unwrap_or_default`]
772///     2. [`PanicOnDefault`] may be used to NOT let [implementation of `Default` for `Contract`](Default) value become the outcome `Contract`'s `state`, when [`env::state_read`] returns [`Option::None`]
773/// 7. calls original `Contract::mutating_method(&mut state, deserialized_input_success.argument)` as defined in `#[near]` annotated [impl block](near#implementation-of-near-macro-and-host-functions-calls-used)
774/// 8. calls [`env::state_write`] with `&state` as argument.
775///
776/// ---
777///
778/// ## Implementation of `#[callback_unwrap]` attribute and **host functions** calls used
779///
780/// This heading describes [`#[callback_unwrap]`](near#callback_unwrap-annotates-function-arguments).
781///
782/// In a nutshell and if the details of [ABI](https://github.com/near/abi) generation layer are put aside,
783///
784/// ```rust
785/// # use near_sdk::near;
786/// # #[near(contract_state)]
787/// # pub struct Contract { /* .. */ }
788/// #[near]
789/// impl Contract {
790///     pub fn method(
791///         &mut self,
792///         regular: String,
793///         #[callback_unwrap] one: String,
794///         #[callback_unwrap] two: String
795///     ) { /* .. */ }
796/// }
797/// ```
798///
799/// For above `method` using the attribute on arguments, changes the body of function generated in  [`#[near]` on mutating method](near#for-above-mutating-method-near-macro-defines-the-following-function)
800///
801/// ```rust,no_run
802/// #[no_mangle]
803/// pub extern "C" fn method() { /* .. */ }
804/// ```
805///
806/// in the following way:
807///
808/// 1. arguments, annotated with `#[callback_unwrap]`, are no longer expected to be included into `input`,
809///    deserialized in (step **3**, [`#[near]` on mutating method](near#for-above-mutating-method-near-macro-defines-the-following-function)).
810/// 2. for each argument, annotated with `#[callback_unwrap]`:
811///     1. [`env::promise_result`] host function is called with corresponding index, starting from 0
812///        (`0u64` for argument `one`, `1u64` for argument `two` above), and saved into `promise_result` variable
813///     2. if the `promise_result` is a [`PromiseResult::Failed`] error, then [`env::panic_str`] host function is called to signal callback computation error
814///     3. otherwise, if the `promise_result` is a [`PromiseResult::Successful`], it's unwrapped and saved to a `data` variable
815///     4. `data` is deserialized similar to that as usual (step **3**, [`#[near]` on mutating method](near#for-above-mutating-method-near-macro-defines-the-following-function)),
816///        and saved to `deserialized_n_promise` variable
817/// 3. counterpart of (step **7**, [`#[near]` on mutating method](near#for-above-mutating-method-near-macro-defines-the-following-function)):
818///    original method is called `Contract::method(&mut state, deserialized_input_success.regular, deserialized_0_promise, deserialized_1_promise)`,
819///    as defined in `#[near]` annotated impl block
820///
821/// ---
822pub use near_sdk_macros::near;
823
824/// This macro is deprecated. Use [near] instead. The difference between `#[near]` and `#[near_bindgen]` is that
825/// with `#[near_bindgen]` you have to manually add boilerplate code for structs and enums so that they become Json- and Borsh-serializable:
826/// ```rust
827/// use near_sdk::{near_bindgen, NearSchema, borsh::{BorshSerialize, BorshDeserialize}};
828///
829/// #[near_bindgen]
830/// #[derive(BorshSerialize, BorshDeserialize, NearSchema)]
831/// #[borsh(crate = "near_sdk::borsh")]
832/// struct MyStruct {
833///    pub name: String,
834/// }
835/// ```
836/// Instead of:
837/// ```rust
838/// use near_sdk::near;
839///
840/// #[near(serializers=[borsh])]
841/// struct MyStruct {
842///     pub name: String,
843/// }
844/// ```
845pub use near_sdk_macros::near_bindgen;
846
847/// `ext_contract` takes a Rust Trait and converts it to a module with static methods.
848/// Each of these static methods takes positional arguments defined by the Trait,
849/// then the receiver_id, the attached deposit and the amount of gas and returns a new Promise.
850///
851/// ## Examples
852///
853/// ```rust
854/// use near_sdk::{AccountId,ext_contract, near, Promise, Gas};
855///
856/// #[near(contract_state)]
857/// struct Contract {
858///     calculator_account: AccountId,
859/// }
860///
861/// #[ext_contract(ext_calculator)]
862/// trait Calculator {
863///     fn mult(&self, a: u64, b: u64) -> u128;
864///     fn sum(&self, a: u128, b: u128) -> u128;
865/// }
866///
867/// #[near]
868/// impl Contract {
869///    pub fn multiply_by_five(&mut self, number: u64) -> Promise {
870///        ext_calculator::ext(self.calculator_account.clone())
871///            .with_static_gas(Gas::from_tgas(5))
872///            .mult(number, 5)
873///    }
874/// }
875///
876/// ```
877///
878/// See more information about role of ext_contract in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/crosscontract)
879pub use near_sdk_macros::ext_contract;
880
881/// `BorshStorageKey` generates implementation for [BorshIntoStorageKey](crate::__private::BorshIntoStorageKey) trait.
882/// It allows the type to be passed as a unique prefix for persistent collections.
883/// The type should also implement or derive [BorshSerialize](borsh::BorshSerialize) trait.
884///
885/// More information about storage keys in [NEAR documentation](https://docs.near.org/build/smart-contracts/anatomy/storage)
886/// ## Example
887/// ```rust
888/// use near_sdk::{BorshStorageKey, collections::Vector, near};
889///
890/// #[near(serializers=[borsh])]
891/// #[derive(BorshStorageKey)]
892/// pub enum StorageKey {
893///     Messages,
894/// }
895///
896/// // Define the contract structure
897/// #[near(contract_state)]
898/// pub struct Contract {
899///     messages: Vector<String>
900/// }
901///
902/// // Define the default, which automatically initializes the contract
903/// impl Default for Contract {
904///     fn default() -> Self {
905///         Self {
906///             messages: Vector::new(StorageKey::Messages)
907///         }
908///     }
909/// }
910/// ```
911pub use near_sdk_macros::BorshStorageKey;
912
913/// `PanicOnDefault` generates implementation for `Default` trait that panics with the following
914/// message `The contract is not initialized` when `default()` is called.
915/// This is a helpful macro in case the contract is required to be initialized with either `init` or
916/// `init(rust_state)`
917///
918/// ## Example
919/// ```rust
920/// use near_sdk::{PanicOnDefault, near};
921///
922/// #[near(contract_state)]
923/// #[derive(PanicOnDefault)]
924/// pub struct Contract {
925///     pub name: String,
926/// }
927/// ```
928pub use near_sdk_macros::PanicOnDefault;
929
930/// NOTE: This is an internal implementation for `#[near_bindgen(events(standard = ...))]` attribute.
931/// Please use [near] instead.
932///
933/// This derive macro is used to inject the necessary wrapper and logic to auto format
934/// standard event logs and generate the `emit` function, and event version.
935///
936/// The macro is not for public use.
937pub use near_sdk_macros::EventMetadata;
938
939/// `NearSchema` is a derive macro that generates `BorshSchema` and / or `JsonSchema` implementations.
940/// Use `#[abi(json)]` attribute to generate code for `JsonSchema`. And `#[abi(borsh)]` for `BorshSchema`.
941/// You can use both and none as well.
942/// ## Example
943/// ```rust
944/// use near_sdk_macros::NearSchema;
945///
946/// #[derive(NearSchema)]
947/// #[abi(borsh)]
948/// struct Value {
949///    field: String,
950/// }
951/// ```
952/// In this example, BorshSchema will be generated for `Value` struct.
953pub use near_sdk_macros::NearSchema;
954
955/// `FunctionError` generates implementation for `near_sdk::FunctionError` trait.
956/// It allows contract runtime to panic with the type using its [ToString] implementation
957/// as the message.
958/// ## Example
959/// ```rust
960/// use near_sdk::{FunctionError, near};
961///
962/// #[derive(FunctionError)]
963/// pub enum MyError {
964///     Error,
965/// }
966///
967/// impl std::fmt::Display for MyError {
968///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
969///         match self {
970///             MyError::Error => write!(f, "Error"),
971///         }
972///     }
973/// }
974///
975/// #[near(contract_state)]
976/// pub struct Contract {}
977///
978/// #[near]
979/// impl Contract {
980///     #[handle_result]
981///     pub fn some_function(&self) -> Result<(), MyError> {
982///         Err(MyError::Error)
983///     }
984/// }
985/// ```
986pub use near_sdk_macros::FunctionError;
987
988pub mod store;
989
990#[cfg(feature = "legacy")]
991pub mod collections;
992mod environment;
993pub use environment::env;
994
995#[cfg(feature = "unstable")]
996pub use near_sys as sys;
997
998mod promise;
999pub use promise::{Allowance, Promise, PromiseOrValue};
1000
1001// Private types just used within macro generation, not stable to be used.
1002#[doc(hidden)]
1003#[path = "private/mod.rs"]
1004pub mod __private;
1005
1006pub mod json_types;
1007
1008mod types;
1009pub use crate::types::*;
1010
1011#[cfg(all(feature = "unit-testing", not(target_arch = "wasm32")))]
1012pub use environment::mock;
1013#[cfg(all(feature = "unit-testing", not(target_arch = "wasm32")))]
1014pub use environment::mock::test_vm_config;
1015#[cfg(all(feature = "unit-testing", not(target_arch = "wasm32")))]
1016// Re-export to avoid breakages
1017pub use environment::mock::MockedBlockchain;
1018#[cfg(all(feature = "unit-testing", not(target_arch = "wasm32")))]
1019pub use test_utils::context::VMContext;
1020
1021pub mod utils;
1022pub use crate::utils::storage_key_impl::IntoStorageKey;
1023pub use crate::utils::*;
1024
1025#[cfg(feature = "__macro-docs")]
1026pub mod near_annotations;
1027
1028#[cfg(all(feature = "unit-testing", not(target_arch = "wasm32")))]
1029pub mod test_utils;
1030
1031// Set up global allocator by default if custom-allocator feature is not set in wasm32 architecture.
1032#[cfg(all(feature = "wee_alloc", target_arch = "wasm32"))]
1033#[global_allocator]
1034static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
1035
1036// Exporting common crates
1037
1038pub use base64;
1039pub use borsh;
1040pub use bs58;
1041#[cfg(feature = "abi")]
1042pub use schemars;
1043pub use serde;
1044pub use serde_json;