智能合约 EOS nodejs 与链上合约交互事例

Surou · 2018年12月04日 · 158 次阅读

链上部署合约部分代码

Table
struct [[eosio::table("users"), eosio::contract("some.game")]] user{
        capi_name account_name;
        uint64_t qualifications;
        auto primary_key() const { return account_name; }
    };
Action
ACTION addqualify(capi_name account);
void some_contract::addqualify(capi_name account){
    require_auth( _self.value );
    user_tables user_table(_self, _self.value);
    auto itr = user_table.find(account);
    eosio_assert(itr != user_table.end(), "account not find" );
    user_table.modify( itr, _self, [&]( auto& u ) {
        u.qualifications += 1;
    });
}

NodeJs 代码部分

EosService.js

const Eos = require('eosjs');
const config = require('../config/EosNetwork');

class EosService {
  constructor() {
    this.eosApi = Eos({
      httpEndpoint: `${config.network.protocol}://${config.network.host}${config.network.port ? ':' : ''}${config.network.port}`,
      chainId: config.network.chainId,
      keyProvider: config.self.privateKey,
      fetchConfiguration: {
        timeout: config.network.timeout,
      },
    });
    this.authorization = [`${config.contract.account}@active`];
    this.transactionOptions = { authorization: this.authorization };
    this.contractResult = null;
  }

  async init() {
    try {
      this.contractResult = await this.eosApi.contract(config.contract.code);
    } catch (e) {
      console.log(e); // TODO throw
    }
  }

  api() {
    return this.eosApi;
  }

  async pushAction(action, params) {
    if (this.contractResult === null) {
      await this.init();
    }
    try {
      this.contractResult[action](params, this.transactionOptions);
    } catch (e) {
      console.log(e); // TODO throw
    }
  }
}

module.exports = EosService;

chain.js

const EosService = require('../services/EosService');

class Chain {
  constructor() {
    this.eosService = new EosService();
  }

  async addQualify(account) {
    await this.eosService.pushAction('addqualify', account);
  }
}

module.exports = Chain;

game.js

const Chain = require('./chain');
const chain = new Chain();
....
await chain.addQualify(item.challenger); //此时,链上users 对应账户的qualifications将会+1
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册