code-423n4 / 2022-01-xdefi-findings

0 stars 0 forks source link

"constants" expressions are expressions, not constants. Use "immutable" instead. #26

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Handle

Dravee

Vulnerability details

Impact

Due to how constant variables are implemented, an expression assigned to a constant variable is recomputed each time that the variable is used, which wastes some gas.

If the variable was immutable instead: the calculation would only be done once at deploy time (in the constructor), and then the result would be saved and read directly at runtime rather than being recalculated.

See: ethereum/solidity#9232

Proof of Concept

Here, the exponentiation operation is computed everytime the _pointsMultiplier variable is used:

XDEFIDistribution.sol:17:    uint256 internal constant _pointsMultiplier = uint256(2**128);

Tools Used

VS Code

Recommended Mitigation Steps

Change expressions that are constant to immutable and implement the calculation in the constructor

deluca-mike commented 2 years ago

I have tested this (and you can do by changing it and rerunning the hardhat tests and comparing the gas reports) and this seems to be fixed in solidity now, so it is not valid in this specific case. At least is not in 0.8.10. Thankfully, because uint256(2**128) is more readable.