code-423n4 / 2022-04-badger-citadel-findings

0 stars 1 forks source link

Gas Optimizations #162

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

C4-001: Revert String Size Optimization

Impact

Shortening revert strings to fit in 32 bytes will decrease deploy time gas and will decrease runtime gas when the revert condition has been met.

Revert strings that are longer than 32 bytes require at least one additional mstore, along with additional overhead for computing memory offset, etc.

Proof of Concept

Revert strings > 32 bytes are here:

https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/CitadelMinter.sol#L321

Tools Used

Manual Review

Recommended Mitigation Steps

Shorten the revert strings to fit in 32 bytes. That will affect gas optimization.

C4-002 : Adding unchecked directive can save gas

Impact

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.

Proof of Concept

https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/CitadelMinter.sol#L152

https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/CitadelMinter.sol#L344

https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/KnightingRound.sol#L260

Tools Used

None

Recommended Mitigation Steps

Consider applying unchecked arithmetic where overflow/underflow is not possible.

C4-003 : Use calldata instead of memory for function parameters

Impact

In some cases, having function arguments in calldata instead of memory is more optimal.

Consider the following generic example:

contract C {
function add(uint[] memory arr) external returns (uint sum) {
uint length = arr.length;
for (uint i = 0; i < arr.length; i++) {
sum += arr[i];
}
}
}

In the above example, the dynamic array arr has the storage location memory. When the function gets called externally, the array values are kept in calldata and copied to memory during ABI decoding (using the opcode calldataload and mstore). And during the for loop, arr[i] accesses the value in memory using a mload. However, for the above example this is inefficient. Consider the following snippet instead:

contract C {
function add(uint[] calldata arr) external returns (uint sum) {
uint length = arr.length;
for (uint i = 0; i < arr.length; i++) {
sum += arr[i];
}
}
}

In the above snippet, instead of going via memory, the value is directly read from calldata using calldataload. That is, there are no intermediate memory operations that carries this value.

Gas savings: In the former example, the ABI decoding begins with copying value from calldata to memory in a for loop. Each iteration would cost at least 60 gas. In the latter example, this can be completely avoided. This will also reduce the number of instructions and therefore reduces the deploy time cost of the contract.

In short, use calldata instead of memory if the function argument is only read.

Note that in older Solidity versions, changing some function arguments from memory to calldata may cause "unimplemented feature error". This can be avoided by using a newer (0.8.*) Solidity compiler.

Examples Note: The following pattern is prevalent in the codebase:

function f(bytes memory data) external {
(...) = abi.decode(data, (..., types, ...));
}

Here, changing to bytes calldata will decrease the gas. The total savings for this change across all such uses would be quite significant.

Proof Of Concept

Examples:

https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/CitadelMinter.sol#L152

https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/CitadelMinter.sol#L344

Tools Used

None

Recommended Mitigation Steps

Change memory definition with calldata.

C4-004 : Non-strict inequalities are cheaper than strict ones

Impact

Strict inequalities add a check of non equality which costs around 3 gas.

Proof of Concept

https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/KnightingRound.sol#L313

Tools Used

Code Review

Recommended Mitigation Steps

Use >= or <= instead of > and < when possible.

C4-005: Use of constant keccak variables results in extra hashing (and so gas).

Impact

That would Increase gas costs on all privileged operations.

Proof of Concept

The following role variables are marked as constant.

https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/KnightingRound.sol#L19
https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/KnightingRound.sol#L24
https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/GlobalAccessControl.sol#L40
https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/GlobalAccessControl.sol#L25

This results in the keccak operation being performed whenever the variable is used, increasing gas costs relative to just storing the output hash. Changing to immutable will only perform hashing on contract deployment which will save gas.

See: ethereum/solidity#9232 (https://github.com/ethereum/solidity/issues/9232#issuecomment-646131646)

Tools Used

Code Review

Recommended Mitigation Steps

Consider to change the variable to be immutable rather than constant.

C4-006 : Check if amount > 0 before token transfer can save gas

Impact

Since _amount can be 0. Checking if (_amount != 0) before the transfer can potentially save an external call and the unnecessary gas cost of a 0 token transfer.

Proof of Concept

https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/StakedCitadel.sol#L469

All Contracts

Tools Used

None

Recommended Mitigation Steps

Consider checking amount != 0.

C4-007 : There is no need to assign default values to variables

Impact - Gas Optimization

When a variable is declared solidity assigns the default value. In case the contract assigns the value again, it costs extra gas.

Example: uint x = 0 costs more gas than uint x without having any different functionality.

Proof of Concept

https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/CitadelMinter.sol#L152

https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/CitadelMinter.sol#L344

Tools Used

Code Review

Recommended Mitigation Steps

uint x = 0 costs more gas than uint x without having any different functionality.

C4-008 : Use Shift Right/Left instead of Division/Multiplication if possible

Impact

A division/multiplication by any number x being a power of 2 can be calculated by shifting log2(x) to the right/left.

While the DIV opcode uses 5 gas, the SHR opcode only uses 3 gas. Furthermore, Solidity's division operation also includes a division-by-0 prevention which is bypassed using shifting.

Proof of Concept

  1. Navigate to the following smart contract line.
  src/Funding.sol::36 => uint256 public citadelPriceInAsset; /// asset per citadel price eg. 1 WBTC (8 decimals) = 40,000 CTDL ==> price = 10^8 / 40,000
  src/KnightingRound.sol::43 => /// eg. 1 WBTC (8 decimals) = 40,000 CTDL ==> price = 10^8 / 40,000
  src/StakedCitadel.sol::252 => maxWithdrawalFee = WITHDRAWAL_FEE_HARD_CAP; // 2% maximum withdrawal fee
  src/StakedCitadel.sol::253 => maxManagementFee = MANAGEMENT_FEE_HARD_CAP; // 2% maximum management fee
  src/StakedCitadelVester.sol::34 => uint256 public constant INITIAL_VESTING_DURATION = 86400 * 21; // 21 days of vesting
  src/interfaces/erc20/IERC20.sol::58 => * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729

Tools Used

None

Recommended Mitigation Steps

A division/multiplication by any number x being a power of 2 can be calculated by shifting log2(x) to the right/left.

C4-009: > 0 can be replaced with != 0 for gas optimization

Impact

!= 0 is a cheaper operation compared to > 0, when dealing with uint.

Proof of Concept

  1. Navigate to the following contracts.
  src/CitadelMinter.sol::270 => } else if (_weight > 0) {
  src/CitadelMinter.sol::343 => require(length > 0, "CitadelMinter: no funding pools");
  src/Funding.sol::170 => require(_assetAmountIn > 0, "_assetAmountIn must not be 0");
  src/Funding.sol::209 => if (funding.discount > 0) {
  src/Funding.sol::322 => require(amount > 0, "nothing to sweep");
  src/Funding.sol::340 => require(amount > 0, "nothing to claim");
  src/Funding.sol::424 => require(_citadelPriceInAsset > 0, "citadel price must not be zero");
  src/Funding.sol::452 => require(_citadelPriceInAsset > 0, "citadel price must not be zero");
  src/KnightingRound.sol::125 => _saleDuration > 0,
  src/KnightingRound.sol::129 => _tokenOutPrice > 0,
  src/KnightingRound.sol::172 => require(_tokenInAmount > 0, "_tokenInAmount should be > 0");
  src/KnightingRound.sol::184 => if (boughtAmountTillNow > 0) {
  src/KnightingRound.sol::215 => require(tokenOutAmount_ > 0, "nothing to claim");
  src/KnightingRound.sol::313 => _saleDuration > 0,
  src/KnightingRound.sol::332 => _tokenOutPrice > 0,
  src/KnightingRound.sol::411 => require(amount > 0, "nothing to sweep");
  src/StakedCitadel.sol::835 => if(_fee > 0) {
  src/StakedCitadel.sol::908 => uint256 management_fee = managementFee > 0
  src/StakedCitadelVester.sol::138 => require(_amount > 0, "StakedCitadelVester: cannot vest 0");
  src/SupplySchedule.sol::61 => globalStartTimestamp > 0,
  src/SupplySchedule.sol::91 => cachedGlobalStartTimestamp > 0,
  src/SupplySchedule.sol::180 => globalStartTimestamp > 0,

Tools Used

Code Review

Recommended Mitigation Steps

Use "!=0" instead of ">0" for the gas optimization.

C4-0010 : Free gas savings for using solidity 0.8.10+

Impact

Using newer compiler versions and the optimizer gives gas optimizations and additional safety checks are available for free.

Proof of Concept

  src/CitadelToken.sol::2 => pragma solidity ^0.8.0;
  src/GlobalAccessControl.sol::3 => pragma solidity ^0.8.0;

Solidity 0.8.10 has a useful change which reduced gas costs of external calls which expect a return value: https://blog.soliditylang.org/2021/11/09/solidity-0.8.10-release-announcement/

Code Generator: Skip existence check for external contract if return data is expected. In this case, the ABI decoder will revert if the contract does not exist

All Contracts

Tools Used

None

Recommended Mitigation Steps

Consider to upgrade pragma to at least 0.8.10.

C4-011: > 0 can be replaced with != 0 for gas optimization

Impact

From Pragma 0.8.0, ABI coder v2 is activated by default. The pragma abicoder v2 can be deleted from the repository. That will provide gas optimization.

Proof of Concept

  1. Navigate to the following code section.

""" https://github.com/code-423n4/2022-04-badger-citadel/blob/main/src/GlobalAccessControl.sol#L4 """

Tools Used

None

Recommended Mitigation Steps

ABI coder v2 is activated by default. It is recommended to delete redundant codes.

From Solidity v0.8.0 Breaking Changes https://docs.soliditylang.org/en/v0.8.0/080-breaking-changes.html