code-423n4 / 2022-07-axelar-findings

0 stars 0 forks source link

Gas Optimizations #204

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Caching the length in for loops and increment in for loop postcondition can be made unchecked

This reduce gas cost as show here https://forum.openzeppelin.com/t/a-collection-of-gas-optimisation-tricks/19966/5

Caching the length in for loops:

  1. if it is a storage array, this is an extra sload operation (100 additional extra gas (EIP-2929 2) for each iteration except for the first),
  2. if it is a memory array, this is an extra mload operation (3 additional gas for each iteration except for the first),
  3. if it is a calldata array, this is an extra calldataload operation (3 additional gas for each iteration except for the first)

for loop postcondition can be made unchecked Gas savings: roughly speaking this can save 30-40 gas per loop iteration. For lengthy loops, this can be significant!

https://github.com/code-423n4/2022-07-axelar/blob/9c4c44b94cddbd48b9baae30051a4e13cbe39539/contracts/deposit-service/AxelarDepositService.sol#L168

for (uint256 i; i < refundTokens.length; i++) {

Can be optimized to

uint256 refundTokensLength = refundTokens.length;
for (uint256 i; i < refundTokensLength;) {
    ...
    unchecked { ++i; }
}

Consider using ++i instead of i++

Currently every loops such as

https://github.com/code-423n4/2022-07-axelar/blob/9c4c44b94cddbd48b9baae30051a4e13cbe39539/contracts/deposit-service/AxelarDepositService.sol#L168

are using i++ which is more expensive than ++i

for (uint256 i; i < refundTokens.length; ++i) {

is better than

for (uint256 i; i < refundTokens.length; i++) {

Use delete to remove wrapping to save gas

https://github.com/code-423n4/2022-07-axelar/blob/9c4c44b94cddbd48b9baae30051a4e13cbe39539/xc20/contracts/XC20Wrapper.sol#L71-L72

Change

        wrapped[axelarToken] = address(0);
        unwrapped[xc20Token] = address(0);

to

        delete wrapped[axelarToken];
        delete unwrapped[xc20Token];

to save gas since delete is using negative gas (Get gas refund)

GalloDaSballo commented 2 years ago

Less than 100 gas saved (delete doesn't save gas btw, delete is a SSTORE for 0)