Rubicon contest - defsec's results

An order book protocol for Ethereum, built on L2s.

General Information

Platform: Code4rena

Start Date: 23/05/2022

Pot Size: $50,000 USDC

Total HM: 44

Participants: 99

Period: 5 days

Judge: hickuphh3

Total Solo HM: 11

Id: 129

League: ETH

Rubicon

Findings Distribution

Researcher Performance

Rank: 54/99

Findings: 4

Award: $93.83

🌟 Selected for report: 0

🚀 Solo Findings: 0

Judge has assessed an item in Issue #380 as Medium risk. The relevant finding follows:

#0 - HickupHH3

2022-06-25T03:49:08Z

C4-001 : Use safeTransfer/safeTransferFrom consistently instead of transfer/transferFrom

dup of #316

Awards

1.8534 USDC - $1.85

Labels

bug
duplicate
2 (Med Risk)

External Links

Lines of code

https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/RubiconMarket.sol#L1232

Vulnerability details

Impact

The ** feeBps** does not have any upper or lower bounds. Values that are too large will lead to reversions in several critical functions or the platform user will lost all funds when paying the fee. If the authorization sets to fee as %1000, the market owner can steal funds.

Proof of Concept

  1. Navigate to the following contract : https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/RubiconMarket.sol#L1232

Tools Used

Code Review

Consider defining upper and lower bounds on the feeBps variable.

#0 - bghughes

2022-06-04T20:31:38Z

Duplicate of #125

#1 - HickupHH3

2022-06-18T04:37:14Z

Duplicate of #21

ISSUE LIST

C4-001 : Use safeTransfer/safeTransferFrom consistently instead of transfer/transferFrom

C4-002 : Front-runnable Initializers

C4-003 : Missing zero-address check in the setter functions and initiliazers

C4-004 : Missing events for only functions that change critical parameters

C4-005 : Critical changes should use two-step procedure

C4-006 : Pragma Version

C4-007 : transferOwnership should be two step

C4-008 : Missing Re-entrancy Guard

C4-009 : Contract should have pause/unpause functionality

C4-001 : Use safeTransfer/safeTransferFrom consistently instead of transfer/transferFrom

Impact - LOW

Impact

It is good to add a require() statement that checks the return value of token transfers or to use something like OpenZeppelin’s safeTransfer/safeTransferFrom unless one is sure the given token reverts in case of a failure. Failure to do so will cause silent failures of transfers and affect token accounting in contract.

Reference: This similar medium-severity finding from Consensys Diligence Audit of Fei Protocol: https://consensys.net/diligence/audits/2021/01/fei-protocol/#unchecked-return-value-for-iweth-transfer-call

Proof of Concept

  1. Navigate to the following contract.

  2. transfer/transferFrom functions are used instead of safe transfer/transferFrom on the following contracts.

contracts/RubiconRouter.sol:303: ERC20(buy_gem).transfer(msg.sender, fill); contracts/RubiconRouter.sol:320: ERC20(buy_gem).transfer(msg.sender, fill); contracts/RubiconRouter.sol:348: ERC20(buy_gem).transfer(msg.sender, buy_amt); contracts/RubiconRouter.sol:377: ERC20(pay_gem).transfer(msg.sender, max_fill_amount - fill); contracts/RubiconRouter.sol:406: ERC20(buy_gem).transfer(msg.sender, _after - _before); contracts/RubiconRouter.sol:366: ERC20(pay_gem).transferFrom(msg.sender, address(this), max_fill_amount); //transfer pay here contracts/RubiconRouter.sol:471: ERC20(targetPool).transfer(msg.sender, newShares); contracts/rubiconPools/BathPair.sol:544: // transfer here contracts/rubiconPools/BathPair.sol:601: IERC20(asset).transfer(msg.sender, booty); contracts/rubiconPools/BathPair.sol:615: IERC20(quote).transfer(msg.sender, booty); contracts/rubiconPools/BathToken.sol:353: IERC20(filledAssetToRebalance).transfer( contracts/rubiconPools/BathToken.sol:357: IERC20(filledAssetToRebalance).transfer(msg.sender, stratReward); contracts/rubiconPools/BathToken.sol:602: underlyingToken.transfer(feeTo, _fee); contracts/rubiconPools/BathToken.sol:605: underlyingToken.transfer(receiver, amountWithdrawn); contracts/rubiconPools/BathToken.sol:693: function transfer(address to, uint256 value) external returns (bool) {

Tools Used

Code Review

Consider using safeTransfer/safeTransferFrom or require() consistently.

C4-002 : Front-runnable Initializers

Impact - LOW

All contract initializers were missing access controls, allowing any user to initialize the contract. By front-running the contract deployers to initialize the contract, the incorrect parameters may be supplied, leaving the contract needing to be redeployed.

Proof of Concept

  1. Navigate to the following contracts.
contracts/RubiconMarket.sol:551: function initialize(bool _live, address _feeTo) public { contracts/rubiconPools/BathPair.sol:115: function initialize(uint256 _maxOrderSizeBPS, int128 _shapeCoefNum) contracts/rubiconPools/BathToken.sol:181: function initialize( contracts/rubiconPools/BathHouse.sol:97: function initialize( contracts/rubiconPools/BathHouse.sol:231: /// @notice Function to initialize and store the address of the ~lone~ bathPair contract for the Rubicon protocol contracts/rubiconPools/BathHouse.sol:247: IBathPair(newPair).initialize(_maxOrderSizeBPS, _shapeCoefNum); contracts/rubiconPools/BathHouse.sol:417: "initialize(address,address,address)",
  1. initialize functions does not have access control. They are vulnerable to front-running.

Tools Used

Manual Code Review

While the code that can be run in contract constructors is limited, setting the owner in the contract's constructor to the msg.sender and adding the onlyOwner modifier to all initializers would be a sufficient level of access control.

C4-003 : # Missing zero-address check in the setter functions and initiliazers

Impact

Missing checks for zero-addresses may lead to infunctional protocol, if the variable addresses are updated incorrectly.

Proof of Concept

  1. Navigate to the following contracts.
https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/rubiconPools/BathToken.sol#L183 https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/rubiconPools/BathHouse.sol#L97

Tools Used

Code Review

Consider adding zero-address checks in the discussed constructors: require(newAddr != address(0));.

C4-004 : Missing events for only functions that change critical parameters

Impact - Non critical

The afunctions that change critical parameters should emit events. Events allow capturing the changed parameters so that off-chain tools/interfaces can register such changes with timelocks that allow users to evaluate them and consider if they would like to engage/exit based on how they perceive the changes as affecting the trustworthiness of the protocol or profitability of the implemented financial services. The alternative of directly querying on-chain contract state for such changes is not considered practical for most users/usages.

Missing events and timelocks do not promote transparency and if such changes immediately affect users’ perception of fairness or trustworthiness, they could exit the protocol causing a reduction in liquidity which could negatively impact protocol TVL and reputation.

Proof of Concept

  1. Navigate to the following contract.
https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/rubiconPools/BathHouse.sol#L253 https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/rubiconPools/BathHouse.sol#L279 https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/rubiconPools/BathHouse.sol#L286 https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/rubiconPools/BathHouse.sol#L294 https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/rubiconPools/BathHouse.sol#L310

See similar High-severity H03 finding OpenZeppelin’s Audit of Audius (https://blog.openzeppelin.com/audius-contracts-audit/#high) and Medium-severity M01 finding OpenZeppelin’s Audit of UMA Phase 4 (https://blog.openzeppelin.com/uma-audit-phase-4/)

Tools Used

None

Add events to all functions that change critical parameters.

C4-005 : Critical changes should use two-step procedure

Impact - NON CRITICAL

The critical procedures should be two step process.

Proof of Concept

  1. Navigate to the following contract.
https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/rubiconPools/BathHouse.sol#L253 https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/rubiconPools/BathHouse.sol#L279 https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/rubiconPools/BathHouse.sol#L286 https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/rubiconPools/BathHouse.sol#L294 https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/rubiconPools/BathHouse.sol#L310

Tools Used

Code Review

Lack of two-step procedure for critical operations leaves them error-prone. Consider adding two step procedure on the critical functions.

C4-006 : # Pragma Version

Impact

In the contracts, floating pragmas should not be used. Contracts should be deployed with the same compiler version and flags that they have been tested with thoroughly. Locking the pragma helps to ensure that contracts do not accidentally get deployed using, for example, an outdated compiler version that might introduce bugs that affect the contract system negatively.

## Proof of Concept

https://swcregistry.io/docs/SWC-103

../../contracts/c4udit/examples/Test.sol::1 => pragma solidity ^0.8.0; ../../contracts/interfaces/IBathBuddy.sol::3 => pragma solidity >=0.7.6; ../../contracts/interfaces/IBathHouse.sol::3 => pragma solidity >=0.7.6; ../../contracts/interfaces/IBathPair.sol::3 => pragma solidity >=0.7.6; ../../contracts/interfaces/IBathToken.sol::3 => pragma solidity >=0.7.6; ../../contracts/interfaces/IERC20Minimal.sol::2 => pragma solidity >=0.5.0; ../../contracts/interfaces/IRubiconMarket.sol::3 => pragma solidity >=0.7.6; ../../contracts/interfaces/IStrategistUtility.sol::3 => pragma solidity >=0.7.6; ../../contracts/interfaces/IVestingWallet.sol::3 => pragma solidity >=0.7.6; ../../contracts/interfaces/IWETH.sol::3 => pragma solidity >=0.7.6; ../../contracts/peripheral_contracts/BathBuddy.sol::2 => pragma solidity >=0.6.0 <0.8.0; ../../contracts/peripheral_contracts/ERC20.sol::3 => pragma solidity >=0.6.0 <0.8.0; ../../contracts/peripheral_contracts/IERC20.sol::3 => pragma solidity >=0.6.0 <0.8.0; ../../contracts/peripheral_contracts/VestingWallet.sol::3 => pragma solidity ^0.7.6; ../../contracts/proxy/Address.sol::3 => pragma solidity >=0.6.2 <0.8.0; ../../contracts/proxy/OVMProxy.sol::3 => pragma solidity >=0.6.0 <0.8.0; ../../contracts/proxy/TransparentUpgradeableProxy.sol::3 => pragma solidity >=0.6.0 <0.8.0; ../../contracts/proxy/UpgradeableProxy.sol::3 => pragma solidity >=0.6.0 <0.8.0;

Tools Used

Manual code review

Upgrade pragma solidity 0.8.10.

C4-007: transferOwnership should be two step

Impact - NON CRITICAL

The owner is the authorized user in the solidity contracts. Usually, an owner can be updated with transferOwnership function. However, the process is only completed with single transaction. If the address is updated incorrectly, an owner functionality will be lost forever.

Proof of Concept

  1. Navigate to the following contracts.
https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/RubiconMarket.sol#L22

Tools Used

Code Review

Lack of two-step procedure for critical operations leaves them error-prone. Consider adding two step procedure on the critical functions.

C4-008 : # Missing Re-entrancy Guard

Impact - LOW

The re-entrancy guard is missing on the some of the functions. The external interactions can cause to the re-entrancy vulnerability.

Proof of Concept

  1. Navigate to the following contract.
https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/RubiconMarket.sol#L392 https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/RubiconMarket.sol#L272

Tools Used

Code Review

Follow the check effect interaction pattern or put re-entrancy guard.

C4-009 : Contract should have pause/unpause functionality

Impact

In case a hack is occuring or an exploit is discovered, the team should be able to pause functionality until the necessary changes are made to the system. Additionally, the AuraLocker.sol contract should be manged by proxy so that upgrades can be made by the owner.

To use a thorchain example again, the team behind thorchain noticed an attack was going to occur well before the system transferred funds to the hacker. However, they were not able to shut the system down fast enough. (According to the incidence report here: https://github.com/HalbornSecurity/PublicReports/blob/master/Incident%20Reports/Thorchain_Incident_Analysis_July_23_2021.pdf)

Proof of Concept

All Market Functions

Tools Used

Code Review

Pause functionality on the contract would have helped secure the funds quickly.

C4-001: Revert String Size Optimization

C4-002 : Adding unchecked directive can save gas

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

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

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

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

C4-007 : Using operator && used more gas

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

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

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

C4-011 : Cache array length in for loops can save gas

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

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

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/RubiconMarket.sol::571 => require(isActive(id), "Offer was deleted or taken, or never existed."); ../../contracts/peripheral_contracts/ERC20.sol::269 => require(sender != address(0), "ERC20: transfer from the zero address"); ../../contracts/peripheral_contracts/ERC20.sol::270 => require(recipient != address(0), "ERC20: transfer to the zero address"); ../../contracts/peripheral_contracts/ERC20.sol::276 => "ERC20: transfer amount exceeds balance" ../../contracts/peripheral_contracts/ERC20.sol::313 => require(account != address(0), "ERC20: burn from the zero address"); ../../contracts/peripheral_contracts/ERC20.sol::319 => "ERC20: burn amount exceeds balance" ../../contracts/peripheral_contracts/ERC20.sol::343 => require(owner != address(0), "ERC20: approve from the zero address"); ../../contracts/peripheral_contracts/ERC20.sol::344 => require(spender != address(0), "ERC20: approve to the zero address"); ../../contracts/rubiconPools/BathToken.sol::470 => require(_shares == shares, "did not mint expected share count"); ../../contracts/rubiconPools/BathPair.sol::318 => require(assigned, "Didnt Find that element in live list, cannot scrub");

Tools Used

Manual Review

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/RubiconRouter.sol::85 => for (uint256 index = 0; index < topNOrders; index++) { ../../contracts/RubiconRouter.sol::168 => uint256 currentAmount = 0; ../../contracts/RubiconRouter.sol::169 => for (uint256 i = 0; i < route.length - 1; i++) { ../../contracts/RubiconRouter.sol::226 => uint256 currentAmount = 0; ../../contracts/RubiconRouter.sol::227 => for (uint256 i = 0; i < route.length - 1; i++) { ../../contracts/rubiconPools/BathPair.sol::310 => bool assigned = false; ../../contracts/rubiconPools/BathPair.sol::311 => for (uint256 index = 0; index < array.length; index++) { ../../contracts/rubiconPools/BathPair.sol::427 => for (uint256 index = 0; index < quantity; index++) { ../../contracts/rubiconPools/BathPair.sol::480 => for (uint256 index = 0; index < quantity; index++) { ../../contracts/rubiconPools/BathPair.sol::582 => for (uint256 index = 0; index < ids.length; index++) { ../../contracts/rubiconPools/BathToken.sol::635 => for (uint256 index = 0; index < bonusTokens.length; index++) {

Tools Used

None

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

../../contracts/RubiconMarket.sol::298 => _offer.buy_gem.transferFrom(msg.sender, feeTo, fee), ../../contracts/RubiconMarket.sol::305 => _offer.buy_gem.transferFrom(msg.sender, _offer.owner, spend), ../../contracts/RubiconMarket.sol::306 => "_offer.buy_gem.transferFrom(msg.sender, _offer.owner, spend) failed - check that you can pay the fee" ../../contracts/RubiconMarket.sol::309 => _offer.pay_gem.transfer(msg.sender, quantity), ../../contracts/RubiconMarket.sol::310 => "_offer.pay_gem.transfer(msg.sender, quantity) failed" ../../contracts/RubiconMarket.sol::361 => require(_offer.pay_gem.transfer(_offer.owner, _offer.pay_amt)); ../../contracts/RubiconMarket.sol::416 => require(pay_gem.transferFrom(msg.sender, address(this), pay_amt)); ../../contracts/RubiconRouter.sol::157 => ERC20(toApprove).approve(RubiconMarketAddress, 2**256 - 1); ../../contracts/RubiconRouter.sol::202 => ERC20(route[0]).transferFrom( ../../contracts/RubiconRouter.sol::251 => ERC20(route[route.length - 1]).transfer(to, currentAmount); ../../contracts/RubiconRouter.sol::274 => ERC20(route[0]).transferFrom( ../../contracts/RubiconRouter.sol::303 => ERC20(buy_gem).transfer(msg.sender, fill); ../../contracts/RubiconRouter.sol::320 => ERC20(buy_gem).transfer(msg.sender, fill); ../../contracts/RubiconRouter.sol::348 => ERC20(buy_gem).transfer(msg.sender, buy_amt); ../../contracts/RubiconRouter.sol::356 => msg.sender.transfer(delta); ../../contracts/RubiconRouter.sol::366 => ERC20(pay_gem).transferFrom(msg.sender, address(this), max_fill_amount); //transfer pay here ../../contracts/RubiconRouter.sol::374 => msg.sender.transfer(buy_amt); // Return native ETH ../../contracts/RubiconRouter.sol::377 => ERC20(pay_gem).transfer(msg.sender, max_fill_amount - fill); ../../contracts/RubiconRouter.sol::406 => ERC20(buy_gem).transfer(msg.sender, _after - _before); ../../contracts/RubiconRouter.sol::419 => ERC20(pay_gem).transferFrom(msg.sender, address(this), pay_amt); ../../contracts/RubiconRouter.sol::434 => msg.sender.transfer(delta); ../../contracts/RubiconRouter.sol::451 => msg.sender.transfer(pay_amt); ../../contracts/RubiconRouter.sol::465 => target.approve(targetPool, amount); ../../contracts/RubiconRouter.sol::471 => ERC20(targetPool).transfer(msg.sender, newShares); ../../contracts/RubiconRouter.sol::486 => IBathToken(targetPool).transferFrom(msg.sender, address(this), shares); ../../contracts/RubiconRouter.sol::491 => msg.sender.transfer(withdrawnWETH); ../../contracts/RubiconRouter.sol::531 => ERC20(route[0]).transferFrom( ../../contracts/RubiconRouter.sol::547 => // msg.sender.transfer(fill); ../../contracts/RubiconRouter.sol::548 => msg.sender.transfer(fill);

All Contracts

Tools Used

None

Consider checking amount != 0.

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

../../contracts/RubiconRouter.sol::82 => uint256 lastBid = 0; ../../contracts/RubiconRouter.sol::83 => uint256 lastAsk = 0; ../../contracts/RubiconRouter.sol::85 => for (uint256 index = 0; index < topNOrders; index++) { ../../contracts/RubiconRouter.sol::168 => uint256 currentAmount = 0; ../../contracts/RubiconRouter.sol::169 => for (uint256 i = 0; i < route.length - 1; i++) { ../../contracts/RubiconRouter.sol::226 => uint256 currentAmount = 0; ../../contracts/RubiconRouter.sol::227 => for (uint256 i = 0; i < route.length - 1; i++) { ../../contracts/rubiconPools/BathPair.sol::310 => bool assigned = false; ../../contracts/rubiconPools/BathPair.sol::311 => for (uint256 index = 0; index < array.length; index++) { ../../contracts/rubiconPools/BathPair.sol::427 => for (uint256 index = 0; index < quantity; index++) { ../../contracts/rubiconPools/BathPair.sol::480 => for (uint256 index = 0; index < quantity; index++) { ../../contracts/rubiconPools/BathPair.sol::582 => for (uint256 index = 0; index < ids.length; index++) { ../../contracts/rubiconPools/BathToken.sol::635 => for (uint256 index = 0; index < bonusTokens.length; index++) {

Tools Used

Code Review

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

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

All Contracts

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/

Solidity 0.8.13 has some improvements too but not well tested.

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

Consider to upgrade pragma to at least 0.8.10.

C4-006 : ++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/RubiconRouter.sol::82 => uint256 lastBid = 0; ../../contracts/RubiconRouter.sol::83 => uint256 lastAsk = 0; ../../contracts/RubiconRouter.sol::85 => for (uint256 index = 0; index < topNOrders; index++) { ../../contracts/RubiconRouter.sol::168 => uint256 currentAmount = 0; ../../contracts/RubiconRouter.sol::169 => for (uint256 i = 0; i < route.length - 1; i++) { ../../contracts/RubiconRouter.sol::226 => uint256 currentAmount = 0; ../../contracts/RubiconRouter.sol::227 => for (uint256 i = 0; i < route.length - 1; i++) { ../../contracts/rubiconPools/BathPair.sol::310 => bool assigned = false; ../../contracts/rubiconPools/BathPair.sol::311 => for (uint256 index = 0; index < array.length; index++) { ../../contracts/rubiconPools/BathPair.sol::427 => for (uint256 index = 0; index < quantity; index++) { ../../contracts/rubiconPools/BathPair.sol::480 => for (uint256 index = 0; index < quantity; index++) { ../../contracts/rubiconPools/BathPair.sol::582 => for (uint256 index = 0; index < ids.length; index++) { ../../contracts/rubiconPools/BathToken.sol::635 => for (uint256 index = 0; index < bonusTokens.length; index++) {

Tools Used

Code Review

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

C4-007 : 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/rubiconPools/BathPair.sol::277 => current[target] = current[current.length - 1]; ../../contracts/rubiconPools/BathPair.sol::311 => for (uint256 index = 0; index < array.length; index++) { ../../contracts/rubiconPools/BathPair.sol::420 => askNumerators.length == askDenominators.length && ../../contracts/rubiconPools/BathPair.sol::421 => askDenominators.length == bidNumerators.length && ../../contracts/rubiconPools/BathPair.sol::422 => bidNumerators.length == bidDenominators.length, ../../contracts/rubiconPools/BathPair.sol::423 => "not all order lengths match" ../../contracts/rubiconPools/BathPair.sol::425 => uint256 quantity = askNumerators.length; ../../contracts/rubiconPools/BathPair.sol::472 => askNumerators.length == askDenominators.length && ../../contracts/rubiconPools/BathPair.sol::473 => askDenominators.length == bidNumerators.length && ../../contracts/rubiconPools/BathPair.sol::474 => bidNumerators.length == bidDenominators.length &&

Tools Used

Code Review

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-008 : 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/rubiconPools/BathHouse.sol::111 => require(_reserveRatio > 0); ../../contracts/rubiconPools/BathHouse.sol::281 => require(rr > 0); ../../contracts/rubiconPools/BathPair.sol::231 => // if delta > 0 - delta is fill => handle any amount of fill here ../../contracts/rubiconPools/BathPair.sol::232 => if (askDelta > 0) { ../../contracts/rubiconPools/BathPair.sol::251 => // if delta > 0 - delta is fill => handle any amount of fill here ../../contracts/rubiconPools/BathPair.sol::252 => if (bidDelta > 0) { ../../contracts/rubiconPools/BathPair.sol::333 => (askNumerator > 0 && askDenominator > 0) || ../../contracts/rubiconPools/BathPair.sol::334 => (bidNumerator > 0 && bidDenominator > 0), ../../contracts/rubiconPools/BathPair.sol::515 => if (assetRebalAmt > 0) { ../../contracts/rubiconPools/BathPair.sol::523 => if (quoteRebalAmt > 0) { ../../contracts/rubiconPools/BathPair.sol::597 => if (fillCountA > 0) { ../../contracts/rubiconPools/BathPair.sol::611 => if (fillCountQ > 0) {

Tools Used

Code Review

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

C4-009 : 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 to replace revert strings with custom errors.

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

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

C4-011 : 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/RubiconRouter.sol::82 => uint256 lastBid = 0; ../../contracts/RubiconRouter.sol::83 => uint256 lastAsk = 0; ../../contracts/RubiconRouter.sol::85 => for (uint256 index = 0; index < topNOrders; index++) { ../../contracts/RubiconRouter.sol::168 => uint256 currentAmount = 0; ../../contracts/RubiconRouter.sol::169 => for (uint256 i = 0; i < route.length - 1; i++) { ../../contracts/RubiconRouter.sol::226 => uint256 currentAmount = 0; ../../contracts/RubiconRouter.sol::227 => for (uint256 i = 0; i < route.length - 1; i++) { ../../contracts/rubiconPools/BathPair.sol::310 => bool assigned = false; ../../contracts/rubiconPools/BathPair.sol::311 => for (uint256 index = 0; index < array.length; index++) { ../../contracts/rubiconPools/BathPair.sol::427 => for (uint256 index = 0; index < quantity; index++) { ../../contracts/rubiconPools/BathPair.sol::480 => for (uint256 index = 0; index < quantity; index++) { ../../contracts/rubiconPools/BathPair.sol::582 => for (uint256 index = 0; index < ids.length; index++) { ../../contracts/rubiconPools/BathToken.sol::635 => for (uint256 index = 0; index < bonusTokens.length; index++) {

Tools Used

None

Consider to cache array length.

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

Proof of Concept

  1. Navigate to the following smart contract line.
https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/RubiconRouter.sol#L21

Tools Used

None

Consider using immutable variable.

C4-013 : 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/rubiconPools/BathPair.sol:214: StrategistTrade memory info = strategistTrades[id]; contracts/rubiconPools/BathPair.sol:224: order memory offer1 = getOfferInfo(info.askId); //ask contracts/rubiconPools/BathPair.sol:225: order memory offer2 = getOfferInfo(info.bidId); //bid contracts/rubiconPools/BathPair.sol:292: function getOfferInfo(uint256 id) internal view returns (order memory) { contracts/rubiconPools/BathPair.sol:299: order memory offerInfo = order(ask_amt, ask_gem, bid_amt, bid_gem); contracts/rubiconPools/BathPair.sol:325: address[2] memory tokenPair, // ASSET, Then Quote contracts/rubiconPools/BathPair.sol:352: order memory ask = order( contracts/rubiconPools/BathPair.sol:358: order memory bid = order( contracts/rubiconPools/BathPair.sol:382: StrategistTrade memory outgoing = StrategistTrade( contracts/rubiconPools/BathPair.sol:413: address[2] memory tokenPair, // ASSET, Then Quote contracts/rubiconPools/BathPair.sol:414: uint256[] memory askNumerators, // Quote / Asset contracts/rubiconPools/BathPair.sol:415: uint256[] memory askDenominators, // Asset / Quote contracts/rubiconPools/BathPair.sol:416: uint256[] memory bidNumerators, // size in ASSET contracts/rubiconPools/BathPair.sol:417: uint256[] memory bidDenominators // size in QUOTES contracts/rubiconPools/BathPair.sol:442: address[2] memory tokenPair, // ASSET, Then Quote contracts/rubiconPools/BathPair.sol:464: uint256[] memory ids, contracts/rubiconPools/BathPair.sol:465: address[2] memory tokenPair, // ASSET, Then Quote contracts/rubiconPools/BathPair.sol:466: uint256[] memory askNumerators, // Quote / Asset contracts/rubiconPools/BathPair.sol:467: uint256[] memory askDenominators, // Asset / Quote contracts/rubiconPools/BathPair.sol:468: uint256[] memory bidNumerators, // size in ASSET contracts/rubiconPools/BathPair.sol:469: uint256[] memory bidDenominators // size in QUOTES contracts/rubiconPools/BathPair.sol:578: function scrubStrategistTrades(uint256[] memory ids) contracts/rubiconPools/BathPair.sol:635: ) public view returns (uint256[] memory) { contracts/rubiconPools/BathToken.sol:187: string memory _symbol = string( contracts/rubiconPools/BathHouse.sol:416: bytes memory _initData = abi.encodeWithSignature( contracts/RubiconMarket.sol:250: OfferInfo memory _offer = offers[id]; contracts/RubiconMarket.sol:279: OfferInfo memory _offer = offers[id]; contracts/RubiconMarket.sol:358: OfferInfo memory _offer = offers[id]; contracts/RubiconMarket.sol:406: OfferInfo memory info;

Tools Used

None

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

AuditHub

A portfolio for auditors, a security profile for protocols, a hub for web3 security.

Built bymalatrax © 2024

Auditors

Browse

Contests

Browse

Get in touch

ContactTwitter