在开始前,建议确认你的 SUI 客户端版本号是否与官方文档要求一致:
sui --version
示例版本号:
sui 1.39.3-homebrew
确保版本号符合文档要求以避免潜在问题。
执行以下命令以生成一个新的合约项目:
sui move new my_first_package
项目生成后,可以查看项目的目录结构:
pwd
示例输出:
/Users/admin/work_atom/move/my_first_package
进入项目的 sources
文件夹:
cd sources
pwd
示例输出:
/Users/admin/work_atom/move/my_first_package/sources
在 sources
文件夹中可以随意创建模块,例如:
ls
示例输出:
github.move math.move my_first_package.move
其中 my_first_package.move
的示例代码如下:
cat my_first_package.move
module my_first_package::my_first_package {
public fun say_hello(name: vector<u8>): vector<u8> {
let mut result = vector::empty<u8>();
vector::append(&mut result, b"hello ");
vector::append(&mut result, name);
result
}
#[test]
public fun test_say_hello() {
let result = say_hello(b"yyle88");
assert!(result == b"hello yyle88", 101);
}
}
其中 math.move
的示例代码如下:
cat math.move
module hello_blockchain::math {
public fun add(a: u64, b: u64): u64 {
return a + b
}
#[test]
public fun test_add() {
let result = add(2, 3);
assert!(result == 5, 101);
}
}
返回项目根目录:
cd ..
pwd
示例输出:
/Users/admin/work_atom/move/my_first_package
编辑项目配置文件 Move.toml
,为新增模块指定地址:
vim Move.toml
在 [addresses]
部分增加 hello_blockchain = "0x0"
:
[addresses]
my_first_package = "0x0"
hello_blockchain = "0x0"
配置完成后,hello_blockchain
模块的地址已被正确设置。
在项目根目录执行以下命令编译合约:
sui move build
示例输出:
UPDATING GIT DEPENDENCY https://github.com/MystenLabs/sui.git
INCLUDING DEPENDENCY Sui
INCLUDING DEPENDENCY MoveStdlib
BUILDING my_first_package
运行以下命令测试合约:
sui move test
示例输出:
INCLUDING DEPENDENCY Sui
INCLUDING DEPENDENCY MoveStdlib
BUILDING my_first_package
Running Move unit tests
[ PASS ] hello_blockchain::math::test_add
[ PASS ] hello_blockchain::github::test_page
[ PASS ] hello_blockchain::github::test_page_sui_go_guide
[ PASS ] my_first_package::my_first_package::test_say_hello
Test result: OK. Total tests: 4; passed: 4; failed: 0
执行以下命令部署合约到区块链:
sui client publish --gas-budget 50000000
示例输出:
UPDATING GIT DEPENDENCY https://github.com/MystenLabs/sui.git
INCLUDING DEPENDENCY Sui
INCLUDING DEPENDENCY MoveStdlib
BUILDING my_first_package
Successfully verified dependencies on-chain against source.
Transaction Digest: HXQT2cv15bABW87o6KUSJxbYuHVHCYGHefWpafLnsC4P
部署成功后,Transaction Digest
就是本次发布的交易哈希(类似 txid
或 txHash
)。你可以通过区块链浏览器查询发布结果:
注意:请避免多次重复发布,否则每次都会生成一个新的合约实例。
合约部署后,即可通过代码调用合约。
请在 GitHub 上给个 ⭐,感谢支持!!!