[Ethereum] How to create an array of unique addresses

contract-designcontract-developmentsolidity

I have a contract that contains a simple mapping; let's say mapping(address => uint256) balances;

I want to be able to somehow get all the participants of this smart contract. The simplest way seems to have an additional dynamic array of addresses and iterate over them. But searching for an address on each token transfer or payable function call looks overcomplicated.

Is there a way to have something like a set() in Python, i.e. an array of unique addresses?

Best Answer

There's no native set in solidity but you can work something simpler with an array and a mapping.

It is very simple, but have the disadvantage it is append only set, you cannot easily delete an element from it.

contract SimpleSet {
    // Mapping from address to position in the array
    // 0 means the address is not in the array
    mapping (address => uint) index;

    // Array with address 
    address[] store;

    function SimpleSet() public {
        // We will use position 0 to flag invalid address
        store.push(0x0);
    }

    function addToArray(address who) public {
        if (!inArray(who)) {
            // Append
            index[who] = store.length;
            store.push(who);
        }
    }

    function inArray(address who) public view returns (bool) {
        // address 0x0 is not valid if pos is 0 is not in the array
        if (who != 0x0 && index[who] > 0) {
            return true;
        }
        return false;
    }

    function getPosition(uint pos) public view returns (address) {
        // Position 0 is not valid
        require(pos > 0); 
        return store[pos];
    }
}
Related Topic