简体   繁体   中英

MyContract.methods.addData doesn't work from nodejs web3

I am connecting to my Solidity contract through nodejs and web3 . 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:

bytes32[20] bytesArray;

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

The call from my nodejs file:

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 .

I tested this contact with Remix and it works fine, values are added and I'm able to see them. But I need to do this from nodejs and so far it's not working.

Using call in the code below is incorrect.

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. Any change to state needs to use send : https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-send

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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