以太坊 Truffle 合约交互

之前的文章以太坊 Truffle 合约创建 编译 迁移介绍了 Truffle 创建部署合约,下面还在之前的环境下实践合约的交互。

交互分为:

  1. 写,叫做 “交易 transaction
  2. 读,叫做 “调用 call

在之前的示例项目 myproject 中写调用和交易的代码进行实践。

1. 环境准备

cd myproject
npm init -y
npm install --save [email protected]
npm install --save [email protected]

2. 调用

call.js

var Web3 = require("web3");

var contract = require("truffle-contract");
var data = require("./build/contracts/Storage.json");

var Storage = contract(data);

var provider = new Web3.providers.HttpProvider("http://localhost:8545");
Storage.setProvider(provider);

Storage.deployed().then(function (instance){
  return instance.get.call();
}).then(result => {
  console.info(result.toString());
}).catch(err => {
  console.info(err);
});

运行:

node call.js

输出:

0

3. 交易

transaction.js

var Web3 = require("web3");

var contract = require("truffle-contract");
var data = require("./build/contracts/Storage.json");

var Storage = contract(data);

var provider = new Web3.providers.HttpProvider("http://localhost:8545");

Storage.setProvider(provider);

var storageInstance;

Storage.deployed().then(function (instance){
  storageInstance = instance;

  return storageInstance.set(42, {from:Storage.web3.eth.accounts[0]}).then(result => {
    console.info(result.tx);
  }).then(()=>{
    return storageInstance.get.call();
  }).then(result => {
    console.info(result.toString());
  }).catch(err => {
    console.info(err);
  });
});

运行:

node transaction.js

输出:

0x370a860e48a548127098957c58c6d008250653b8ec54154d3c130d48f4657f1d
42

你可能感兴趣的:(以太坊 Truffle 合约交互)