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

0 stars 0 forks source link

Gas Optimizations #222

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

G-1 ++I COSTS LESS GAS THAN I++, ESPECIALLY WHEN IT’S USED IN FOR-LOOPS (--I/I-- TOO) Saves 6 gas per loop AxelarGateway.sol L#207

AxelarAuthWeighted.sol L#98 AxelarAuthWeighted.sol L#116

G-2 .LENGTH SHOULD NOT BE LOOKED UP IN EVERY LOOP OF A FOR-LOOP The overheads outlined below are PER LOOP, excluding the first loop

storage arrays incur a Gwarmaccess (100 gas) memory arrays use MLOAD (3 gas) calldata arrays use CALLDATALOAD (3 gas) Caching the length changes each of these to a DUP (3 gas), and gets rid of the extra DUP needed to store the stack offset

AxelarGateway.sol L#207

AxelarAuthWeighted.sol L#98 AxelarAuthWeighted.sol L#116

G-3 ++I/I++ SHOULD BE UNCHECKED{++I}/UNCHECKED{I++}WHEN IT IS NOT POSSIBLE FOR THEM TO OVERFLOW, AS IS THE CASE WHEN USED IN FOR- AND WHILE-LOOPS AxelarGateway.sol L#207

AxelarAuthWeighted.sol L#98 AxelarAuthWeighted.sol L#116

G-4 MULTIPLE ADDRESS MAPPINGS CAN BE COMBINED INTO A SINGLE MAPPING OF AN ADDRESS TO A STRUCT, WHERE APPROPRIATE Saves a storage slot for the mapping. Depending on the circumstances and sizes of types, can avoid a Gsset (20000 gas) per mapping combined. Reads and subsequent writes can also be cheaper when a function requires both values and they both fit in the same storage slot. Finally, if both fields are accessed in the same function, can save ~42 gas per access due to not having to recalculate the key’s keccak256 hash (Gkeccak256 - 30 gas) and that calculation’s associated stack operations.

https://github.com/code-423n4/2022-07-axelar/blob/main/xc20/contracts/XC20Wrapper.sol#:~:text=mapping(address,)%20public%20unwrapped%3B

G-5 IT COSTS MORE GAS TO INITIALIZE VARIABLES TO ZERO THAN TO LET THE DEFAULT OF ZERO BE APPLIED AxelarGateway.sol L#207 AxelarAuthWeighted.sol L#68 AxelarAuthWeighted.sol L#94-95 AxelarAuthWeighted.sol L#98 AxelarAuthWeighted.sol L#116

GalloDaSballo commented 2 years ago

40 gas from keccak + less than 100 for rest

GalloDaSballo commented 2 years ago

150 to be generous