code-423n4 / 2021-12-vader-findings

0 stars 0 forks source link

`uint a = b++;` is a confusing syntax and can be gas-optimized #157

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Handle

Dravee

Vulnerability details

Impact

uint a = b++; is an error-prone syntax that is often misunderstood by developers. 5 gas can be saved with a pre-increment after the assignment.

Proof of Concept

The uint256 id = positionId++; code is here https://github.com/code-423n4/2021-12-vader/blob/main/contracts/dex-v2/pool/BasePoolV2.sol#L510:

It's an often misunderstood syntax as after this line, id == positionId - 1 (or id + 1 == positionId) is the true statement.

In short, the value of positionId is first stored in uint256 id, and then the variable positionId is incremented by 1.

Tools Used

Manual Review

Recommended Mitigation Steps

The existing short-syntax is not worth the cost on code clarity (more so than the 5 gas saved). I'd advise you divide the statement over 2 lines:

// Before 
uint256 id = positionId++;

// After
uint256 id = positionId;
++positionId; // pre-increment costs 5 gas less than post-increment