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
Rank: 54/99
Findings: 4
Award: $93.83
🌟 Selected for report: 0
🚀 Solo Findings: 0
🌟 Selected for report: berndartmueller
Also found by: 0x1f8b, 0xDjango, 0xsomeone, ACai, Bahurum, BouSalman, CertoraInc, Deivitto, Dravee, GimelSec, IllIllI, JMukesh, Kaiziron, PP1004, Ruhum, SmartSek, VAD37, WatchPug, _Adam, aez121, antonttc, blockdev, broccolirob, camden, cccz, cryptphi, defsec, dipp, ellahi, fatherOfBlocks, gzeon, horsefacts, ilan, jayjonah8, joestakey, kenta, kenzo, minhquanym, oyc_109, pauliax, pedroais, peritoflores, sashik_eth, shenwilly, simon135, throttle, xiaoming90, z3s
0.1022 USDC - $0.10
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
🌟 Selected for report: Ruhum
Also found by: 0x1f8b, 0x4non, 0xDjango, Dravee, GimelSec, StErMi, berndartmueller, blackscale, catchup, cccz, csanuragjain, defsec, eccentricexit, ellahi, horsefacts, hubble, joestakey, kenzo, pedroais, peritoflores, reassor, rotcivegaf, sashik_eth, shenwilly, sseefried, throttle, xiaoming90
1.8534 USDC - $1.85
https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/RubiconMarket.sol#L1232
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.
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
🌟 Selected for report: IllIllI
Also found by: 0x1337, 0x1f8b, 0x4non, 0xDjango, 0xKitsune, 0xNazgul, 0xf15ers, ACai, AlleyCat, Bahurum, BouSalman, CertoraInc, Chom, Dravee, ElKu, FSchmoede, Funen, GimelSec, Hawkeye, JC, JMukesh, Kaiziron, MaratCerby, Metatron, PP1004, Picodes, Ruhum, SmartSek, StErMi, TerrierLover, UVvirus, UnusualTurtle, WatchPug, Waze, _Adam, asutorufos, berndartmueller, blackscale, blockdev, broccolirob, c3phas, catchup, cryptphi, csanuragjain, defsec, delfin454000, dipp, eccentricexit, ellahi, fatherOfBlocks, gzeon, hansfriese, horsefacts, hubble, ilan, joestakey, kebabsec, minhquanym, oyc_109, parashar, pauliax, rotcivegaf, sach1r0, sashik_eth, shenwilly, simon135, sorrynotsorry, sseefried, throttle, unforgiven, xiaoming90
53.5592 USDC - $53.56
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
Navigate to the following contract.
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) {
Code Review
Consider using safeTransfer/safeTransferFrom or require() consistently.
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.
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)",
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.
Missing checks for zero-addresses may lead to infunctional protocol, if the variable addresses are updated incorrectly.
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
Code Review
Consider adding zero-address checks in the discussed constructors: require(newAddr != address(0));.
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.
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/)
None
Add events to all functions that change critical parameters.
The critical procedures should be two step process.
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
Code Review
Lack of two-step procedure for critical operations leaves them error-prone. Consider adding two step procedure on the critical functions.
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.
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;
Manual code review
Upgrade pragma solidity 0.8.10.
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.
https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/RubiconMarket.sol#L22
Code Review
Lack of two-step procedure for critical operations leaves them error-prone. Consider adding two step procedure on the critical functions.
The re-entrancy guard is missing on the some of the functions. The external interactions can cause to the re-entrancy vulnerability.
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
Code Review
Follow the check effect interaction pattern or put re-entrancy guard.
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)
All Market Functions
Code Review
Pause functionality on the contract would have helped secure the funds quickly.
🌟 Selected for report: IllIllI
Also found by: 0x1f8b, 0x4non, 0xDjango, 0xNazgul, 0xf15ers, 0xkatana, Chom, DavidGialdi, Dravee, ElKu, FSchmoede, Fitraldys, Funen, GimelSec, JC, Kaiziron, MaratCerby, Metatron, MiloTruck, Picodes, Randyyy, RoiEvenHaim, SmartSek, Tomio, UnusualTurtle, WatchPug, Waze, _Adam, antonttc, asutorufos, berndartmueller, blackscale, blockdev, c3phas, catchup, csanuragjain, defsec, delfin454000, ellahi, fatherOfBlocks, gzeon, hansfriese, ilan, joestakey, minhquanym, oyc_109, pauliax, pedroais, reassor, rfa, rotcivegaf, sach1r0, samruna, sashik_eth, simon135, z3s
38.3159 USDC - $38.32
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.
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");
Manual Review
Shorten the revert strings to fit in 32 bytes. That will affect gas optimization.
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.
../../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++) {
None
Consider applying unchecked arithmetic where overflow/underflow is not possible. Example can be seen from below.
Unchecked{i++};
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.
../../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
None
Consider checking amount != 0.
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.
../../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++) {
Code Review
uint x = 0 costs more gas than uint x without having any different functionality.
Using newer compiler versions and the optimizer gives gas optimizations and additional safety checks are available for free.
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
None
Consider to upgrade pragma to at least 0.8.10.
++i is more gas efficient than i++ in loops forwarding.
../../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++) {
Code Review
It is recommend to use unchecked{++i} and change i declaration to uint256.
Using double require instead of operator && can save more gas.
../../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 &&
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
Strict inequalities add a check of non equality which costs around 3 gas.
../../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) {
Code Review
Use >= or <= instead of > and < when possible.
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
Code Review
Recommended to replace revert strings with custom errors.
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.
Contracts
None
A division/multiplication by any number x being a power of 2 can be calculated by shifting log2(x) to the right/left.
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.
../../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++) {
None
Consider to cache array length.
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.
https://github.com/code-423n4/2022-05-rubicon/blob/main/contracts/RubiconRouter.sol#L21
None
Consider using immutable variable.
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.
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;
None
Some parameters in examples given above are later hashed. It may be beneficial for those parameters to be in memory rather than calldata.