NEAR 智能合约开发

Posted mutourend

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NEAR 智能合约开发相关的知识,希望对你有一定的参考价值。

1. 引言

NEAR系列博客有:

NEAR官方推荐使用Rust语言来编写智能合约,然后编译为WebAssembly并部署在NEAR链上。

near.dev中有各种合约示例。

Rust工具中需增加wasm支持:

rustup target add wasm32-unknown-unknown

NEAR合约基本架构为:

.
├── Cargo.toml
└── src
   └── lib.rs

Cargo.toml中引入相应的依赖:

[
dependencies
]
near-sdk = "3.1.0"

[
profile.release
]
codegen-units = 1
# Tell `rustc` to optimize for small code size.
opt-level = "z"
lto = true
debug = false
panic = "abort"
# Opt into extra safety checks on arithmetic operations https://stackoverflow.com/a/64136471/249801
overflow-checks = true

实际合约文件中会引用相关依赖:

use near_sdk::borsh::self, BorshDeserialize, BorshSerialize;
use near_sdk::env, near_bindgen;

主要的合约逻辑体现在lib.rs文件中,定义struct并实现相应的function:

#[near_bindgen]
#[derive(Default, BorshDeserialize, BorshSerialize)]
pub struct Counter 
    val: i8, // i8 is signed. unsigned integers are also available: u8, u16, u32, u64, u128


#[near_bindgen]
impl Counter 

其中

#[near_bindgen]
#[derive(Default, BorshDeserialize, BorshSerialize)]

表示该struct为合约对外主体。

可为合约编写相应的测试用例,测试没问题后,可编译合约:

cargo build --target wasm32-unknown-unknown --release

编译的.wasm文件可部署到NEAR链上。可借助near-cli工具进行部署。

near deploy --wasmFile target/wasm32-unknown-unknown/release/rust_counter_tutorial.wasm --accountId YOUR_ACCOUNT_HERE

合约调用方法可为:

near call YOUR_ACCOUNT_HERE decrement --accountId YOUR_ACCOUNT_HERE

相应结果为:

Scheduling a call: YOUR_ACCOUNT.testnet.decrement()
Receipt: 3HiRrL4fg9Q62VV9aVfAdRk8bQ5nYEYTni9482qjPJ71
    Log [YOUR_ACCOUNT.testnet]: Decreased number to 0
    Log [YOUR_ACCOUNT.testnet]: Make sure you don't overflow, my friend.
Transaction Id 7jVgp677evM7srG697bVWErErzieBWExLvkSiBfvZ8YC

合约查看可为:

near view YOUR_ACCOUNT_HERE get_num --accountId YOUR_ACCOUNT_HERE

相应结果为:

View call: YOUR_ACCOUNT.testnet.get_num()
1

参考资料

[1] NEAR docs Building a Smart Contract in Rust

以上是关于NEAR 智能合约开发的主要内容,如果未能解决你的问题,请参考以下文章

如何让用户在前端部署 NEAR 协议智能合约?

NEAR 协议中存储的智能合约 WebAssembly 二进制文件在哪里/如何?

是否可以在 Rust 的 NEAR 智能合约中验证 NIST P-256 曲线?

ReactJS 不从产品上的智能合约(NEAR)调用方法(查看时测试网不存在)

NEAR,如何实现撤销(汇编脚本)

Near 协议 FunctionCallError(MethodResolveError(MethodNotFound))