code-423n4 / 2021-10-slingshot-findings

0 stars 0 forks source link

Adding unchecked directive can save gas #68

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Handle

WatchPug

Vulnerability details

For the arithmetic operations that will never over/underflow, using the unchecked directive (Solidity v0.8 has default overflow/underflow checks) can save some gas from the unnecessary internal over/underflow checks.

For example:

https://github.com/code-423n4/2021-10-slingshot/blob/9c0432cca2e43731d5a0ae9c151dacf7835b8719/contracts/lib/LibERC20Token.sol#L18-L32

if (currentAllowance < amount) {
    // we can optimise gas by using uint256(-1) instead of `amount`
    // using amount is safer, but then each time we interacting with token
    // we have to approve it.
    // For now, let's go with more secure option,
    // when we add whitelisting for tokens and revoke "super admin" option for updating modules
    // we can go for gas and change it to uint256.max
    //
    // however gas usage base on tests looks like this:
    // - with amount:       min 126003, max 442559, avg 249189
    // - with uint256(-1):  min 141006, max 499514, avg 277865
    // so we will spend more at first run (when we need to save all uint256 bits),
    // but then we will gain in next runs.
    token.safeIncreaseAllowance(spender, amount - currentAllowance);
}

amount - currentAllowance will never underflow.

tommyz7 commented 2 years ago

Duplicate of #97