Solidity Mapping – How to Check if List Contains a Value

mappingsolidity

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?

Best Answer

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).

Related Topic