EOS Dawn 3.0 智能合约 -- 新格式

一、简介

随着EOS Dawn 3.0发布,智能合约的坑又要从新踩了o(╥﹏╥)o;
3.0不只将原来自己就在链里的基础合约独立出来,简单的介绍见3.0合约改变,合约的书写方式也有巨大变化,相比以前更加“面向对象”;
这边文章就从最简单的hello合约,讲解下,详细的例子会在以后文章介绍;数据库

二、2.0的合约格式

先来看看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的智能合约更加的“面向对象”,来看看和上面功能同样的智能合约在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

  • 首先,定义继承自contract的智能合约结构体,在public下实现智能合约的action接口,而后在private下实现table等结构(注释中的@仍是须要添加)
  • 其次,在定义结构体的时候,须要使用EOSLIB_SERIALIZE( structname, (param)...),将结构体进行序列化,table存储的时候,才能正常序列化;
  • 最后,使用EOSIO_ABI(classname, (action)...),一样序列化操做,在abi生成的时候,正确生成abi;

三、生成合约文件

生成合约的方式依然没有变: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下,智能合约的新编写方式,下篇写简单数据库功能的智能合约。对象

做者:redbutterfly 连接:https://www.jianshu.com/p/03d8b096340c 來源:简书 简书著做权归做者全部,任何形式的转载都请联系做者得到受权并注明出处。
相关文章
相关标签/搜索