1
pragma solidity 0.4.24;


contract ArraysExample {
   uint[] numbers;

   function addUser() public returns (uint[]) {
      numbers.push(random());
      return numbers;
   }

   function random() private view returns (uint8) {
      return uint8(uint256(keccak256(block.timestamp, block.difficulty))%251);
   }
}

When I call the following contracts method

const Web3 = require("web3");
const web3 = new Web3();
web3.setProvider(new 
web3.providers.HttpProvider("http://localhost:7545"));

const fs = require("fs");
const abi = JSON.parse(fs.readFileSync("abi.json", "utf8")).abi;
const contractAddress = "0x1fba6995e24ffa28bd0d14acd16e6f4cdac8df68";

const contractInstance = new web3.eth.Contract(abi, contractAddress);

contractInstance.methods
.addUser() 
.call()
.then(numbers => console.log(numbers));

I get this response when I execute the following code instead of ['142', '215', '8' ... ]: enter image description here

1

The contract works.

Here it is Remix, returning an array with multiple items, as expected.

enter image description here

Your testing methodology is flawed. Specifically, you're using the .call() method which is a read-only invocation, like a dry run. It can't update the state. This is why the array isn't growing.

Have a look over here for a more complete explainer: https://blog.b9lab.com/calls-vs-transactions-in-ethereum-smart-contracts-62d6b17d0bc2

| improve this answer | |
  • 1
    Thank you Rob, that worked for me. I needed to add an event to my contract and emit it. web3.eth.getAccounts().then(accounts => { contractInstance.methods .addUser() .send({ from: accounts[0] }) .then(txReceipt => { console.log(txReceipt.events.newNumberPushed); }); }); it's how my code looks like now. – Marcello Bardus Nov 19 '18 at 20:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.