code-423n4 / 2021-11-streaming-findings

0 stars 0 forks source link

Gas Optimization On The 2^256-1 #255

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Handle

defsec

Vulnerability details

Impact

Various projects (e.g. Uniswap - https://github.com/Uniswap/interface/blob/main/src/hooks/useApproveCallback.ts#L88 , see here 1 using the constant MaxUint256 from ethers.js) set the default value of the user's allowance to 2^256 - 1. Now the value 2^256 - 1 can also be represented in hex as 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff. From Ethereum's yellow paper we know that zeros are cheaper than non-zero values in the hex representation. Considering this fact, an alternative choice could be now 0x8000000000000000000000000000000000000000000000000000000000000000 or 2^255 to represent "infinity". If you do the calculations with Remix, you will see that the former costs 47'872 gas, while the latter costs 45'888 gas. If you accept that infinity can also be represented via 2^255 (instead of 2^256-1) - and I think most projects can live with that - you can already save 1'984 gas (or 4.1%) leveraging this optimisation trick.

Proof of Concept

  1. Navigate to the following contract.

"https://github.com/code-423n4/2021-11-streaming/blob/main/Streaming/src/LockeERC20.sol#L113"

Tools Used

Code Review

Recommended Mitigation Steps

Change 2^256-1 With 2^255.

Reference

https://ethereum.github.io/yellowpaper/paper.pdf

https://forum.openzeppelin.com/t/a-collection-of-gas-optimisation-tricks/19966