1. 程式人生 > >EOS Dawn 3.0 智慧合約 -- 新格式

EOS Dawn 3.0 智慧合約 -- 新格式

1、簡介

隨著EOS Dawn 3.0釋出,智慧合約的坑又要重新踩了o(╥﹏╥)o;
3.0不僅將原來本身就在鏈裡的基礎合約獨立出來,簡單的介紹見3.0合約改變,合約的書寫方式也有巨大變化,相比之前更加“面向物件”;
這邊文章就從最簡單的hello合約,講解下,詳細的例子會在之後文章介紹;

2、2.0的合約格式

先來看看2.0的最基礎的智慧合約如何編寫:

#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" 

重要地方都已經給出解釋,以後該格式也不是重點,也不在多解釋。

2、3.0的合約格式

而3.0的智慧合約更加的“面向物件”,來看看和上面功能一樣的智慧合約在3.0下的實現方式:

/**
 * @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) ) 

可以看出,這種格式比較舒適,面向物件的風格;

  • 首先,定義繼承自contract的智慧合約結構體,在public下實現智慧合約的action介面,然後在private下實現table等結構(註釋中的@還是需要新增)
  • 其次,在定義結構體的時候,需要使用EOSLIB_SERIALIZE( structname, (param)...),將結構體進行序列化,table儲存的時候,才能正常序列化;
  • 最後,使用EOSIO_ABI(classname, (action)...),同樣序列化操作,在abi生成的時候,正確生成abi;

3、生成合約檔案

生成合約的方式依然沒有變:

eosiocpp -g hello.abi hello.cpp //生成abi檔案
eosiocpp -o hello.wast hello.cpp //生成wast檔案

然後,使用cleos set contract hello ./hello -p hello部署即可

3、總結

本篇主要簡單描述下,EOS Dwan 3.0下,智慧合約的新編寫方式,下篇寫簡單資料庫功能的智慧合約。



作者:redbutterfly
連結:https://www.jianshu.com/p/03d8b096340c
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯絡作者獲得授權並註明出處。