首页 > 解决方案 > MyContract.methods.addData 不适用于 nodejs web3

问题描述

我通过和连接到我的Solidity合同。我能够读取信息,但是当尝试将元素添加到数组时,它不会被添加。nodejsweb3

这是我的代码。

solidity方法:

bytes32[20] bytesArray;

function add(uint8 id, bytes32 s) public {
  bytesArray[id] = s;
} 

我的nodejs文件中的调用:

var myContractABI = <the_abi>;
var contractAddress = '0x...';
var myContract = new web3.eth.Contract(myContractABI, contractAddress);
myContract.setProvider(web3.currentProvider);

添加一个值:

myContract.methods.add(0, web3.utils.asciiToHex("some string")).call()
  .then(receipt => {
      console.log(" added? " + receipt); // returns [object Object]
});

然后获取值:

myContract.methods.getArray().call()
  .then(receipt => {
      console.log("full array " + receipt);
});

数组回来了,但它的所有值仍然是空的,0x0000000000000000000000000000000000000000000000000000000000000000

我测试了这个联系人,Remix它工作正常,添加了值,我可以看到它们。但我需要这样做nodejs,到目前为止它不起作用。

标签: node.jsethereumsolidityweb3web3js

解决方案


call在下面的代码中使用是不正确的。

myContract.methods.add(0, web3.utils.asciiToHex("some string")).call()
  .then(receipt => {
      console.log(" added? " + receipt); // returns [object Object]
});

这是一个常见的错误。call用于在本地 VM 上运行功能,不会广播到区块链进行挖掘。对状态的任何更改都需要使用sendhttps ://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-send


推荐阅读