Expand description
§near-sdk
near-sdk
is a Rust toolkit for developing smart contracts on the NEAR blockchain.
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.
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 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
:
[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:
use near_sdk::{env, near};
#[near(contract_state)]
#[derive(Default)]
pub struct Counter {
value: i32,
}
#[near]
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
Install cargo near in case if you don’t have it:
cargo install --locked cargo-near
Build your contract for the NEAR blockchain:
cargo near build
§Running Unit Tests
Use the following testing setup:
#[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:
cargo test
Re-exports§
pub use near_sys as sys;
pub use base64;
pub use borsh;
pub use bs58;
pub use schemars;
pub use serde;
pub use serde_json;
pub use crate::utils::*;
Modules§
- collections
- Collections that offer an alternative to standard containers from
std::collections::*
by utilizing the underlying blockchain trie storage more efficiently. - 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
. Unless you know what you are doing prefer usingenv::*
whenever possible. In case of cross-contract calls prefer using even higher-level API available throughcallback_args
,callback_args_vec
,ext_contract
,Promise
, andPromiseOrValue
. - json_
types - Helper types for JSON serialization.
- mock
- Mock blockchain utilities. These can only be used inside tests and are not available for a wasm32 target.
- near
#[near]
and#[near_bindgen]
documentation module- store
- Collections and types used when interacting with storage.
- test_
utils - Testing blockchain utilities. These can only be used inside tests and are not available for a wasm32 target.
- utils
- Helper methods that often used in smart contracts.
Macros§
- log
- Helper macro to log a message through
env::log_str
. This macro can be used similar to thestd::format
macro. - require
- Helper macro to create assertions that will panic through the runtime host functions.
- setup_
alloc Deprecated - Deprecated helper function which used to generate code to initialize the
GlobalAllocator
. This is now initialized by default. Disablewee_alloc
feature to configure manually. - testing_
env - Initializes a testing environment to mock interactions which would otherwise go through a
validator node. This macro will initialize or overwrite the
MockedBlockchain
instance for interactions from a smart contract.
Structs§
- Abort
- A simple type used in conjunction with FunctionError representing that the function should abort without a custom message.
- Account
Id - NEAR Account Identifier.
- Account
IdRef - Account identifier. This is the human readable UTF-8 string which is used internally to index accounts on the network and their respective state.
- Gas
- A wrapper struct for
u64
that represents gas. And provides helpful methods to convert to and from tera-gas and giga-gas. - GasWeight
- Weight of unused gas to use with
promise_batch_action_function_call_weight
. - Mocked
Blockchain - Mocked blockchain that can be used in the tests for the smart contracts.
It implements
BlockchainInterface
by redirecting calls toVMLogic
. It unwraps errors ofVMLogic
to cause panic during the unit tests similarly to how errors ofVMLogic
would cause the termination of guest program execution. Unit tests can even assert the expected error message. - Near
Token - A wrapper struct for
u128
that represents tokens. And provides helpful methods to convert with a proper precision. - Promise
- A structure representing a result of the scheduled execution on another contract.
- Promise
Index - 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
and can be used to refer this promise inpromise_then
,promise_batch_create
, and other functions. Example: - Public
Key - Public key in a binary format with base58 string serialization with human-readable curve.
The key types currently supported are
secp256k1
anded25519
. - Runtime
Fees Config - VMContext
- Context for the contract execution.
Enums§
- Allowance
- Allow an access key to spend either an unlimited or limited amount of gas
- Curve
Type - PublicKey curve
- Promise
Error - All error variants which can occur with promise results.
- Promise
OrValue - When the method can return either a promise or a value, it can be called with
PromiseOrValue::Promise
orPromiseOrValue::Value
to specify which one should be returned. - Promise
Result - When there is a callback attached to one or more contract calls the execution results of these calls are available to the contract invoked through the callback.
- Return
Data - VmPromise
Result - When there is a callback attached to one or more contract calls the execution results of these calls are available to the contract invoked through the callback.
Traits§
- Function
Error - Enables contract runtime to panic with the given type. Any error type used in conjunction
with
#[handle_result]
has to implement this trait. - Into
Storage Key - Converts Self into a
Vec<u8>
that is used for a storage key throughinto_storage_key
.
Functions§
Type Aliases§
- Block
Height - Height of the block.
- Block
Height Delta Deprecated - Block height delta that measures the difference between
BlockHeight
s. - Crypto
Hash - Raw type for 32 bytes of the hash.
- Duration
- Raw type for duration in nanoseconds
- Epoch
Height - Height of the epoch.
- GCCount
Deprecated - Iterator
Index Deprecated - Merkle
Hash Deprecated - Hash used by a struct implementing the Merkle tree.
- Nonce
Deprecated - Nonce for transactions.
- NumBlocks
Deprecated - Number of blocks in current group.
- NumSeats
Deprecated - Number of seats of validators (block producer or hidden ones) in current group (settlement).
- NumShards
Deprecated - Number of shards in current group.
- Promise
Id Deprecated - Protocol
Version Deprecated - Receipt
Index Deprecated - An index of Receipt to append an action
- ShardId
Deprecated - Shard index, from 0 to NUM_SHARDS - 1.
- Storage
Usage - StorageUsage is used to count the amount of storage used by a contract.
- Storage
Usage Change Deprecated - StorageUsageChange is used to count the storage usage within a single contract call.
- Timestamp
- Raw type for timestamp in nanoseconds
- Validator
Id Deprecated - Validator identifier in current group.
- Validator
Mask Deprecated - Mask which validators participated in multi sign.
Attribute Macros§
- ext_
contract ext_contract
takes a Rust Trait and converts it to a module with static methods. 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.- near
- 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. - near_
bindgen - 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:
Derive Macros§
- Borsh
Storage Key BorshStorageKey
generates implementation forBorshIntoStorageKey
trait. It allows the type to be passed as a unique prefix for persistent collections. The type should also implement or deriveBorshSerialize
trait.- Event
Metadata - NOTE: This is an internal implementation for
#[near_bindgen(events(standard = ...))]
attribute. - Function
Error FunctionError
generates implementation fornear_sdk::FunctionError
trait. It allows contract runtime to panic with the type using itsToString
implementation as the message.- Near
Schema NearSchema
is a derive macro that generatesBorshSchema
and / orJsonSchema
implementations. Use#[abi(json)]
attribute to generate code forJsonSchema
. And#[abi(borsh)]
forBorshSchema
. You can use both and none as well.- Panic
OnDefault PanicOnDefault
generates implementation forDefault
trait that panics with the following messageThe contract is not initialized
whendefault()
is called. This is a helpful macro in case the contract is required to be initialized with eitherinit
orinit(ignore_state)
.