Platform: Code4rena
Start Date: 08/06/2022
Pot Size: $115,000 USDC
Total HM: 26
Participants: 72
Period: 11 days
Judge: leastwood
Total Solo HM: 14
Id: 132
League: ETH
Rank: 35/72
Findings: 2
Award: $241.45
🌟 Selected for report: 0
🚀 Solo Findings: 0
🌟 Selected for report: BowTiedWardens
Also found by: 0x1f8b, 0x29A, 0x52, 0xNazgul, 0xNineDec, 0xf15ers, 0xkatana, 0xmint, Chom, ElKu, Funen, IllIllI, JMukesh, Jujic, Kaiziron, Lambda, MiloTruck, Ruhum, SmartSek, SooYa, TerrierLover, TomJ, WatchPug, Waze, _Adam, asutorufos, auditor0517, bardamu, c3phas, catchup, cccz, ch13fd357r0y3r, cloudjunky, cmichel, cryptphi, csanuragjain, defsec, fatherOfBlocks, hansfriese, hyh, jayjonah8, joestakey, k, kenta, obtarian, oyc_109, robee, sach1r0, shenwilly, simon135, slywaters, sorrynotsorry, tintin, unforgiven, xiaoming90, zzzitron
142.2658 USDC - $142.27
Most contracts use an init pattern (instead of a constructor) to initialize contract parameters. Unless these are enforced to be atomic with contact deployment via deployment script or factory contracts, they are susceptible to front-running race conditions where an attacker/griefer can front-run (cannot access control because admin roles are not initialized) to initially with their own (malicious) parameters upon detecting (if an event is emitted) which the contract deployer has to redeploy wasting gas and risking other transactions from interacting with the attacker-initialized contract.
Many init functions do not have an explicit event emission which makes monitoring such scenarios harder. All of them have re-init checks; while many are explicit some (those in auction contracts) have implicit reinit checks in initAccessControls() which is better if converted to an explicit check in the main init function itself. (details credit to: https://github.com/code-423n4/2021-09-sushimiso-findings/issues/64) The vulnerable initialization functions in the codebase are:
Replica.sol, initialize, 104 PromiseRouter.sol, initialize, 146 NomadBase.sol, __NomadBase_initialize, 97 BridgeToken.sol, initialize, 34 LPToken.sol, initialize, 21 GovernanceRouter.sol, initialize, 179
You allow in some arrays to have duplicates. Sometimes you assumes there are no duplicates in the array.
GovernanceRouter._addDomain pushed (_domain) and doesn't check if the domain already exists.
To improve algorithm precision instead using division in comparison use multiplication in the following scenario:
Instead a < b / c use a * c < b.
In all of the big and trusted contracts this rule is maintained.
RoutersFacet.sol, 349, if (_numerator < (denominator * 95) / 100) revert RoutersFacet__setLiquidityFeeNumerator_tooSmall();
Some fee parameters of functions are not checked for invalid values. Validate the parameters:
StableSwap.setSwapFee (newSwapFee) StableSwap.setAdminFee (newAdminFee) SwapUtils.setSwapFee (newSwapFee) SwapUtils.setAdminFee (newAdminFee) StableSwapFacet.setSwapAdminFee (newAdminFee) StableSwapFacet.setSwapFee (newSwapFee)
Some fee parameters of functions are not checked for invalid values. Validate the parameters:
StableSwap.initialize (_adminFee) PortalFacet.repayAavePortal (_feeAmount) StableSwap.initialize (_fee) SponsorVault.reimburseLiquidityFees (_liquidityFee) SwapUtils._feePerToken (swapFee) PortalFacet._backLoan (_fee) PortalFacet.repayAavePortalFor (_feeAmount) BridgeFacet._getFastTransferAmount (_liquidityFeeDen) StableSwapFacet.initializeSwap (_adminFee) StableSwapFacet.initializeSwap (_fee)
You use safeApprove of openZeppelin although it's deprecated. (see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/566a774222707e424896c0c390a84dc3c13bdcb2/contracts/token/ERC20/utils/SafeERC20.sol#L38) You should change it to increase/decrease Allowance as OpenZeppilin says.
Deprecated safeApprove in RoutersFacet.sol line 267: if (s.routerPermissionInfo.approvedRouters[router]) revert RoutersFacet__setupRouter_alreadyAdded(); Deprecated safeApprove in RoutersFacet.sol line 378: s.routerPermissionInfo.approvedForPortalRouters[_router] = false;
The following requires are with empty messages. This is very important to add a message for any require. So the user has enough information to know the reason of failure.
Solidity file: ExcessivelySafeCall.sol, In line 127 with Empty Require message. Solidity file: Multicall.sol, In line 18 with Empty Require message.
external / public functions parameters should be validated to make sure the address is not 0. Otherwise if not given the right input it can mistakenly lead to loss of user funds.
SponsorVault.sol.withdraw _receiver GovernanceRouter.sol.initialize _recoveryManager DiamondCutFacet.sol.diamondCut _init XAppConnectionManager.sol.setHome _home
The project is compiled with different versions of solidity, which is not recommended because it can lead to undefined behaviors.
owner param should be validated to make sure the owner address is not address(0). Otherwise if not given the right input all only owner accessible functions will be unaccessible.
RoutersFacet.sol.setupRouter owner BridgeToken.sol.transferOwnership _newOwner BridgeToken.sol.permit _owner
Users can mistakenly think that the return value is the named return, but it is actually the actualreturn statement that comes after. To know that the user needs to read the code and is confusing. Furthermore, removing either the actual return or the named return will save gas.
StableSwapFacet.sol, calculateRemoveSwapLiquidityOneToken TypedMemView.sol, indexLEUint TypedMemView.sol, index TypedMemView.sol, nibbleHex TypedMemView.sol, build TypedMemView.sol, hash160 TypedMemView.sol, isValid StableSwap.sol, calculateRemoveLiquidityOneToken TypedMemView.sol, indexUint
The following contracts have a function that allows them an admin to change it to a different address. If the admin accidentally uses an invalid address for which they do not have the private key, then the system gets locked. It is important to have two steps admin change where the first is announcing a pending new admin and the new address should then claim its ownership. A similar issue was reported in a previous contest and was assigned a severity of medium: code-423n4/2021-06-realitycards-findings#105
StableSwap.sol XAppConnectionClient.sol BaseConnextFacet.sol Home.sol GovernanceMessage.sol StableSwapFacet.sol BridgeToken.sol SwapUtils.sol GovernanceRouter.sol ConnextPriceOracle.sol IBridgeToken.sol NomadFacet.sol
You should use safe math for solidity version <8 since there is no default over/under flow check it suchversions of solidity.
The contract UpgradeBeaconProxy.sol doesn't use safe math and is of solidity version < 8 The contract IMessageRecipient.sol doesn't use safe math and is of solidity version < 8 The contract XAppConnectionClient.sol doesn't use safe math and is of solidity version < 8 The contract UpgradeBeaconController.sol doesn't use safe math and is of solidity version < 8
#0 - jakekidd
2022-07-01T22:53:58Z
Missing fee parameter validation and Does not validate the input fee parameter are the same
Some of the "code instances" above seem mismatched??
The contract UpgradeBeaconProxy.sol doesn't use safe math and is of solidity version < 8 The contract IMessageRecipient.sol doesn't use safe math and is of solidity version < 8 The contract XAppConnectionClient.sol doesn't use safe math and is of solidity version < 8 The contract UpgradeBeaconController.sol doesn't use safe math and is of solidity version < 8
all of these are out of scope
Solidity file: ExcessivelySafeCall.sol, In line 127 with Empty Require message. Solidity file: Multicall.sol, In line 18 with Empty Require message.
out of scope
🌟 Selected for report: IllIllI
Also found by: 0x1f8b, 0x29A, 0xKitsune, 0xNazgul, 0xf15ers, 0xkatana, 0xmint, BowTiedWardens, ElKu, Fitraldys, Funen, Kaiziron, Lambda, Metatron, MiloTruck, Randyyy, Ruhum, SmartSek, TomJ, Tomio, UnusualTurtle, Waze, _Adam, apostle0x01, asutorufos, c3phas, catchup, csanuragjain, defsec, fatherOfBlocks, hansfriese, hyh, ignacio, joestakey, k, kaden, nahnah, oyc_109, rfa, robee, sach1r0, simon135, slywaters
99.18 USDC - $99.18
In the following files there are state variables that could be set immutable to save gas.
wrapped in ConnextPriceOracle.sol remoteDomain in Replica.sol tokenBeacon in TokenRegistry.sol
Unused state variables are gas consuming at deployment (since they are located in storage) and are a bad code practice. Removing those variables will decrease deployment gas cost and improve code quality. This is a full list of all the unused storage variables we found in your code base.
NomadBase.sol, committedRoot PriceOracle.sol, isPriceOracle
There are places in the code (especially in for-each loops) that loads the same array element more than once. In such cases, only one array boundaries check should take place, and the rest are unnecessary. Therefore, this array element should be cached in a local variable and then be loaded again using this local variable, skipping the redundant second array boundaries check:
SwapUtils.sol.removeLiquidity - double load of minAmounts[i] Multicall.sol.aggregate - double load of calls[i]
Caching the array length is more gas efficient. This is because access to a local variable in solidity is more efficient than query storage / calldata / memory. We recommend to change from:
for (uint256 i=0; i<array.length; i++) { ... }
to:
uint len = array.length for (uint256 i=0; i<len; i++) { ... }
StableSwap.sol, _pooledTokens, 81 GovernanceRouter.sol, _calls, 419 SwapUtils.sol, balances, 558 GovernanceRouter.sol, _localCalls, 244 GovernanceRouter.sol, domains, 443 TypedMemView.sol, memViews, 813 GovernanceRouter.sol, _remoteCalls, 248 RelayerFacet.sol, _transferIds, 164 SwapUtils.sol, xp, 205 ConnextPriceOracle.sol, tokenAddresses, 176 SwapUtils.sol, pooledTokens, 844 SwapUtils.sol, pooledTokens, 1039 GovernanceRouter.sol, domains, 326 SwapUtils.sol, pooledTokens, 1055
Prefix increments are cheaper than postfix increments.
Further more, using unchecked {++x} is even more gas efficient, and the gas saving accumulates every iteration and can make a real change
There is no risk of overflow caused by increamenting the iteration index in for loops (the ++i
in for (uint256 i = 0; i < numIterations; ++i)
).
But increments perform overflow checks that are not necessary in this case.
These functions use not using prefix increments (++x
) or not using the unchecked keyword:
change to prefix increment and unchecked: Queue.sol, i, 95 change to prefix increment and unchecked: Merkle.sol, i, 34 change to prefix increment and unchecked: GovernanceRouter.sol, i, 248 change to prefix increment and unchecked: Queue.sol, i, 111 change to prefix increment and unchecked: ConnextPriceOracle.sol, i, 176 change to prefix increment and unchecked: Merkle.sol, i, 128 change to prefix increment and unchecked: SwapUtils.sol, i, 591 change to prefix increment and unchecked: SwapUtils.sol, i, 300 change to prefix increment and unchecked: StableSwapFacet.sol, i, 415 change to prefix increment and unchecked: SwapUtils.sol, i, 425 change to prefix increment and unchecked: SwapUtils.sol, i, 924 change to prefix increment and unchecked: GovernanceRouter.sol, i, 443 change to prefix increment and unchecked: GovernanceRouter.sol, i, 244 change to prefix increment and unchecked: Merkle.sol, i, 60 change to prefix increment and unchecked: SwapUtils.sol, i, 254 change to prefix increment and unchecked: SwapUtils.sol, i, 558 change to prefix increment and unchecked: StableSwap.sol, i, 81
In for loops you initialize the index to start from 0, but it already initialized to 0 in default and this assignment cost gas. It is more clear and gas efficient to declare without assigning 0 and will have the same meaning:
SwapUtils.sol, 1039 StableSwapFacet.sol, 415 Queue.sol, 71 SwapUtils.sol, 924 Multicall.sol, 16 ConnextPriceOracle.sol, 176 SwapUtils.sol, 405 GovernanceMessage.sol, 97 SwapUtils.sol, 425
Reading a storage variable is gas costly (SLOAD). In cases of multiple read of a storage variable in the same scope, caching the first read (i.e saving as a local variable) can save gas and decrease the overall gas uses. The following is a list of functions and the storage variables that you read twice:
SponsorVault.sol: relayerFeeCap is read twice in reimburseRelayerFees
Unnecessary default assignments, you can just declare and it will save gas and have the same meaning.
Version.sol (L#9) : uint8 public constant VERSION = 0; VersionFacet.sol (L#16) : uint8 internal immutable _version = 0; Version0.sol (L#9) : uint8 public constant VERSION = 0; BridgeFacet.sol (L#68) : uint16 public constant AAVE_REFERRAL_CODE = 0;
You can change the order of the storage variables to decrease memory uses.
In TypedMemView.sol,rearranging the storage fields can optimize to: 2 slots from: 3 slots. The new order of types (you choose the actual variables): 1. uint256 2. bytes29 3. uint8
In FacetHelper.sol,rearranging the storage fields can optimize to: 11 slots from: 12 slots. The new order of types (you choose the actual variables): 1. bytes32 2. bytes32 3. uint256 4. uint256 5. uint256 6. address 7. uint32 8. uint32 9. uint32 10. address 11. address 12. address 13. address 14. address
In GovernanceRouter.sol,rearranging the storage fields can optimize to: 5 slots from: 6 slots. The new order of types (you choose the actual variables): 1. uint256 2. uint256 3. XAppConnectionManager 4. address 5. uint32 6. uint32 7. address
In Replica.sol,rearranging the storage fields can optimize to: 4 slots from: 5 slots. The new order of types (you choose the actual variables): 1. uint256 2. uint256 3. uint256 4. uint32 5. uint8
In ProposedOwnableUpgradeable.sol,rearranging the storage fields can optimize to: 6 slots from: 8 slots. The new order of types (you choose the actual variables): 1. uint256 2. uint256 3. uint256 4. uint256 5. address 6. bool 7. bool 8. address
In Executor.sol,rearranging the storage fields can optimize to: 4 slots from: 5 slots. The new order of types (you choose the actual variables): 1. bytes 2. uint256 3. uint256 4. address 5. uint16
In RelayerFeeMessage.sol,rearranging the storage fields can optimize to: 5 slots from: 6 slots. The new order of types (you choose the actual variables): 1. uint256 2. uint256 3. uint256 4. uint256 5. uint8 6. uint8
Use bytes32 instead of string to save gas whenever possible. String is a dynamic data structure and therefore is more gas consuming then bytes32.
TypedMemView.sol (L287), string memory err = string( abi.encodePacked("Type assertion failed. Got 0x", uint80(g), ". Expected 0x", uint80(e)) );
The following require messages are of length more than 32 and we think are short enough to short them into exactly 32 characters such that it will be placed in one slot of memory and the require function will cost less gas. The list:
Solidity file: SwapUtils.sol, In line 784, Require message length to shorten: 33, The message: Cannot get more than pool balance Solidity file: OZERC20.sol, In line 254, Require message length to shorten: 34, The message: ERC20: approve to the zero address Solidity file: OZERC20.sol, In line 253, Require message length to shorten: 36, The message: ERC20: approve from the zero address Solidity file: OZERC20.sol, In line 186, Require message length to shorten: 35, The message: ERC20: transfer to the zero address Solidity file: SwapUtils.sol, In line 697, Require message length to shorten: 33, The message: Cannot get more than pool balance Solidity file: GovernanceRouter.sol, In line 240, Require message length to shorten: 36, The message: !domains length matches calls length Solidity file: OZERC20.sol, In line 226, Require message length to shorten: 33, The message: ERC20: burn from the zero address Solidity file: TypedMemView.sol, In line 745, Require message length to shorten: 40, The message: TypedMemView/copyTo - Null pointer deref Solidity file: OZERC20.sol, In line 185, Require message length to shorten: 37, The message: ERC20: transfer from the zero address
Using != 0 is slightly cheaper than > 0. (see https://github.com/code-423n4/2021-12-maple-findings/issues/75 for similar issue)
ProposedOwnableUpgradeable.sol, 276: change '_proposedOwnershipTimestamp > 0' to '_proposedOwnershipTimestamp != 0' SwapUtils.sol, 1007: change 'balance > 0' to 'balance != 0' StableSwapFacet.sol, 132: change 'balance > 0' to 'balance != 0' BridgeFacet.sol, 499: change '_amount > 0' to '_amount != 0' SponsorVault.sol, 258: change 'balance > 0' to 'balance != 0' AmplificationUtils.sol, 86: change 'futureA_ > 0' to 'futureA_ != 0' SwapUtils.sol, 954: change 'balance > 0' to 'balance != 0' SwapUtils.sol, 916: change 'balance > 0' to 'balance != 0'
IUpdaterManager Home.sol._setUpdaterManager - unnecessary casting IUpdaterManager(_updaterManager)
You can use unchecked in the following calculations since there is no risk to overflow:
Replica.sol (L#143) - confirmAt[_newRoot] = block.timestamp + optimisticSeconds;
Due to how the EVM natively works on 256 numbers, using a 8 bit number here introduces additional costs as the EVM has to properly enforce the limits of this smaller type. See the warning at this link: https://docs.soliditylang.org/en/v0.8.0/internals/layout_in_storage.html#layout-of-state-variables-in-storage We recommend to use uint256 for the index in every for loop instead using uint8:
StableSwapFacet.sol, uint8 i, 415 Encoding.sol, uint8 i, 22 Encoding.sol, uint8 i, 36 StableSwap.sol, uint8 i, 81 TypedMemView.sol, uint8 i, 158 TypedMemView.sol, uint8 i, 146
You can inline the following functions instead of writing a specific function to save gas. (see https://github.com/code-423n4/2021-11-nested-findings/issues/167 for a similar issue.)
TypedMemView.sol, nullView, { return NULL; } TypedMemView.sol, isNull, { return memView == NULL; } TypedMemView.sol, notNull, { return !isNull(memView); } Queue.sol, lastItem, { return _q.queue[_q.last]; } Queue.sol, isEmpty, { return _q.last < _q.first; } AmplificationUtils.sol, getAPrecise, { return _getAPrecise(self); } GovernanceMessage.sol, governor, { return _view.index(5, 32); }
The following functions are used exactly once. Therefore you can inline them and save gas and improve code clearness.
Message.sol, destination NomadBase.sol, _setUpdater GovernanceMessage.sol, serializeCall XAppConnectionManager.sol, _recoverWatcherFromSig XAppConnectionClient.sol, _isReplica
Change if -> revert pattern to 'require' to save gas and improve code quality, if (some_condition) { revert(revert_message) }
to: require(!some_condition, revert_message)
In the following locations:
UpgradeBeaconProxy.sol, 85 TypedMemView.sol, 568 UpgradeBeaconController.sol, 39
Using newer compiler versions and the optimizer gives gas optimizations and additional safety checks are available for free.
The advantages of versions 0.8.* over <0.8.0 are:
1. Safemath by default from 0.8.0 (can be more gas efficient than library based safemath.) 2. Low level inliner : from 0.8.2, leads to cheaper runtime gas. Especially relevant when the contract has small functions. For example, OpenZeppelin libraries typically have a lot of small helper functions and if they are not inlined, they cost an additional 20 to 40 gas because of 2 extra jump instructions and additional stack operations needed for function calls. 3. Optimizer improvements in packed structs: Before 0.8.3, storing packed structs, in some cases used an additional storage read operation. After EIP-2929, if the slot was already cold, this means unnecessary stack operations and extra deploy time costs. However, if the slot was already warm, this means additional cost of 100 gas alongside the same unnecessary stack operations and extra deploy time costs. 4. Custom errors from 0.8.4, leads to cheaper deploy time cost and run time cost. Note: the run time cost is only relevant when the revert condition is met. In short, replace revert strings by custom errors.
XAppConnectionManager.sol NomadBase.sol Version0.sol XAppConnectionClient.sol UpgradeBeaconProxy.sol Home.sol TypeCasts.sol GovernanceMessage.sol
We recommend not to cache msg.sender since calling it is 2 gas while reading a variable is more.
https://github.com/code-423n4/2022-06-connext/tree/main/contracts/contracts/nomad-core/contracts/governance/GovernanceRouter.sol#L182 https://github.com/code-423n4/2022-06-connext/tree/main/contracts/contracts/core/connext/helpers/ConnextPriceOracle.sol#L78 https://github.com/code-423n4/2022-06-connext/tree/main/contracts/contracts/core/connext/facets/BridgeFacet.sol#L416