solidity – Error: Invalid Number of Arguments to Solidity Function (Mapping)

soliditytruffleweb3js

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.

Best Answer

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) 
});