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

------------------越是喧嚣的世界,越需要宁静的思考------------------ 合抱之木,生于毫末;九层之台,起于垒土;千里之行,始于足下。 积土成山,风雨兴焉;积水成渊,蛟龙生焉;积善成德,而神明自得,圣心备焉。故不积跬步,无以至千里;不积小流,无以成江海。骐骥一跃,不能十步;驽马十驾,功在不舍。锲而舍之,朽木不折;锲而不舍,金石可镂。蚓无爪牙之利,筋骨之强,上食埃土,下饮黄泉,用心一也。蟹六跪而二螯,非蛇鳝之穴无可寄托者,用心躁也。