My question is related to finding keys mapped to valid values in a given range (n_start, n_end) at runtime using minimum gas, if possible.
mapping(uint => myStruct) clusterContract;
uint
contains the block number on the blockchain. So this may be in between 0 and 1,000,000 and keep increases. Based on client's behaviour new mapping will be generated but there may be some empty spots, for example exiting mappings
as follows:
clusterContract[0] = structA;
clusterContract[1001] = structB;
clusterContract[1002] = structC;
clusterContract[1003] = structD;
clusterContract[1100] = structE;
clusterContract[2000] = structF;
clusterContract[7999] = structG;
clusterContract[8001] = structH;
Following answer says that:
Unfortunately not. A mapping just matches a key to a value. It doesn't have a list of either per se.
At this point, for example: I just want to reach structs that pointed from valid keys in between 1000 and 8000, which should be 1001(structB), 1002(structC), 1002(structD), 2000(structF) and 7999(structG).
In order to do that only solution I have come up with is to iterate through all elements from 1000 to 8000 and check that each block number valid key or not and if it is valid do the operation I want to:
for(int i=1000; i++; i<8000) {
if( clusterContract[i] ) //check whether key exists. I could not figure out how to check key exists or not.
clusterContract[i].StructX.val = 64; //or do something else.
}
[Q] As you can see, I need to iterate through 7000 values to check if their keys are valid or not. Is this a suggested solution, where gas usage might be inefficient since I need to do 7000 if then
or more if the range increases? Any recommended solution would be very appreciated. Please note that Binary Search Tree might be a good solution but again larger the tree, there would be inefficient gas for adding new nodes or searching within the tree.
=> Or if I remove the key validity check (whether key i
exists or not), when this code piece is converted into lowest level code piece (Ethereum Virtual Machine code) by Solidity, would nonexisting keys be ignored automatically, since they don't exist? Hence only valid keys will be considered and it won't iterate through 7000 items.
for(int i=1000; i++; i<8000)
clusterContract[i].StructX.val = 64; //only existing keys are updated.
Thank you for your valuable time and help. I am sorry if there is grammar mistakes, I did my best to explain this problem with some examples.