随着EOS Dawn 3.0发布,智能合约的坑又要从新踩了o(╥﹏╥)o;
3.0不只将原来自己就在链里的基础合约独立出来,简单的介绍见3.0合约改变,合约的书写方式也有巨大变化,相比以前更加“面向对象”;
这边文章就从最简单的hello合约,讲解下,详细的例子会在以后文章介绍;数据库
先来看看2.0的最基础的智能合约如何编写:app
#include <eoslib/eos.hpp> namespace hello { /** * @abi action * @abi table * 上面两行,分别用于在执行eoscpp -g的时候,自动生成action和table */ struct printinfo { account_name sender; eosio::string info; }; void print_hello ( const hello::printinfo& data ) { require_auth(data.sender); eosio::print( "Hello World: ", eosio::name(data.sender), "->", data.info, "\n" ); } } extern "C" { /** * init为初始化函数,当合约上传或更新的时候执行。 */ void init() { eosio::print( "Init World!\n" ); } /// apply函数,执行合约的时候,调用该函数,并根据code、action选择的进行的操做。 void apply( uint64_t code, uint64_t action ) { if( code == N(hello) ) { if( action == N(printinfo) ) { hello::print_hello( eosio::current_message<hello::printinfo>() ); } } else { assert(0, "unknown code"); } } } // extern "C"
重要地方都已经给出解释,之后该格式也不是重点,也不在多解释。函数
而3.0的智能合约更加的“面向对象”,来看看和上面功能同样的智能合约在3.0下的实现方式:ui
/** * @file hello.cpp * @author redbutterfly */ #include <eosiolib/eosio.hpp> #include <eosiolib/print.hpp> using namespace eosio; class hello : public eosio::contract { public: using std::string; using contract::contract; /// 执行eosiocpp 时生成action /// @abi action void printinfo( account_name sender, std::string info ) { eosio::print( "Hello World: ", name{data.sender}, "->", data.info, "\n" ); } private: /// 执行eosiocpp 时生成table /// @abi table struct message { account_name sender; std::string info; /// 序列化该结构,用于table时候查询 EOSLIB_SERIALIZE( message, (sender)(info) ) }; }; EOSIO_ABI( hello, (printinfo) )
能够看出,这种格式比较温馨,面向对象的风格;spa
生成合约的方式依然没有变:3d
eosiocpp -g hello.abi hello.cpp //生成abi文件 eosiocpp -o hello.wast hello.cpp //生成wast文件
而后,使用cleos set contract hello ./hello -p hello
部署便可code
本篇主要简单描述下,EOS Dwan 3.0下,智能合约的新编写方式,下篇写简单数据库功能的智能合约。对象