0

If I have a variable declaration such as follows:

mapping(address => uint) public totalETHSpent;

Is there any way for me to return the entire mapping object as-is via a get(). I see that in the docs, it mentions that this is not possible: https://docs.soliditylang.org/en/v0.8.11/types.html?highlight=mapping#data-location

What other GAS FRIENDLY options do we have if I need to return a mapping of 10,000 entries?

2 Answers 2

0

You can do this by using a loop function(ex.foor,while)

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract Test2 {
    mapping(address => uint) public totalETHSpent;

    function getEThSpentByAddress(address[] calldata users) public view returns(uint256[] memory) {
      uint _length = users.length;
      uint[] memory results = new uint[](_length);

      for(uint i = 0; i < _length; i++) {
          results[i] = totalETHSpent[users[i]];
      }

      return results;
  }
}

You can modify the code to make the gas bill more effective.

But it looks like you really need a loop.

0

You cannot, in general, get all the data out of a mapping. Let alone in a gas efficient way.

You will need to explain your use case and make some compromises.

Some options are:

  • Track the information off-chain, send it on-chain and then confirm it on-chain.
  • Double-account the information on-chain, once as a mapping and second for enumeration.

You can also study implementations of ERC721Enumerable, this is the first standardized approach to this problem. And I think Su Squares is the first project to actually implement this double accounting.

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.