0

I have a simple contract that takes integer inputs from different clients and eventually calls a function to calculate average. When I run the contract in Remix debugger, I can see the function go through correctly. But, I can't seem to get the same from web3.js. Can you please suggest what am I missing?

The Solidity documentation on storage is so poorly worded that, I can't follow it at all!

The types where the so-called storage location is important are structs and arrays. If you e.g. pass such variables in function calls, their data is not copied if it can stay in memory or stay in storage. This means that you can modify their content in the called function and these modifications will still be visible in the caller.

This is with Ethereum Testrpc.

Contract

Setting runningNumber and members[] is not shown here.

contract Lister {
    struct ListMembers {
        bytes32[] members;
        uint256 averageNumber; 
        uint256 runningNumber;  
    }

    // Instance of the ListMemebers struct
    ListMembers public lm;

   function calculateAverageNumber() {        
        uint256 numMembers = uint256(lm.members.length);
        uint256 sampleSum = lm.runningNumber - lm.randomNumber;
        uint256 avgSum = sampleSum / numMembers;
        lm.averageNumber = avgSum;
    }

     function getAverageNumber() returns (uint256) {
        return lm.averageNumber;
    }

web3.js

var Web3 = require('web3');
var fs = require('fs');
//
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
var abiFile = fs.readFileSync('Lister.abi').toString();
var abiDef = JSON.parse(abiFile);
var ListingContract = web3.eth.contract(abiDef);
var contractInstance = ListingContract.at('0xdc80....3aff');
//
contractInstance.getAverageNumber.call(
    (err, res) => {
        if (err) {
            console.log(err)
        } else {
            console.log(res)
        }
    }
)
  • can you add the code for the initial setting? – Dean Eigenmann Sep 26 '17 at 21:40
0

You need to mark getAverageNumber() constant. Otherwise you won't be able to read it from web3.js. See this answer for more about what this means: https://stackoverflow.com/questions/45867572/solidity-return-function-why-the-constant

  • That didn't work. I have another function getRunningNumber that returns lm.runningNumber correctly without the constant modifier. How can I confirm that lm.averageNumber is actually getting updated? – cogitoergosum Aug 27 '17 at 23:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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