Reading mapping and array storage variables

capnnemocapnnemo Member Posts: 10
edited November 2015 in web3-js
Hello,

I am trying to display some storage variables from a contract in a web front end using web3.

struct Foo {
uint bar;
uint buzz;
}

mapping(address => Foo) public _aMapping;
However, when I try the following JS to read _aMapping..

var result = myContractInstance._aMapping.call(
{from: web3.eth.defaultAccount, value: 0, gas: 2000000},
function(err, result){
console.log(result);
}
);
..I get this message:

Error: new BigNumber() not a number: [object Object]

When I modify the above to get the value for a specific key..

var result = myContractInstance._aMapping.call(
'0x66e5667e9ff37b7f5e29afc57fc9b645a66e9fd4',
{from: web3.eth.defaultAccount, value: 0, gas: 2000000},
function(err, result){
console.log(result);
}
..I see some cryptic output:

Array [ Object, Object ]

Maintaining a separate address array of known keys and accessing that did not help either.

Could someone please tell me if they know a way to read a mapping containing addresses and structs from web3?

Thanks.

Comments

  • capnnemocapnnemo Member Posts: 10
    Thanks for the clarification. However, I am still getting funny return values as I described above. As an additional example, when I expect an address, I only get "0x". Is it possible web3 does not correctly deserialize non-primitive types?
  • capnnemocapnnemo Member Posts: 10
    I came back to this issue today and thought I'd post an update. As tjade273 mentioned above, constant functions don't need a call() invocation.

    This is how a public array (_addresses) can be read:

    var result = contract._addresses(i);

    To read the entire array, one has to iterate over all valid indices:
    for(i=0;; i++) {
         var result = contract._addresses(i);
         if(result=="0x") break;
         console.log(result);
    }
    To read mapping values, one must always provide a valid key:

    var deets = contract._authorized(result);

    Let's say the above returns a two-tuple corresponding to a struct. The return values can be read using something like:
    console.log(deets[0].c[0]);
    console.log(deets[1].c[0]);
    In general, the inputs and outputs of these accessors functions can be checked in the ABI (duh).
Sign In or Register to comment.