简体   繁体   English

MyContract.methods.addData在Node.js Web3中不起作用

[英]MyContract.methods.addData doesn't work from nodejs web3

I am connecting to my Solidity contract through nodejs and web3 . 我连接到我的Solidity ,通过合同nodejsweb3 I am able to read information, but when trying to add an element to an array it is not added. 我能够读取信息,但是在尝试将元素添加到数组时不会添加。

This is my code. 这是我的代码。

The solidity method: solidity法:

bytes32[20] bytesArray;

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

The call from my nodejs file: 来自我的nodejs文件的调用:

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

Add a value: 添加一个值:

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

Then to get the value: 然后获取值:

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

The array comes back but all its values are still empty, 0x0000000000000000000000000000000000000000000000000000000000000000 . 数组返回,但其所有值仍为空0x0000000000000000000000000000000000000000000000000000000000000000

I tested this contact with Remix and it works fine, values are added and I'm able to see them. 我使用Remix测试了这种联系方式,效果很好,可以添加值,并且可以看到它们。 But I need to do this from nodejs and so far it's not working. 但是我需要从nodejs进行此nodejs ,到目前为止它仍然无法正常工作。

Using call in the code below is incorrect. 在下面的代码中使用call是不正确的。

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

This is a common mistake. 这是一个常见的错误。 call is used to run functions on a local VM and is not broadcast out to the blockchain for mining. call用于在本地VM上运行功能,并且不会广播到区块链进行挖掘。 Any change to state needs to use send : https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-send 状态的任何更改都需要使用sendhttps : //web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-send

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM