区块链技术与金融区块链大学EOS技术爱好者

EOS开发入门

2019-01-10  本文已影响43人  柏链教育

  在上一篇文章《EOS开发环境搭建》中,我们已经完成了EOS开发环境的搭建,本次为大家带来的是EOS开发入门的相关内容。

1. EOS的合约开发基础

  智能合约是一种旨在以信息化方式传播、验证或执行合同的计算机协议。智能合约允许在没有第三方的情况下进行可信交易,这些交易可追踪且不可逆转。

1.1 所需知识

1.2 c++与智能合约部分语法

struct [[eosio::table]] task {
         uint64_t    taskID;
         name        creator; 
         name        worker;
         asset       bonus;
         uint8_t     status = 0;
         string      remark;
         string      comment;

         uint64_t primary_key()const { return taskID; }
      };

      typedef eosio::multi_index< "tasks"_n, task > tasks;
      //tasks 是最终的表名字,task是结构体名字
tasks tk( _code, _code.value );

    tk.emplace( creator, [&](auto &t){
        t.creator = creator;
        t.worker  = worker;
        t.taskID  = tk.available_primary_key();//主键自动增长
        t.bonus   = taskBonus;
        t.remark  = memo;
    });

1.3 理解abi文件

  这是一个空的abi文件

{
   "version": "eosio::abi/1.0",
   "types": [],
   "structs": [],
   "actions": [],
   "tables": [],
   "ricardian_clauses": [],
   "abi_extensions": [],
   "___comment" : ""
}

  其中structsactionstables可以认为是abi文件的三要素,每个合约内可以有多个action,每个action会执行这样那样的逻辑,需要借助结构体的结构将信息存储或变更保存在区块链中,这个保存的数据我们类比为传统数据库中的表,也就是tables。我们学习智能合约编写主要要写什么?其实就是写一个一个action,类似于rpc中的微服务。与传统数据库编程一样,我们同样也是围绕着table做增删改查操作。

2. EOS的hello智能合约

2.1 编写hello合约

#include <eosiolib/eosio.hpp>
#include <eosiolib/print.hpp>

using namespace eosio;

class hello : public contract {
  public:
      using contract::contract;

      [[eosio::action]]
      void hi( name user ) {
         print( "Hello, ", user);
      }
};

EOSIO_DISPATCH( hello, (hi))

上例中hello是我们的类名,需要继承eos为我们提供的基类contract,[[eosio::action]]是一个特殊用法,定义一个action必须在函数声明前加上此标记。hi这个函数就是一个 action,本例实现的就是一个打招呼的action,根据输入的不同用户进行打招呼。

EOSIO_DISPATCH( hello, (hi)) 是生成action的关键,EOSIO_DISPATCH是eos提供的宏,hello显然就是类名,(hi)就是要生成的action,如果多个action,采用相同格式在后面添加。

2.2 hello合约的部署和调用

eosio-cpp -o hello.wasm hello.cpp --abigen
编译hello合约
cleos create account eosio hello YOUR_PUBLIC_KEY -p eosio@active
cleos set contract hello ./hello -p hello@active
部署hello合约
//先创建一个普通账户bob
cleos create account eosio bob YOUR_PUBLIC_KEY -p eosio@active
//bob调用hello合约的hi动作
cleos push action hello hi '["bob"]' -p bob@active

调用hello合约

  到这一步,一个简单的hello智能合约就部署并调用完成了,快来试试吧。下次将为大家分享关于EOS开发实战的内容,敬请关注。


上一篇下一篇

猜你喜欢

热点阅读