2

Whenever I try to access a mapping in truffle console, I get this error.

mapping(uint256 => uint256[]) public myMapping;

I try:

myContract.deployed().then(function(instance) { return instance.myMapping.call(0) });

Why does the mapping expect two arguments, and what should the second argument be? I just want the value keyed at 0.

1
  • It looks like you're mapping uint256 to an array of uint256, so it probably expects an index for the array. Maybe get rid of those brackets in the mapping definition? Or just use an array uint256[]? Apr 30, 2018 at 3:43

1 Answer 1

5

Because you declared a public mapping, Solidity creates a getter. It looks something like this:

function myMapping(uint256 _index, uint256 _arrayIndex) 
    external
    view
    returns (uint256) 
{
    return myMapping[_index][_arrayIndex];
}

You mapping maps uint256's to uint256[] arrays. As Solidity's standard getter does not return arrays, you will have to specify which element in the array you want to the getter.

To get the first element of the first array in the mapping, use

myContract.deployed().then(function(instance) { 
    return instance.myMapping.call(0,0) 
});

If you want you smart contract to retrieve the array in full, try this function:

function myFullMapping(uint256 _index) 
    external
    view
    returns (uint256[]) 
{
    return myMapping[_index];
}

In JavaScript, you can use this code to get the first array in the mapping:

myContract.deployed().then(function(instance) { 
    return instance.myFullMapping.call(0) 
});
1
  • Any way to get the whole array from console? May 1, 2018 at 23:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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