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, "
" );
    }
}

extern "C" {

    /**
     * init为初始化函数,当合约上传或更新的时候执行。
     */
    void init()  {
       eosio::print( "Init World!
" );
    }
    /// 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, "
" );
        }

    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
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
原文地址:https://www.cnblogs.com/feng9exe/p/9897439.html