17
pragma solidity ^0.4.24;

contract User {
    mapping(uint=>address) addresses;
    uint addressRegistryCount;   

    function set(address userAddress) public {
        addresses[addressRegistryCount] = userAddress;
        addressRegistryCount++;
    }

    function get(address userAddress) public view returns (uint) {
        for (uint i = 0; i <= addressRegistryCount; i++) {
            if(addresses[i] == userAddress)
                return i;
        }
    }

    /*function getAll() {

    }*/
}

In this contract I have a function called getAll. Inside that function I´m trying to return the full mapping of users. How can I make that?

Rosco Kalis
  • 2,137
  • 2
  • 14
  • 26
UnexpectedCharacter
  • 852
  • 1
  • 11
  • 30
  • If you want to fetch it from the off-chain, then just add public before addresses, and you've got yourself a "getAll" function (which you can invoke from the off-chain via addresses()). – goodvibration Jan 15 '19 at 09:20
  • 4
    @goodvibration Adding the public identifier doesn't result in a getAll function. It gives you a public function which takes index as input and returns only one element of mapping. – saman.shahmohamadi Jan 15 '19 at 09:36
  • Sample: https://gist.github.com/samanshahmohamadi/d0d43034e45ccadfd48ce97ed0bd1aba – saman.shahmohamadi Jan 15 '19 at 09:43

2 Answers2

27

You can't return a mapping directly. What you can do is to make an array and add all address values that is stored in the addresses mapping to it. Then return that array.

function getAll() public view returns (address[] memory){
    address[] memory ret = new address[](addressRegistryCount);
    for (uint i = 0; i < addressRegistryCount; i++) {
        ret[i] = addresses[i];
    }
    return ret;
}
1

Instead of a mapping, you can return 2 arrays. Take a look at this working example...

function getAvailableMintsForUser(WhitelistStorage storage self) public view returns (uint256[] memory, uint8[] memory) {
    uint256 balance = self.contract.balanceOf(msg.sender);
    uint256[] memory tokenIds = new uint256[](balance);
    uint8[] memory available = new uint8[](balance);
    for(uint256 i = 0 ; i < balance ; i++) {
        tokenIds[i] = self.chroma.tokenOfOwnerByIndex(msg.sender, i);
        available[i] = calcAvailableMintsPerTokenId(self, tokenIds[i]);
    }
    return (tokenIds, available);
}
rogers
  • 121
  • 2