Consider the following contract that illustrates the problem. Here we have a dynamic array of mappings, add()
is meant to add a fresh new mapping to the end of the array, return the value for mapping key 0
and change that value to true
. remove()
in turn is meant to remove the last mapping from an array.
contract ClearMapping {
mapping(uint => bool)[] state;
// 1. add -> false
// 2. remove
// 3. add -> true
function add() returns (bool) {
uint pos = state.length++;
bool curr = state[pos][0];
state[pos][0] = true;
return curr;
}
function remove() {
state.length--;
}
}
One can think that removing a mapping element from an array effectively clears that mapping, and that adding a new mapping in place of the old one will have a fresh, all key* -> false
, element. It turns out that it is not true.
Same thing happens if you try to swap elements that have mappings inside, everything will be swapped except of mappings.
The only solution I see to deal with this, is by manually delete/reassign every used mapping key, but it becomes costly in terms of gas usage very fast.
The questions I'm looking to answer is:
- Is this a bug in EVM/Solidity?
- Is there a convenient/effective way to clear/swap mappings?
- Should I not use mappings as temporary KeyValue instances?
Thanks for the attention!