Example
Wrap a struct in #[near_bindgen] and it generates a smart contract compatible with the NEAR blockchain:
Features
-
Unit-testable. Writing unit tests is easy with
near-bindgen:Run unit test the usual way:
-
Asynchronous cross-contract calls. Asynchronous cross-contract calls allow parallel execution of multiple contracts in parallel with subsequent aggregation on another contract.
envexposes the following methods:promise_create-- schedules an execution of a function on some contract;promise_then-- attaches the callback back to the current contract once the function is executed;promise_and-- combinator, allows waiting on several promises simultaneously, before executing the callback;promise_return-- treats the result of execution of the promise as the result of the current function.
Follow examples/cross-contract-high-level to see various usages of cross contract calls, including system-level actions done from inside the contract like balance transfer (examples of other system-level actions are: account creation, access key creation/deletion, contract deployment, etc).
-
Initialization methods. We can define an initialization method that can be used to initialize the state of the contract.
Pre-requisites
To develop Rust contracts you would need to:
- Install Rustup:
|
- Add wasm target to your toolchain:
Writing Rust Contract
You can follow the examples/status-message crate that shows a simple Rust contract.
The general workflow is the following:
-
Create a crate and configure the
Cargo.tomlsimilarly to how it is configured in examples/status-message/Cargo.toml; -
Crate needs to have one
pubstruct that will represent the smart contract itself:- The struct needs to implement
Defaulttrait which NEAR will use to create the initial state of the contract upon its first usage; - The struct also needs to implement
BorshSerializeandBorshDeserializetraits which NEAR will use to save/load contract's internal state;
Here is an example of a smart contract struct:
- The struct needs to implement
-
Define methods that NEAR will expose as smart contract methods:
- You are free to define any methods for the struct but only public methods will be exposed as smart contract methods;
- Methods need to use either
&self,&mut self, orself; - Decorate the
implsection with#[near_bindgen]macro. That is where all the M.A.G.I.C. (Macros-Auto-Generated Injected Code) is happening - If you need to use blockchain interface, e.g. to get the current account id then you can access it with
env::*;
Here is an example of smart contract methods:
Building Rust Contract
We can build the contract using rustc:
RUSTFLAGS='-C link-arg=-s'