code-423n4 / 2022-04-pooltogether-findings

0 stars 0 forks source link

Gas Optimizations #11

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Gas1:

No need to use safemath library for solidity 0.8.4+ as the compiler itself now checks for overflow/underflow, hence results in lot of gas savings

Gas2:

prefer != instead of > for unsigned integer, saves gas https://github.com/pooltogether/aave-v3-yield-source/blob/e63d1b0e396a5bce89f093630c282ca1c6627e44/contracts/AaveV3YieldSource.sol#L179 https://github.com/pooltogether/aave-v3-yield-source/blob/e63d1b0e396a5bce89f093630c282ca1c6627e44/contracts/AaveV3YieldSource.sol#L233

Gas3:

uint256 should be preferred, not against readability of code https://github.com/pooltogether/aave-v3-yield-source/blob/e63d1b0e396a5bce89f093630c282ca1c6627e44/contracts/AaveV3YieldSource.sol#L145 https://github.com/pooltogether/aave-v3-yield-source/blob/e63d1b0e396a5bce89f093630c282ca1c6627e44/contracts/AaveV3YieldSource.sol#L136

Gas4:

no need to increase or decrease allowance if it's approved for max limit,results in lot of gas savings Similar optimizations are used in ERC20 tokens like WETH, The Wrapped Ether (WETH) ERC-20 contract does not update the allowance if it is the max uint.

https://github.com/pooltogether/aave-v3-yield-source/blob/e63d1b0e396a5bce89f093630c282ca1c6627e44/contracts/AaveV3YieldSource.sol#L296 https://github.com/pooltogether/aave-v3-yield-source/blob/e63d1b0e396a5bce89f093630c282ca1c6627e44/contracts/AaveV3YieldSource.sol#L315

PierrickGT commented 2 years ago

Gas1: PR: https://github.com/pooltogether/aave-v3-yield-source/pull/5

Gas2: We would only save 3 in gas for each function call, which is not worth the loss in legibility of our code.

Gas3: The Aave supply function accept a uint16 for the referral code so we need to store it in a uint16: https://docs.aave.com/developers/core-contracts/pool#supply Decimals are stored in a uint8 in the OpenZeppelin contract, so if we want to overwrite the default value, we need to store it in a uint8: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/14ca3aeb798d9b9be31df86ae7ef8b8f760caa4c/contracts/token/ERC20/ERC20.sol#L87

Gas4: Not really a gas optimization. We can check the allowance off-chain before calling these functions, so we can avoid spending ETH for a transaction.