编写并发布一个智能合约到Aptos

编写并发布一个智能合约到Aptos

确保已经搭建好了开发环境,参考:

MacOS下搭建Aptos开发环境

新建项目文件夹并初始化

mkdir fist-aptos-module
cd first-aptos-module
aptos move init --name first-aptos-module

执行命令之后会生成如下文件:

编写合约代码

sources/文件夹下面新建first_aptos_module.move文件,并写入以下内容:

module myAccount::first_aptos_module {
  struct Coin has key {
    value: u64
  }

  public fun mint(account: signer, value: u64) {
    move_to(&account, Coin { value })
  }
}

在项目根目录下运行:

aptos move compile

此时应该会报一个错误,提示 myAccount没有赋值。

 module myAccount::first_aptos_module {
  │        ^^^^^^^^^ address 'myAccount' is not assigned a value. Try assigning it a value when calling the compiler

{
  "Error": "Move compilation failed: Compilation error"
}

配置toml文件

要解决上面的问题,需要打开Move.toml文件,做如下修改:

增加一个地址申明:

...
[addresses]
myAccount = "0x190d44266241744264b964a37b8f09863167a12d3e70cda39376cfb4e3561e12"

地址用这个命令可以获取:

aptos config show-profiles

修改之后,再次在根目录运行编译命令:

aptos move compile

不出意外,这次就能够编译成功,项目下会多出一个build文件夹。

发布合约到Aptos 开发网

发布的命令如下:

aptos move publish

运行之后,会提示一个选择,输入yes即可,成功后类似如下信息:

{
  "Result": {
    "transaction_hash": "0x9ad3086bdc80a5a15693f0daf60ac2f84ddbad265fdf4a477b294a0df6b32bb4",
    "gas_used": 6737,
    "gas_unit_price": 100,
    "sender": "f93b5398790d84139b1bd3f3f55ab3ab2bc44752c0d61b15c6d557beaf6e69e2",
    "sequence_number": 0,
    "success": true,
    "timestamp_us": 1667389889957695,
    "version": 26294938,
    "vm_status": "Executed successfully"
  }
}

发布合约到Aptos 主网

之前我们的配置都是默认在开发网下面进行。

接下来首先你需要创建一个Aptos钱包,充值一定数量的$APT到账户,然后拷贝出private key。

准备好主网账户之后,在项目根目录运行下面的命令:

aptos config init --profile mainnetAccount

第一个问题输入 mainnet:

Choose network from [devnet, testnet, mainnet, local, custom | defaults to devnet]
mainnet

第二个问题粘贴主网账户的私钥:

Enter your private key as a hex literal (0x...) [Current: None | No input: Generate new key (or keep one if present

账户初始化成功后,用主网账户发布合约步骤:

  1. 修改Move.toml中的账户地址

  2. 运行发布命令

# 这里指明用 主网账户进行发布
aptos move publish --profile mainnetAccount

到这里,已经成功在Aptos主网上发布了你的模块。

Last updated