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:To run unit tests include
env_testfeature: -
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.
-
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 have:
- Rustup installed and switched to
nightlyRust compiler:
|
Writing Rust Contract
You can follow the test-contract 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'
Running Rust Contract
If you skipped the previous steps you can use the already built contract from examples/status-message/res/status-message.wasm.
Start the local testnet
Let's start the local Near testnet to run the contract on it.
- Make sure you have Docker installed;
- Clone the nearprotocol/nearcore;
- Make sure you are in
masterbranch, then run
It might take a minute to start if you machine have not downloaded the docker image yet.;
Note, the locally running node will create testdir directory where it will keep the node state and the configs, including
the secret key of the validator's account which we can use to create new accounts later.
Create the project and deploy the contract
-
Make sure you have the newest version of near-shell installed by running:
-
Create the near-shell project. This will allow having configuration like URL of the node in the config file instead of passing it with each near-shell command.
; -
Modify the config to point to the local node: open
./src/config.jsin./myprojectand changenodeUrlunderdevelopmentto behttp://localhost:3030. This is how it should look like:case 'development': return -
Create account for your smart contract, e.g. we can use
status_messageas the account identifier:Note,
homeDirshould point to the home directory of the node which contains the secret key which we will use to sign transactions. -
Deploy the contract code to the newly created account:
Call contract functions
-
Let's call the
set_statusfunction on the smart contract:Notice that we use account id
test.nearto call a smart contract deployed tostatus_messageaccount id. The smart contract will remember that accounttest.nearleft the message"Hello", see the implementation in examples/status-message/src/lib.rs. -
Do another call to
get_statusfunction to check that the message was correctly recorded:Observe the output:
Result: Hello -
Do another call to
get_statusbut this time inquire about the account that have not left any messages:Observe the output:
Result: null
Cleaning up
- Stop the node using docker commands:
- Remove the node project directory:
- Remove the node data:
Limitations and Future Work
The current implementation of wasm_bindgen has the following limitations:
- The smart contract struct should be serializable with borsh which is true for most of the structs;
- The method arguments and the return type should be json-serializable, which is true for most of the types, with some exceptions. For instance,
a
HashMap<MyEnum, SomeValue>whereMyEnumis a non-trivial tagged-union with field-structs in variants will not serialize into json, you would need to convert it toVec<(MyEnum, SomeValue)>first. Require arguments and the return type to be json-serializable for compatiblity with contracts written in other languages, like TypeScript; - Smart contract can use
stdbut cannot use wasm-incompatible OS-level features, like threads, file system, network, etc. In the future we will support the file system too; - Smart contracts should be deterministic and time-independent, e.g. we cannot use
Instant::now. In the future we will exposeInstant::now;
We also have the following temporary inefficiencies:
- Current smart contracts do not utilize the trie and do not use state storage efficiently. It is okay for small collections,
but in the future we will provide an alternative
near::collections::{HashMap, HashSet, Vec}that will be using storage in an efficient way; - The current smart contract size is around typically ~80-180Kb, which happens because we compile-in the
bincodeandserde-jsonlibraries. In the future, we will cherry-pick only the necessary components from these libraries. For now you can usewasm-optto slightly shrink the size:
See Binaryen for the installation instructions.