Search code examples
blockchainethereumsoliditysmartcontracts

Get Keys of Solidity mapping


I was trying to get keys of a mapping to star name and address of particular contract (not exactly) in solidity contract

mapping(string=>address) nameOfAccounts;

What i am expecting is a method like the Object.keys(nameOfAccounts) in Javascript. Is there any similar method ?. or should i use an additional array. The additional Array may cause extra gas cost(This is not an option that i prefer). Please share some insights

I wanted to know if there is another method that i can do if getting keys is not an option?


Solution

  • The best way to iterate over the keys is that when a key is added you also emit a Solidity event.

    You get keys from the event logs. This can be done client-side (JavaScript, Python) but not within Solidity itself, as EVM does not have access to event data.

    Solidity/EVM does not store iterable keys due to efficiency reasons in execution constrained environment.

    More information here.