【许晓笛】 EOS智能合约案例解析(1)
详解 EOS 智能合约的 hpp 文件
为了帮助大家熟悉 EOS 智能合约,EOS 官方提供了一个代币(资产)智能合约 Demo —— eosio.token。eosio.token 智能合约目前还不是特别完善,个别功能还没有完成。但这个示例合约给出了 EOS 官方智能合约开发的标准结构和开发方法,并且真正的 EOS 代币也会借鉴这个示例合约的逻辑,是 EOS 智能合约入门的经典案例。
照例,eosio.token 合约由三个文件(cpp,hpp,abi)文件组成,本篇文章将为大家讲解 eosio.token.hpp 文件。原文件地址:https://github.com/EOSIO/eos/tree/master/contracts/eosio.token
预处理指令 & 头文件
代码的开头声明了头文件,主要是 eos 智能合约的 API 库。
//预处理指令,防止文件被重复包含 pragma once //eos 资产(asset)头文件 include <eosiolib/asset.hpp> //eos 智能合约 API 库 include <eosiolib/eosio.hpp>
构造函数
智能合约的类名可以与智能合约名不同,智能合约的名字是其账户名。构造函数为空,参数为智能合约账户名。
//每个智能合约类都要继承 contract 类
class token : public contract {
public:
//类构造函数
token( account_name self ):contract(self){}
}创建代币函数(action)
声明 create 函数,这个函数用来新建一种代币,并输入代币的各种属性,同时 create 函数也是一个 action。action 是 eos 智能合约的接口函数,定义外界可以对智能合约做什么动作。
//参数:发币者 void create( accountname issuer, //资产最大数目 asset maximumsupply, //资产是否可以冻结 uint8t issuercanfreeze, //资产是否可以召回 uint8t issuercanrecall, //资产是否可以设置白名单 uint8t issuercan_whitelist );
增发代币函数(action)
声明 issue 函数,这个函数用来增发代币,eosio.token 合约并不是新建了代币就会得到代币,新建的代币只是存储了资料,发币者要想获取代币,需要调用 issue action 来获得代币。
//参数:接收新代币账户,新增多少代币,memo void issue( account_name to, asset quantity, string memo );
转账函数(action)
声明 transfer 函数,这个函数用来转账,是代币智能合约最常用的函数。
//发送账户 void transfer( accountname from, //接收账户 accountname to, //代币数量 asset quantity, //memo string memo );
私有数据结构
智能合约需要存储每种代币的资料,还要存储每个账户持有每种代币的数量。
private:
//account 结构体,单个记录账户存储单个代币的情况
struct account {
//资产余额
asset balance;
//账户是否冻结
bool frozen = false;
//账户是否在白名单
bool whitelist = true;
//设置账户主键为代币名称
uint64t primarykey()const { return balance.symbol.name(); }
};
//currencystats 结构体,记录当代币状态信息
struct currencystats {
//流通量
asset supply;
//最大可流通量
asset maxsupply;
//发币者
accountname issuer;
//是否可以冻结
bool canfreeze = true;
//是否可以召回
bool canrecall = true;
//是否可以设置白名单
bool canwhitelist = true;
//是否已经冻结
bool isfrozen = false;
//是否已经设置白名单
bool enforcewhitelist = false;
//设置主键为代币名称
uint64t primarykey()const { return supply.symbol.name(); }
};
//设置一个multiindex类型,存储 account 结构体
typedef eosio::multiindex<N(accounts), account> accounts;
//设置一个multiindex类型,存储 currencystats 结构体
typedef eosio::multiindex<N(stat), currency_stats> stats;私有函数
合约公有两个私有函数,分别是给账户增加某种资产,和给账户减少某种资产。
//增加资产函数:账户,增加数量,代币状态结构体 void subbalance( accountname owner, asset value, const currencystats& st , //ram 资源支付者 accountname rampayer); //减少资产函数:账户,减少数量,代币状态结构体 void addbalance( accountname owner, asset value, const currencystats& st, );
- 点赞
- 收藏
- 关注作者
评论(0)