1. Variables: No need to explicitly initialize variables with default values
If a variable is not set/initialized, it is assumed to have the default value (0 for uint, false for bool, address(0) for address…). Explicitly initializing it with its default value is an anti-pattern and wastes gas.
We can use uint number; instead of uint number = 0;
I suggest removing explicit initializations for default values.
2. An array’s length should be cached to save gas in for-loops
Reading array length at each iteration of the loop takes 6 gas (3 for mload and 3 to place memory_offset) in the stack.
Caching the array length in the stack saves around 3 gas per iteration.
contracts/auth/AxelarAuthWeighted.sol:17: for (uint256 i; i < recentOperators.length; ++i) {
contracts/auth/AxelarAuthWeighted.sol:98: for (uint256 i = 0; i < signatures.length; ++i) {
contracts/auth/AxelarAuthWeighted.sol:116: for (uint256 i; i < accounts.length - 1; ++i) {
contracts/deposit-service/AxelarDepositService.sol:114: for (uint256 i; i < refundTokens.length; i++) {
contracts/deposit-service/AxelarDepositService.sol:168: for (uint256 i; i < refundTokens.length; i++) {
contracts/deposit-service/AxelarDepositService.sol:204: for (uint256 i; i < refundTokens.length; i++) {
Remediation:
Here, I suggest storing the array’s length in a variable before the for-loop, and use it instead.
1. Variables: No need to explicitly initialize variables with default values
If a variable is not set/initialized, it is assumed to have the default value (0 for uint, false for bool, address(0) for address…). Explicitly initializing it with its default value is an anti-pattern and wastes gas.
We can use
uint number;
instead ofuint number = 0;
Instance Includes:
contracts/auth/AxelarAuthWeighted.sol:68 contracts/auth/AxelarAuthWeighted.sol:94 contracts/auth/AxelarAuthWeighted.sol:95
Recommendation:
I suggest removing explicit initializations for default values.
2. An array’s length should be cached to save gas in for-loops
Reading array length at each iteration of the loop takes 6 gas (3 for mload and 3 to place memory_offset) in the stack. Caching the array length in the stack saves around 3 gas per iteration.
Instances:
Links: contracts/gas-service/AxelarGasService.sol:123
contracts/auth/AxelarAuthWeighted.sol: L17, L98, L116
contracts/AxelarGateway.sol:207
ontracts/deposit-service/AxelarDepositService.sol: L114 L186 L204
Remediation:
Here, I suggest storing the array’s length in a variable before the for-loop, and use it instead.
3. += costs more gas than = + for state variables
Instances:
contracts/auth/AxelarAuthWeighted.so;: 70 , 105
References:
https://github.com/code-423n4/2022-05-backd-findings/issues/108