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

0 stars 0 forks source link

Use of uint8 for counter in for loop increases gas costs #168

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Handle

Dravee

Vulnerability details

Impact Increased gas costs on BoringERC20.sol

Proof of Concept On L19, we use a uint8 as the type for i, the for loop variable: https://github.com/code-423n4/2021-12-yetifinance/blob/1da782328ce4067f9654c3594a34014b0329130a/packages/contracts/contracts/YETI/BoringCrypto/BoringERC20.sol#L19

Due to how the EVM natively works on 256 bit numbers, using a 8 bit number here introduces additional costs as the EVM has to properly enforce the limits of this smaller type.

See the warning at this link: https://docs.soliditylang.org/en/v0.8.0/internals/layout_in_storage.html#layout-of-state-variables-in-storage

When using elements that are smaller than 32 bytes, your contract’s gas usage may be higher. This is because the EVM operates on 32 bytes at a time. Therefore, if the element is smaller than that, the EVM must use more operations in order to reduce the size of the element from 32 bytes to the desired size.

It is only beneficial to use reduced-size arguments if you are dealing with storage values because the compiler will pack multiple elements into one storage slot, and thus, combine multiple reads or writes into a single operation. When dealing with function arguments or memory values, there is no inherent benefit because the compiler does not pack these values.

Recommended Mitigation Steps Change i to be a uint256.

kingyetifinance commented 2 years ago

@LilYeti: Duplicate #123

alcueca commented 2 years ago

Not a duplicate, and it is a worthy gas optimization to be relayed to BoringCrypto to fix.