Why setting array.length to 0 triggers an error ?
I have a function that deletes an element from a dynamic array of structs within a mapping as follows:
mapping(address => MyStruct[]) public structs;
My problem is that if I try to set the length to 0 it triggers this error: VM Exception while processing transaction: invalid opcode
structs[_user].length = 0; // will trigger an error !
But:
structs[_user].length = 1;
will work fine.
It is inside a function like this one:
function _burn(uint index) internal {
require(index < array.length);
array[index] = array[array.length-1];
delete array[array.length-1];
// when array.length is set to 0 it doesn't work:
array.length = array.length - 1; // doesn't work if array.length = 1
array.length = 0; // doesn't work
// when array.length is set to a value > 0 it works:
array.length = 1; // works
array.length = 2; // works
}
I tried at least for 45 hours without findnig any idea why it happens! If you have encontered this issue or know how to handle it, help would be really appreciated.
P.S: I am using solidity 0.5.2
Here is the whole code:
// ---- Redeem a Stake ------ //
function stakeclmidx (uint _stakeidx) public {
require(_stakeidx >= 0);
Stake storage _stake = stakes[msg.sender][_stakeidx];
// See if the stake is over
require(block.number > _stake.endBlock);
require(_stake.amount > 0);
// transfer back token from contract to staker:
balances[address(this)] = balances[address(this)].sub(_stake.amount);
balances[msg.sender] = balances[msg.sender].add(_stake.amount);
emit Transfer(address(this), msg.sender, _stake.amount);
emit StakeClaimed(_stakeidx);
// deletes the stake
_deletestake(msg.sender, _stakeidx);
}
function _deletestake(address _staker,uint _index) internal {
require(_index < stakes[_staker].length);
stakes[_staker][_index] = stakes[_staker][stakes[_staker].length-1];
delete stakes[_staker][stakes[_staker].length-1];
stakes[_staker].length = stakes[_staker].length - 1;
// this last line is the one triggering the error
// it seems it triggers the error only when length value is set to 0
// stakes[_staker].length = 1; works !
// stakes[_staker].length = 2; works !
// stakes[_staker].length = 0; doesn't work !
}
// ---- Redeem a Stake ------ //
Best Regards
delete array[array.length-1]
, it's redundant here.require
statement at the beginning of the function?