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