Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gas Optimizations #226

Open
code423n4 opened this issue Jun 19, 2022 · 0 comments
Open

Gas Optimizations #226

code423n4 opened this issue Jun 19, 2022 · 0 comments
Labels
bug Something isn't working duplicate This issue or pull request already exists G (Gas Optimization)

Comments

@code423n4
Copy link
Contributor

[S]: Suggested optimation, save a decent amount of gas without compromising readability;

[M]: Minor optimation, the amount of gas saved is minor, change when you see fit;

[N]: Non-preferred, the amount of gas saved is at cost of readability, only apply when gas saving is a top priority.

ISSUE LIST

C4-001: Revert String Size Optimization [S]

C4-002 : Adding unchecked directive can save gas [S]

C4-003 : Check if amount > 0 before token transfer can save gas [S]

C4-004 : There is no need to assign default values to variables [S]

C4-005 : Using operator && used more gas [S]

C4-006 : Non-strict inequalities are cheaper than strict ones [M]

C4-007 : Use Custom Errors instead of Revert Strings to save Gas [S]

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

C4-009 : Cache array length in for loops can save gas [S]

C4-010 : State Variables that can be changed to immutable [S]

C4-011 : Use calldata instead of memory for function parameters [M]

C4-012 : ++i is more gas efficient than i++ in loops forwarding

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

C4-014 : Keccak functions in constants waste gas [M]

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:

  contracts/contracts/core/connext/libraries/LibDiamond.sol::66 => require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::113 => revert("LibDiamondCut: Incorrect FacetCutAction");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::121 => require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::123 => require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::132 => require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::139 => require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::141 => require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::150 => require(oldFacetAddress != _facetAddress, "LibDiamondCut: Can't replace function with same function");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::158 => require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::161 => require(_facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::170 => enforceHasContractCode(_facetAddress, "LibDiamondCut: New facet has no code");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::191 => require(_facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::193 => require(_facetAddress != address(this), "LibDiamondCut: Can't remove immutable function");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::224 => require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::226 => require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::228 => enforceHasContractCode(_init, "LibDiamondCut: _init address has no code");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::236 => revert("LibDiamondCut: _init function reverted");
  contracts/contracts/core/connext/libraries/SwapUtils.sol::4 => import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
  contracts/contracts/core/connext/libraries/SwapUtils.sol::5 => import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
  contracts/contracts/core/connext/libraries/SwapUtils.sol::595 => balances[i] = balances[i].sub(amounts[i], "Cannot withdraw more than available");
  contracts/contracts/core/connext/libraries/SwapUtils.sol::697 => require(dy <= self.balances[tokenIndexTo], "Cannot get more than pool balance");
  contracts/contracts/core/connext/libraries/SwapUtils.sol::784 => require(dy <= self.balances[tokenIndexTo], "Cannot get more than pool balance");
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1015 => balances1[i] = v.balances[i].sub(amounts[i], "Cannot withdraw more than available");

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

  contracts/contracts/core/connext/libraries/SwapUtils.sol::1014 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1019 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1039 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1055 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/facets/StableSwapFacet.sol::415 => for (uint8 i = 0; i < _pooledTokens.length; i++) {
  contracts/contracts/core/connext/helpers/ConnextPriceOracle.sol::176 => for (uint256 i = 0; i < tokenAddresses.length; i++) {
  contracts/contracts/core/connext/helpers/Multicall.sol::16 => for (uint256 i = 0; i < calls.length; i++) {
  contracts/contracts/core/connext/helpers/StableSwap.sol::81 => for (uint8 i = 0; i < _pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/Encoding.sol::22 => for (uint8 i = 0; i < 10; i += 1) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::205 => for (uint256 i = 0; i < xp.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::254 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::268 => for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::289 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::300 => for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::302 => for (uint256 j = 0; j < numTokens; j++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::344 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::405 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::425 => for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::558 => for (uint256 i = 0; i < balances.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::591 => for (uint256 i = 0; i < balances.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::844 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::869 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::924 => for (uint256 i = 0; i < amounts.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1014 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1019 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1039 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1055 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/relayer-fee/libraries/RelayerFeeMessage.sol::81 => for (uint256 i = 0; i < length; ) {

Tools Used

None

Recommended Mitigation Steps

Consider applying unchecked arithmetic where overflow/underflow is not possible. Example can be seen from below.

Unchecked{i++};

C4-003 : 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-06-connext/blob/main/contracts/contracts/core/connext/libraries/SwapUtils.sol#L927

All Contracts

Tools Used

None

Recommended Mitigation Steps

Consider checking amount != 0.

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

Impact - Gas Optimization

Boolean is default initialized to false. There is no need assign false to variable.

Proof of Concept

  contracts/contracts/core/connext/libraries/SwapUtils.sol::1014 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1019 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1039 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1055 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/facets/StableSwapFacet.sol::415 => for (uint8 i = 0; i < _pooledTokens.length; i++) {
  contracts/contracts/core/connext/helpers/ConnextPriceOracle.sol::176 => for (uint256 i = 0; i < tokenAddresses.length; i++) {
  contracts/contracts/core/connext/helpers/Multicall.sol::16 => for (uint256 i = 0; i < calls.length; i++) {
  contracts/contracts/core/connext/helpers/StableSwap.sol::81 => for (uint8 i = 0; i < _pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/Encoding.sol::22 => for (uint8 i = 0; i < 10; i += 1) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::205 => for (uint256 i = 0; i < xp.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::254 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::268 => for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::289 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::300 => for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::302 => for (uint256 j = 0; j < numTokens; j++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::344 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::405 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::425 => for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::558 => for (uint256 i = 0; i < balances.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::591 => for (uint256 i = 0; i < balances.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::844 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::869 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::924 => for (uint256 i = 0; i < amounts.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1014 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1019 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1039 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1055 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/relayer-fee/libraries/RelayerFeeMessage.sol::81 => for (uint256 i = 0; i < length; ) {


Tools Used

Code Review

Recommended Mitigation Steps

bool x = false costs more gas than bool x without having any different functionality.

C4-005 : Using operator && used more gas

Impact

Using double require instead of operator && can save more gas.

Proof of Concept

  1. Navigate to the following contracts.
contracts/contracts/core/connext/facets/BridgeFacet.sol:293:      if (_args.params.callback == address(0) && _args.params.callbackFee > 0) {
contracts/contracts/core/connext/facets/BridgeFacet.sol:298:      if (_args.params.callback != address(0) && !Address.isContract(_args.params.callback)) {
contracts/contracts/core/connext/facets/BridgeFacet.sol:638:    if (!s.approvedRelayers[msg.sender] && msg.sender != _args.params.agent) {
contracts/contracts/core/connext/facets/BridgeFacet.sol:655:    if (_args.params.forceSlow && !reconciled) revert BridgeFacet__execute_notReconciled();
contracts/contracts/core/connext/facets/BridgeFacet.sol:673:        if (!_isRouterOwnershipRenounced() && !s.routerPermissionInfo.approvedRouters[_args.routers[i]]) {
contracts/contracts/core/connext/facets/BridgeFacet.sol:781:        !_args.params.receiveLocal &&
contracts/contracts/core/connext/facets/BridgeFacet.sol:782:        pathLen == 1 &&
contracts/contracts/core/connext/facets/BridgeFacet.sol:783:        s.routerBalances[_args.routers[0]][_args.local] < toSwap &&
contracts/contracts/core/connext/facets/RoutersFacet.sol:158:    if (!((owner == address(0) && msg.sender == _router) || owner == msg.sender))
contracts/contracts/core/connext/facets/RoutersFacet.sol:171:      if (!((owner == address(0) && msg.sender == _router) || owner == msg.sender))
contracts/contracts/core/connext/facets/RoutersFacet.sol:543:    if (!_isRouterOwnershipRenounced() && !getRouterApproval(_router))
contracts/contracts/core/connext/facets/RoutersFacet.sol:547:    if (!_isAssetOwnershipRenounced() && !s.approvedAssets[canonicalId])
contracts/contracts/core/connext/facets/ProposedOwnableFacet.sol:205:    if (s._proposed == newlyProposed && newlyProposed != address(0))
contracts/contracts/core/connext/libraries/AmplificationUtils.sol:86:    require(futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A");
contracts/contracts/core/connext/libraries/ConnextMessage.sol:71:    return actionType(_action) == uint8(_type) && messageType(_action) == _type;
contracts/contracts/core/connext/libraries/LibCrossDomainProperty.sol:80:    return isValidPropertyLength(_property) && isType(_property, Types.DomainAndSender);
contracts/contracts/core/connext/libraries/SwapUtils.sol:397:    require(tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool");
contracts/contracts/core/connext/libraries/SwapUtils.sol:493:    require(tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range");
contracts/contracts/core/connext/libraries/SwapUtils.sol:524:    require(tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range");
contracts/contracts/core/connext/libraries/SwapUtils.sol:1007:    require(maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf");
contracts/contracts/core/connext/helpers/ProposedOwnableUpgradeable.sol:241:    if (_proposed == newlyProposed && newlyProposed != address(0))
contracts/contracts/core/connext/helpers/ConnextPriceOracle.sol:93:    if (tokenPrice == 0 && v1PriceOracle != address(0)) {
contracts/contracts/core/connext/helpers/StableSwap.sol:85:          tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i],


Tools Used

Code Review

Recommended Mitigation Steps

Example


using &&:

function check(uint x)public view{
require(x == 0 && x < 1 );
}
// gas cost 21630

using double require:

require(x == 0 );
require( x < 1);
}
}
// gas cost 21622

C4-006 : 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

  contracts/contracts/core/connext/facets/BridgeFacet.sol::293 => if (_args.params.callback == address(0) && _args.params.callbackFee > 0) {
  contracts/contracts/core/connext/facets/BridgeFacet.sol::499 => if (_amount > 0) {
  contracts/contracts/core/connext/facets/BridgeFacet.sol::665 => if (pathLength > 0) // make sure routers are all approved if needed
  contracts/contracts/core/connext/facets/ProposedOwnableFacet.sol::240 => // NOTE: no need to check if _proposedOwnershipTimestamp > 0 because
  contracts/contracts/core/connext/facets/StableSwapFacet.sol::416 => if (i > 0) {
  contracts/contracts/core/connext/helpers/ConnextPriceOracle.sol::150 => require(baseTokenPrice > 0, "invalid base token");
  contracts/contracts/core/connext/helpers/ProposedOwnableUpgradeable.sol::276 => // NOTE: no need to check if _proposedOwnershipTimestamp > 0 because
  contracts/contracts/core/connext/helpers/SponsorVault.sol::217 => if (sponsoredFee > 0) {
  contracts/contracts/core/connext/helpers/StableSwap.sol::82 => if (i > 0) {
  contracts/contracts/core/connext/libraries/AmplificationUtils.sol::86 => require(futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::121 => require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::139 => require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::158 => require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::226 => require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::232 => if (error.length > 0) {
  contracts/contracts/core/connext/libraries/LibDiamond.sol::247 => require(contractSize > 0, _errorMessage);
  contracts/contracts/core/connext/libraries/SwapUtils.sol::369 => if (supply > 0) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::670 => if (dyAdminFee > 0) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::711 => if (dxAdminFee > 0) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::765 => if (dyAdminFee > 0) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::799 => if (dxAdminFee > 0) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::845 => require(v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool");
  contracts/contracts/core/connext/libraries/SwapUtils.sol::965 => if (adminFee > 0) {

Tools Used

Code Review

Recommended Mitigation Steps

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

C4-007 : Use Custom Errors instead of Revert Strings to save Gas

Custom errors from Solidity 0.8.4 are cheaper than revert strings (cheaper deployment cost and runtime cost when the revert condition is met)

Source Custom Errors in Solidity:

Starting from Solidity v0.8.4, there is a convenient and gas-efficient way to explain to users why an operation failed through the use of custom errors. Until now, you could already use strings to give more information about failures (e.g., revert("Insufficient funds.");), but they are rather expensive, especially when it comes to deploy cost, and it is difficult to use dynamic information in them.

Custom errors are defined using the error statement, which can be used inside and outside of contracts (including interfaces and libraries).

Instances include:

All require Statements

Tools Used

Code Review

Recommended Mitigation Steps

Recommended to replace revert strings with custom errors.

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

Contracts

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 : Cache array length in for loops can save gas

Impact

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.

Proof of Concept

  1. Navigate to the following smart contract line.
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1014 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1019 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1039 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1055 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/facets/StableSwapFacet.sol::415 => for (uint8 i = 0; i < _pooledTokens.length; i++) {
  contracts/contracts/core/connext/helpers/ConnextPriceOracle.sol::176 => for (uint256 i = 0; i < tokenAddresses.length; i++) {
  contracts/contracts/core/connext/helpers/Multicall.sol::16 => for (uint256 i = 0; i < calls.length; i++) {
  contracts/contracts/core/connext/helpers/StableSwap.sol::81 => for (uint8 i = 0; i < _pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/Encoding.sol::22 => for (uint8 i = 0; i < 10; i += 1) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::205 => for (uint256 i = 0; i < xp.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::254 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::268 => for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::289 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::300 => for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::302 => for (uint256 j = 0; j < numTokens; j++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::344 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::405 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::425 => for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::558 => for (uint256 i = 0; i < balances.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::591 => for (uint256 i = 0; i < balances.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::844 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::869 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::924 => for (uint256 i = 0; i < amounts.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1014 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1019 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1039 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1055 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/relayer-fee/libraries/RelayerFeeMessage.sol::81 => for (uint256 i = 0; i < length; ) {

Tools Used

None

Recommended Mitigation Steps

Consider to cache array length.

C4-010 : State Variables that can be changed to immutable

Impact

Solidity 0.6.5
introduced immutable as a major feature. It allows setting
contract-level variables at construction time which gets stored in code
rather than storage.

Consider the following generic example:

contract C {
 /// The owner is set during contruction time, and never changed afterwards.
 address public owner = msg.sender;
}

In the above example, each call to the function owner() reads from
storage, using a sload. After
EIP-2929, this costs 2100 gas
cold or 100 gas warm. However, the following snippet is more gas
efficient:

contract C {
 /// The owner is set during contruction time, and never changed afterwards.
 address public immutable owner = msg.sender;
}

In the above example, each storage read of the owner state variable is
replaced by the instruction push32 value, where value is set during
contract construction time. Unlike the last example, this costs only 3
gas.

Tools Used

None

Recommended Mitigation Steps

Consider using immutable variable.

C4-011 : 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.

Proof of Concept

  1. Navigate to the following smart contract line.
contracts/contracts/core/connext/libraries/SwapUtils.sol:286:  function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) {
contracts/contracts/core/connext/libraries/SwapUtils.sol:336:  function _xp(uint256[] memory balances, uint256[] memory precisionMultipliers)

Tools Used

None

Recommended Mitigation Steps

Some parameters in examples given above are later hashed. It may be beneficial for those parameters to be in memory rather than calldata.

C4-012 : ++i is more gas efficient than i++ in loops forwarding

Impact

++i is more gas efficient than i++ in loops forwarding.

Proof of Concept

  1. Navigate to the following contracts.
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1014 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1019 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1039 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1055 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/facets/StableSwapFacet.sol::415 => for (uint8 i = 0; i < _pooledTokens.length; i++) {
  contracts/contracts/core/connext/helpers/ConnextPriceOracle.sol::176 => for (uint256 i = 0; i < tokenAddresses.length; i++) {
  contracts/contracts/core/connext/helpers/Multicall.sol::16 => for (uint256 i = 0; i < calls.length; i++) {
  contracts/contracts/core/connext/helpers/StableSwap.sol::81 => for (uint8 i = 0; i < _pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/Encoding.sol::22 => for (uint8 i = 0; i < 10; i += 1) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::205 => for (uint256 i = 0; i < xp.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::254 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::268 => for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::289 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::300 => for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::302 => for (uint256 j = 0; j < numTokens; j++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::344 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::405 => for (uint256 i = 0; i < numTokens; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::425 => for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::558 => for (uint256 i = 0; i < balances.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::591 => for (uint256 i = 0; i < balances.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::844 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::869 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::924 => for (uint256 i = 0; i < amounts.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1014 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1019 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1039 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::1055 => for (uint256 i = 0; i < pooledTokens.length; i++) {
  contracts/contracts/core/relayer-fee/libraries/RelayerFeeMessage.sol::81 => for (uint256 i = 0; i < length; ) {


Tools Used

Code Review

Recommended Mitigation Steps

It is recommend to use unchecked{++i} and change i declaration to uint256.

C4-013 : > 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 contract sections.
  contracts/contracts/core/connext/facets/BridgeFacet.sol::293 => if (_args.params.callback == address(0) && _args.params.callbackFee > 0) {
  contracts/contracts/core/connext/facets/BridgeFacet.sol::499 => if (_amount > 0) {
  contracts/contracts/core/connext/facets/BridgeFacet.sol::665 => if (pathLength > 0) // make sure routers are all approved if needed
  contracts/contracts/core/connext/facets/ProposedOwnableFacet.sol::240 => // NOTE: no need to check if _proposedOwnershipTimestamp > 0 because
  contracts/contracts/core/connext/facets/StableSwapFacet.sol::416 => if (i > 0) {
  contracts/contracts/core/connext/helpers/ConnextPriceOracle.sol::150 => require(baseTokenPrice > 0, "invalid base token");
  contracts/contracts/core/connext/helpers/ProposedOwnableUpgradeable.sol::276 => // NOTE: no need to check if _proposedOwnershipTimestamp > 0 because
  contracts/contracts/core/connext/helpers/SponsorVault.sol::217 => if (sponsoredFee > 0) {
  contracts/contracts/core/connext/helpers/StableSwap.sol::82 => if (i > 0) {
  contracts/contracts/core/connext/libraries/AmplificationUtils.sol::86 => require(futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::121 => require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::139 => require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::158 => require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::226 => require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)");
  contracts/contracts/core/connext/libraries/LibDiamond.sol::232 => if (error.length > 0) {
  contracts/contracts/core/connext/libraries/LibDiamond.sol::247 => require(contractSize > 0, _errorMessage);
  contracts/contracts/core/connext/libraries/SwapUtils.sol::369 => if (supply > 0) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::670 => if (dyAdminFee > 0) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::711 => if (dxAdminFee > 0) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::765 => if (dyAdminFee > 0) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::799 => if (dxAdminFee > 0) {
  contracts/contracts/core/connext/libraries/SwapUtils.sol::845 => require(v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool");
  contracts/contracts/core/connext/libraries/SwapUtils.sol::965 => if (adminFee > 0) {
  contracts/contracts/core/promise/PromiseRouter.sol::259 => if (callbackFee > 0) {


Tools Used

None

Recommended Mitigation Steps

Consider to replace > 0 with != 0 for gas optimization.

C4-014 : Keccak functions in constants waste gas

Impact

The contracts assigns two constants to the result of a keccak operation, which results in gas waste since the expression is computed each time the constant is accessed.

See this issue for more context: ethereum/solidity#9232 (ethereum/solidity#9232)

Proof of Concept

  contracts/contracts/core/connext/libraries/LibDiamond.sol::14 => bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");

Tools Used

None

Recommended Mitigation Steps

Replace the constant directive with immutable, or assign the already hashed value to the constants

@code423n4 code423n4 added bug Something isn't working G (Gas Optimization) labels Jun 19, 2022
code423n4 added a commit that referenced this issue Jun 19, 2022
@liu-zhipeng liu-zhipeng added the duplicate This issue or pull request already exists label Jul 1, 2022
@itsmetechjay itsmetechjay reopened this Jul 1, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working duplicate This issue or pull request already exists G (Gas Optimization)
Projects
None yet
Development

No branches or pull requests

3 participants