合约编写部署和执行

假设你已经安装了EOSIO并且启动了nodeos。

创建钱包

1
2
3
4
5
$ cleos wallet create -n mywallet
Creating wallet: mywallet
Save password to use in the future to unlock this wallet.
Without password imported keys will not be retrievable.
"PW5KTrGBhmMeDAZxM69PgZxcHXaT2aaebFRWriZq5PDshPUaowpJF"

使用钱包之前,需要解锁钱包:

1
2
$ cleos wallet unlock --password PW5KTrGBhmMeDAZxM69PgZxcHXaT2aaebFRWriZq5PDshPUaowpJF
Unlocked: default

上面的命令你的密码将会记录到shell历史中,更安全的,你可以通过下面的方法解锁:

1
2
$ cleos wallet unlock
password:

你不使用它的时候,锁定它是一个良好的习惯:

1
2
$ cleos wallet lock
Locked: default

Bios关键的系统合约

EOS相当于一个操作系统,而Bios就是这个系统的引导。进入到EOSIO的source code root目录下:

1
2
3
4
5
6
7
$ cleos set contract eosio build/contracts/eosio.bios -p eosio
Reading WAST...
Assembling WASM...
Publishing contract...
executed transaction: 414cf0dc7740d22474992779b2416b0eabdbc91522c16521307dd682051af083 4068 bytes 10000 cycles
# eosio <= eosio::setcode {"account":"eosio","vmtype":0,"vmversion":0,"code":"0061736d0100000001ab011960037f7e7f0060057f7e7e7e...
# eosio <= eosio::setabi {"account":"eosio","abi":{"types":[],"structs":[{"name":"set_account_limits","base":"","fields":[{"n...

创建账户

首先需要为账户创建一个key:

1
2
3
$ cleos create key
Private key: 5JiconQnk5WTpAbX5zcfkgXHhuki6Yy2U2zYKQmL5ovLUKprANN
Public key: EOS6oPBCtWDzeRBxFMHZebxTgHFFybYqurt8GLwMSHabEkZk4tYku

然后把key导入钱包:

1
2
$ cleos wallet import 5JiconQnk5WTpAbX5zcfkgXHhuki6Yy2U2zYKQmL5ovLUKprANN -n mywallet
imported private key for: EOS6oPBCtWDzeRBxFMHZebxTgHFFybYqurt8GLwMSHabEkZk4tYku

通过该钱包创建两个账户 tester1tester2

1
2
3
$ cleos create account eosio tester1 EOS6oPBCtWDzeRBxFMHZebxTgHFFybYqurt8GLwMSHabEkZk4tYku EOS6oPBCtWDzeRBxFMHZebxTgHFFybYqurt8GLwMSHabEkZk4tYku
executed transaction: 49b5aad108995ce096a840f2537376ae4cfadc57e06af7b1f435ae4e291991d7 352 bytes 102400 cycles
# eosio <= eosio::newaccount {"creator":"eosio","name":"tester1","owner":{"threshold":1,"keys":[{"key":"EOS6oPBCtWDzeRBxFMHZebxTg...

同理,把”tester1”改为”tester2”即可创建 tester2 账户。

一个简单的合约

建立一个文件夹命名为hello,并且建立一个hello.cpp文件:

1
2
3
$ mkdir hello
$ cd hello
$ touch hello.cpp

hello.cpp中输入以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <eosiolib/eosio.hpp>
#include <eosiolib/print.hpp>
using namespace eosio;

class hello : public eosio::contract {
public:
using contract::contract;

/// @abi action
void hi( account_name user ) {
print( "Hello, ", name{user} );
}
};

EOSIO_ABI( hello, (hi) )

编译出wast和abi文件,过程中可能会出现warning,可以暂时不需要理会:

1
2
$ eosiocpp -o hello.wast hello.cpp
$ eosiocpp -g hello.abi hello.cpp

接下来通过下面命令部署合约:

1
$ cleos set contract tester1 ../hello -p tester1

现在,我们试着运行一下合约:

1
2
3
4
$ cleos push action tester1 hi '["tester2"]' -p tester2
executed transaction: 28d92256c8ffd8b0255be324e4596b7c745f50f85722d0c4400471bc184b9a16 244 bytes 1000 cycles
# tester1 <= tester1::hi {"user":"tester2"}
>> Hello, tester2

“-p tester2”表示赋予 tester2 权限。

参考

打赏
  • © 2016-2021 留叶
  • Powered by Hexo Theme Ayer
    • PV:
    • UV:

请我喝杯咖啡吧~

支付宝
微信