包含数据到合同函数的事务

时间:2018-03-07 13:41:27

标签: solidity web3js

我在本地测试RPC上部署了以下合同

pragma solidity ^0.4.20;

contract cntrct {
  uint public aaa; 

  function run() payable public
  {
    aaa += msg.value;
  }

  function reader() public returns(uint)
  {
    return aaa;
  }
}

我知道这并没有多大意义,但它是出于测试目的。所以首先我需要生成交易数据,所以我使用:

var run = web3.utils.sha3("run()").substring(0, 10);
//Output: 0xc0406226

现在我将事务中的数据发送到合同,该合同应触发run函数。

web3.eth.sendTransaction({
    to:toAddr, 
    gasPrice: '30000000000', 
    from:fromAddr, 
    data: run, // = 0xc0406226
    value: "1000000000000000000"});

但我的aaa变量保持0,这意味着run()函数从未运行过。我使用aaa函数检查reader()变量:

contract.methods.reader().call().then(console.log)

编辑:这是我在节点中运行的完整代码:

const fromAddr = '0x...';
const toAddr = '0x...';
const contractName = ':cntrct';
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
const solc = require('solc');
const input = fs.readFileSync('Token.sol');
const output = solc.compile(input.toString(), 1);
const bytecode = output.contracts[contractName].bytecode;
const abi = JSON.parse(output.contracts[contractName].interface); 
const contract = new web3.eth.Contract(abi, toAddr); //const?
contract.options.address = toAddr;

//Deploy contract
var deployed = contract.deploy({
    data: bytecode, 
    arguments: [[]]})
  .send({
    from: toAddr, 
    gas: 4700000, 
    gasPrice: '30000000000'}, 
    function(error) {console.log(error)});

//Make a test transaction
var run = web3.utils.sha3("run()").substring(0, 10);
web3.eth.sendTransaction({
    to:toAddr, 
    gasPrice: '30000000000', 
    from:fromAddr, 
    data: run, 
    value: "1000000000000000000"});

//call reader function
contract.methods.reader().call().then(console.log);
//This returns Promise{...} 0

0 个答案:

没有答案