here is my code
I defined a struct in library to record mapping so that i can iterate the mapping inside Map in my contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
library IterableLibrary {
struct Map {
address[] keys;
mapping (address => uint256) value; // record mapping
mapping (address => uint256) indexOf; // record mapping's index
mapping (address => bool) inserted; // record key is inserted or not
}
function getValue(Map storage map, address _key) public view returns (uint256) {
return map.value[_key];
}
function getKeyAtIndex(Map storage map, uint256 _index) public view returns (address) {
return map.keys[_index];
}
function set(Map storage map, address _key, uint256 _val) public {
if (map.inserted[_key]) {
map.value[_key] = _val;
} else {
map.keys.push(_key);
map.value[_key] = _val;
map.indexOf[_key] = map.keys.length;
map.inserted[_key] = true;
}
}
function size(Map storage map) public view returns (uint256) {
return map.keys.length;
}
}
contract IterableMapping {
using IterableLibrary for IterableLibrary.Map;
IterableLibrary.Map private map;
uint256[] public valueList;
function iterableTest() public {
map.set(address(0), 0);
map.set(address(1), 100);
map.set(address(2), 200);
map.set(address(3), 300);
map.set(address(4), 400);
for (uint256 i = 0; i < map.size(); i++) {
// get key according to index
address key = map.getKeyAtIndex(i);
// add 1 to value
uint256 val = map.getValue(key);
val += 1;
map.set(key, val);
valueList[i] = val;
}
}
}
iterable map,get the mapping’s key and value,then add 1 to value.But got faild message
Note: The called function should be payable if you send value and the value you send should be less than your current balance. You may want to cautiously increase the gas limit if the transaction went out of gas.
If i want realize that operation,how can i fix my code?
I tried to delete the add operation then transaction success.Then i tried set a high gas limit but also failed.It’s really got error because gas limit?And is there has some better way to iterate a mapping?
Bring forth my sincerest appreciate to anyone if you could help me.