前提需要搭建好开发环境,可以参考之前的文章:EOS 开发环境搭建。
创建合约目录
cd /Users/mac/eos/contracts
mkdir hello
cd hello
合约代码
创建合约文件:
touch hello.cpp
内容:
#include
#include
using namespace eosio;
class hello : public contract {
public:
using contract::contract;
[[eosio::action]]
void hi( name user ) {
print( "Hello, ", name{user});
}
};
EOSIO_DISPATCH( hello, (hi))
编译
eosio-cpp -o hello.wasm hello.cpp --abigen
为合约创建一个 account
当一个合约被部署了,它是部署在一个 account 上,这个 account 成为了合约的接口。
创建一个 account :
cleos create account eosio hello EOS5QyuomJdvmynsGH5EAnK3i879nZfT4v97CZ3KXFxYvehm77aio -p eosio@active
key 可以通过命令查询:
cleos wallet keys
设置合约
cleos set contract hello /Users/mac/eos/contracts/hello -p hello@active
# 输出
Reading WASM from /Users/mac/eos/contracts/hello/hello.wasm...
Publishing contract...
executed transaction: ed2521e09e61bdd04ef57c371f1a08a1f541d7b0af6986bd1c145ba8018cfa3a 1432 bytes 1132 us
# eosio <= eosio::setcode {"account":"hello","vmtype":0,"vmversion":0,"code":"0061736d0100000001390b60027f7e006000017f60027f7f...
# eosio <= eosio::setabi {"account":"hello","abi":"0e656f73696f3a3a6162692f312e31000102686900010475736572046e616d650100000000...
warning: transaction executed locally, but may not be confirmed by the network yet ]
调用合约
cleos push action hello hi '["bob"]' -p bob@active
# 输出
executed transaction: db32d32a357f734a513ac11400462961858e9fc28c531259dc9fd47566987ff4 104 bytes 537 us
# hello <= hello::hi {"user":"bob"}
>> Hello, bob
添加用户验证
上面的代码可以正常运行,下面添加一个限制:认证的用户必须和参数中的用户名一致。
修改 hi
函数的代码为:
void hi( name user ) {
require_auth( user );
print( "Hello, ", name{user} );
}
重新编译:
eosio-cpp -o hello.wasm hello.cpp --abigen
更新:
cleos set contract hello /Users/mac/eos/contracts/hello -p hello@active
测试:
cleos push action hello hi '["bob"]' -p alice@active
# 输出
Error 3090004: Missing required authority
Ensure that you have the related authority inside your transaction!;
If you are currently using 'cleos push action' command, try to add the relevant authority using -p option.
因为登录的用户是 'alice' 而参数传入的用户名是 'bob',不一致,所以报错。
重新调用:
cleos push action hello hi '["alice"]' -p alice@active
# 输出
executed transaction: 192928e9fa6046f45067f6c1af062a6078dd9d36fc8c279c5e50cb6448e1594c 104 bytes 579 us
# hello <= hello::hi {"user":"alice"}
>> Hello, alice
这回可以了,因为参数 'alice' 是认证用户。