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

0 stars 0 forks source link

Gas Optimizations #199

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

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;

Instance Includes:

contracts/auth/AxelarAuthWeighted.sol:68 contracts/auth/AxelarAuthWeighted.sol:94 contracts/auth/AxelarAuthWeighted.sol:95

contracts/auth/AxelarAuthWeighted.sol:68:        uint256 totalWeight = 0;
contracts/auth/AxelarAuthWeighted.sol:94:        uint256 operatorIndex = 0;
contracts/auth/AxelarAuthWeighted.sol:95:        uint256 weight = 0;

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/gas-service/AxelarGasService.sol:123:        for (uint256 i; i < tokens.length; i++) {

contracts/auth/AxelarAuthWeighted.sol: L17, L98, L116

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/AxelarGateway.sol:207

contracts/AxelarGateway.sol:207:        for (uint256 i = 0; i <symbols.length; i++) {

ontracts/deposit-service/AxelarDepositService.sol: L114 L186 L204

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.


3. += costs more gas than = + for state variables

Instances:

contracts/auth/AxelarAuthWeighted.so;: 70 , 105

contracts/auth/AxelarAuthWeighted.sol:70:            totalWeight += newWeights[i];
contracts/auth/AxelarAuthWeighted.sol:105:            weight += weights[operatorIndex];

References:

https://github.com/code-423n4/2022-05-backd-findings/issues/108


GalloDaSballo commented 2 years ago

Less than 100 gas saved (no unchecked nor ++i)