Is it possible to allocate storage for a state variable in Solidity? I have the following smart contract
contract Demo {
uint256 sharedCounter;
function countUp() external {
sharedCounter = sharedCounter+1;
}
}
The contract has a shared variable, which all contract users can set/increase. The problem is, that the first user to call countUp
will use a lot more gas than the following users, because he initially sets the sharedCounter
variable to a non-zero value. According to the Ethereum yellow paper, the first user to call countUp
will have to pay 20.000 gas to set the variable, the following users only 5.000 as they only update it.
I want countUp
to be fair and to cost the same for every user. The first idea would be to set sharedCounter = 1
in the constructor. This way the initial 20.000 gas is paid in the constructor. The problem is that this way the counter would be wrong.
Another idea is to set sharedCounter = 0
, but this also won't help because the value is still zero and the first user still has to pay more.
Is there a possibility to allocate storage for sharedCounter
in the constructor without setting the value? I was thinking of something like this (although I know this is not working)
constructor() {
sharedCounter = new uint256;
}