4

given address[] wallets. What is the correct method to check that the list contains a given address?

Does solidity provide any native list contains function?

If not, is the only way to do a full iteration of the array and check each element?

Are there more memory efficient ways of doing this, maybe a mapping?

9

Solidity doesn't provide a contains method, you'd have to manually iterate and check.

Using an array for what you're trying to achieve would be a highly inefficient pattern. The best and most cost efficient method is use a mapping data structure. Set the key to be the address and the value to be a boolean. Lists that are too long have the possibility of running out of gas when you're trying to iterate over them.

If you need to iterate through all the keys in the mapping, then you'd need to have an external database to get all the keys. The database can be populated and updated based on events from the smart contract (i.e. an event when the address is added or removed).

4

If I were you, I would use a pattern like this:

contract myWallets
{
    mapping (address => bool) public Wallets;

    function setWallet(address _wallet) public{
        Wallets[_wallet]=true;
    }

    function contains(address _wallet) returns (bool){
        return Wallets[_wallet];
    }
}
0

If you're starting with an unsorted array and you don't know the index where the data lives then all you can do is loop through it. The gas required to do this grows as the list does, and may become so big that the contract becomes unusable.

The obvious solution is to keep the data in a mapping by address => bool. This gives you a constant lookup cost regardless of the number of items stored.

If the data is sorted then you have a few other options including a binary search, but it's not as clean or simple as a mapping.

One final possibility if you really need to keep the data in an unsorted array is to get the user's software to iterate the array on the client side to find the index of their address, then supply it to the contract as a parameter. Then you just have to check if the data is really at that index. However this gets fiddly if the index changes, because by the time the user's transaction gets to the contract, the data may no longer be where they found it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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