Badger Citadel contest - ilan's results

Bringing BTC to DeFi

General Information

Platform: Code4rena

Start Date: 14/04/2022

Pot Size: $75,000 USDC

Total HM: 8

Participants: 72

Period: 7 days

Judge: Jack the Pug

Total Solo HM: 2

Id: 110

League: ETH

BadgerDAO

Findings Distribution

Researcher Performance

Rank: 32/72

Findings: 2

Award: $258.84

🌟 Selected for report: 0

🚀 Solo Findings: 0

L01: funding.sol: setCitadelAssetPriceBounds does not check that the bounds are valid with the current CitadelAssetPrice

Calling setCitadelAssetPriceBounds with _minPrice, _maxPrice where citadelPriceInAsset is not in that range should not be allowed. This can result in a weird state, even though it will not cause a severe vulnerability.

Proof Of Concept

https://github.com/code-423n4/2022-04-badger-citadel/blob/18f8c392b6fc303fe95602eba6303725023e53da/src/Funding.sol#L356

Add require(citadelPriceInAsset >= _minPrice && citadelPriceInAsset <= _maxPrice) to the function

L02 StakedCitadelVester.vest does not check that _unlockBegin is valid.

https://github.com/code-423n4/2022-04-badger-citadel/blob/18f8c392b6fc303fe95602eba6303725023e53da/src/StakedCitadelVester.sol#L132

If an invalid _unlockBegin is given such that _unlockBegin + vestingDuration < block.timestamp then the user will be able to claim vestingToken straight away.

require(_unlockBegin >= block.timestamp)

L03: missing zero address check in functions

Functions in some of the contracts are missing checks that address != 0. Using such addresses can brake the protocol.

StakedCitadelLocker.addReward StakedCitadelLocker.approveRewardDistributor StakedCitadelLocker.setStakingContract StakedCitadelVester.vest Funding.setDiscountManager

require(_var_name != address(0), "address 0 invalid");

NC01: KnightingRound.sol: should check tokenInLimit > 0

should require tokenInLimit > 0, when tokenInLimit = 0 the knigting round isn't functional.

add require(_tokenInLimit > 0) in initialize and setTokenInLimit

NC02: StakedCitadel._calculateFee unecessary if (feeBps == 0)

https://github.com/code-423n4/2022-04-badger-citadel/blob/18f8c392b6fc303fe95602eba6303725023e53da/src/StakedCitadel.sol#L844

if feeBps = 0 then (amount * feeBps) / MAX_BPS; will be 0 anyway, no need for the if statement

NC03: StakedCitadelVester.claim, use require(amount != 0) instead of if (amount != 0)

If there is no claimable balance or the requested amount is 0, then claim should fail on a require. replace if (amount != 0) with require(amount != 0, "error msg")

https://github.com/code-423n4/2022-04-badger-citadel/blob/18f8c392b6fc303fe95602eba6303725023e53da/src/StakedCitadelVester.sol#L90

NC04: Missing documentation

Many functions and complex logic are missing informative documentation and comments.

CitadelMinter.getFundingPoolWeights CitadelMinter.initializeLastMintTimestamp CitadelMinter._transferToFundingPools CitadelMinter._removeFundingPool CitadelMinter._addFundingPool Funding.clearCitadelPriceFlag Funding.setSaleRecipient Funding.setCitadelAssetPriceBounds StakedCitadelVester.initialize SupplySchedule.initialize SupplySchedule.getCurrentEpoch SupplySchedule.getEmissionsForEpoch SupplySchedule.getEmissionsForCurrentEpoch SupplySchedule.getMintable SupplySchedule.setMintingStart SupplySchedule.setEpochRate

NC05: StakedCitadel.ONE_ETH visibility should be explicit

default visibility is internal however it is good practice to specify it explicitly. change ONE_ETH to

uint256 internal constant ONE_ETH = 1e18;

NC06: StakedCitadel._withdraw: calling with shares > 0, totalSupply() = 0, will cause zero division error

trying to withdraw while the total supply of the token is 0, will cause a zero division error. Instead should add require(totalSupply() != 0), "msg" with an informative message, to make the error clear to the caller.

https://github.com/code-423n4/2022-04-badger-citadel/blob/18f8c392b6fc303fe95602eba6303725023e53da/src/StakedCitadel.sol#L811

NC07: Funding.sweep: emit after transfer

It is good practice and more readable to emit at the end.

https://github.com/code-423n4/2022-04-badger-citadel/blob/18f8c392b6fc303fe95602eba6303725023e53da/src/Funding.sol#L328-L329

NC08: SupplySchedule.getEpochAtTimestamp wrong documentation,

// @dev duplicate of getMintable() with debug print added // @dev this function is out of scope for reviews and audits

this comment is meant for getMintableDebug and not for getEpochAtTimestamp. Can be confusing while reading the code.

https://github.com/code-423n4/2022-04-badger-citadel/blob/18f8c392b6fc303fe95602eba6303725023e53da/src/SupplySchedule.sol#L52

NC09: SupplySchedule.getEmissionsForEpoch should check that _epoch is valid

require that the _epoch is valid and has a rate, this is better than returning 0.

change getEmissionsForEpoch to:

rate = epochRate[_epoch]; require(rate > 0, "invalid epoch"); return rate * epochLength;

NC10: simplify logic in CitadelMinter.setFundingPoolWeight

this logic:

uint256 _newTotalWeight = totalFundingPoolWeight; _newTotalWeight = _newTotalWeight - fundingPoolWeights[_pool]; fundingPoolWeights[_pool] = _weight; _newTotalWeight = _newTotalWeight + _weight; totalFundingPoolWeight = _newTotalWeight; emit FundingPoolWeightSet(_pool, _weight, _newTotalWeight);

is unecessarily complex, can simplify to:

totalFundingPoolWeight = totalFundingPoolWeight - fundingPoolWeights[_pool] + _weight; fundingPoolWeights[_pool] = _weight; emit FundingPoolWeightSet(_pool, _weight, totalFundingPoolWeight)

This is much more readable and saves gas.

NC11: Add error message to require in StakedCitadelLocker.sol

Most require statements in this contract are missing an error message. One should be added.

Example: require(_stakingToken != address(0)) -> require(_stakingToken != address(0), "zero adress")

NC12: Funding.sol: use unit256 consistantly , replace unit

use uint256 or unit consistently, preferably uint256

funding.sol 224

funding.sol 419

NC13: a += b rather than a = a + b

a += b is cleaner than a = a + b.

Example:

totalTokenIn = totalTokenIn + _tokenInAmount; -> totalTokenIn += _tokenInAmount;

example in repo

Gas Optimization Report

Make if statement inclusive

if (amount > claimable) -> if (amount >= claimable)

making the inequality strinct can save gas

https://github.com/code-423n4/2022-04-badger-citadel/blob/18f8c392b6fc303fe95602eba6303725023e53da/src/StakedCitadelVester.sol#L87

Use saleEnd instead of saleDuration to avoid calulating saleStart + saleDuration repeatadly

the only use of saleDuration is in the calculations of saleStart + saleDuration. Hence, it will save gas to just save in storage the sale end instead of saleDuration. Update the initializer and function setSaleDuration accordingly

https://github.com/code-423n4/2022-04-badger-citadel/blob/18f8c392b6fc303fe95602eba6303725023e53da/src/KnightingRound.sol#L36

cache vesting[recipient]

StakedCitadelVester.claimableBalance, cache vesting[recipient]. Can save 5 storage calls.

function claimableBalance(address recipient) public view returns (uint256) { uint256 locked = vesting[recipient].lockedAmounts; uint256 claimed = vesting[recipient].claimedAmounts; if (block.timestamp >= vesting[recipient].unlockEnd) { return locked - claimed; } return ((locked * (block.timestamp - vesting[recipient].unlockBegin)) / (vesting[recipient].unlockEnd - vesting[recipient].unlockBegin)) - claimed; }

https://github.com/code-423n4/2022-04-badger-citadel/blob/18f8c392b6fc303fe95602eba6303725023e53da/src/StakedCitadelVester.sol#L108

StakedCitadel._withdraw, calling token.balanceOf(address(this)) twice.

takedCitadel._withdraw calls balance() and then token.balanceOf(address(this)), which do exactly the same and will return the same.

Instead, call uint256 b = balance(); after the require, then use b for the 2 usages, here and here

uint256 r = (balance() * _shares) / totalSupply(); _burn(msg.sender, _shares); // Check balance uint256 b = token.balanceOf(address(this));

->

uint256 b = balance(); uint256 r = (b * _shares) / totalSupply(); _burn(msg.sender, _shares);

Upgrade pragma to at least 0.8.4 for StakedCitadelLocker.sol, MedianOracle.sol

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.

https://github.com/Citadel-DAO/staked-citadel-locker/blob/efc27b442fd4089369e4d2df163f82c35aa81537/src/StakedCitadelLocker.sol#L2

https://github.com/ampleforth/market-oracle/blob/5e7fd1506784f074748ab6bd5df740ca2227b14f/contracts/MedianOracle.sol#L1

General Gas Saving Good Practices

Change i++ to ++i

i++ is generally more expensive because it must increment a value and return the old value, so it may require holding two numbers in memory. ++i only uses one number in memory.

Example:

for (uint256 i = 0; i < numPools; i++) -> for (uint256 i = 0; i < numPools ++i)

Use calldata

Use calldata instead of memory for external functions where the function argument is read-only. Reading directly from calldata using calldataload instead of going via memory saves the gas from the intermediate memory operations that carry the values.

No need to explicitly initialize variables with default values

If a variable is not initialized it is automatically set to the default value (0 for uint, false for bool, address(0) for address...). Explicitly initializing it with its default value is an anti-pattern and wastes gas.

Contracts: CitadelMinter.sol StakedCitadelLocker.sol SupplySchedule.sol

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