Platform: Code4rena
Start Date: 15/03/2024
Pot Size: $60,500 USDC
Total HM: 16
Participants: 43
Period: 21 days
Judge: hansfriese
Total Solo HM: 5
Id: 348
League: ETH
Rank: 20/43
Findings: 1
Award: $236.67
🌟 Selected for report: 0
🚀 Solo Findings: 0
🌟 Selected for report: popeye
Also found by: 0xbrett8571, JcFichtner, LinKenji, Rhaydden, SAQ, Sathish9098, albahaca, clara, emerald7017, fouzantanveer, foxb868, hunter_w3b, kaveyjoe, roguereggiant
236.6726 USDC - $236.67
This protocol introduces a distinctive approach where bidders and shorters provide ETH, with bidders receiving dUSD while shorters are compensated with the bidders' collateral along with a ShortRecord. This ShortRecord enables shorters to manage their debt position akin to a Collateralized Debt Position (CDP) but with an innovative twist; the collateral and the LST yield go to the shorter, not the asset. This novel structure not only enhances liquidity and financial flexibility but also aligns with Ethereum's decentralization ethos, providing a robust, user-centric financial instrument for the DeFi ecosystem.
Name | Description |
---|---|
BidOrdersFacet.sol | This code defines the BidOrdersFacet contract for creating bid orders within a decentralized finance platform, facilitating market and forced bids with a focus on optimizing gas usage through sorted placements and short matching. It incorporates libraries for mathematical operations, data types, and system-specific logic to manage bids, including updates based on oracle prices and complex bid matching algorithms. |
ShortOrdersFacet.sol | This code introduces a component focused on creating limit short orders in a market system, emphasizing the exclusive use of limit orders for shorts, with specific parameters for market impact, price, and amount, alongside optimization features for market placement. |
PrimaryLiquidationFacet.sol | This code outlines a system for executing primary liquidations within a financial market, focusing on enforcing collateral requirements and mitigating undercollateralized positions through forced market bids, alongside managing associated fees and adjustments to ensure market stability and participant incentives. |
BridgeRouterFacet.sol | This code defines a contract that manages interactions with Ethereum and staked Ethereum bridges, allowing users to deposit and withdraw liquid staking tokens (LST) or Ethereum in exchange for an equivalent value in protocol-specific tokens, aiming to facilitate seamless liquidity movements and yield generation within a decentralized finance ecosystem. |
ExitShortFacet.sol | This code defines a contract for managing short positions in a trading platform, allowing users to exit their shorts by directly repaying their debt with assets from their wallet or escrowed balance, or by placing a bid in the market to buy back the required amount. It supports partial exits, ensuring users can adjust their positions according to market conditions or their strategy. |
RedemptionFacet.sol | This contract facilitates the redemption of short positions in a trading platform. It allows users to propose redemptions of undercollateralized short positions, subject to a dispute period, during which other users can challenge the proposed redemptions if they find inaccuracies. Successful redemptions adjust the short positions accordingly, and the redeemer's collateral is updated based on the outcome. |
LibBridgeRouter.sol | This library manages the interaction between users and different bridges in a decentralized finance platform, handling the credit and debit of digital assets during deposits and withdrawals. It includes functionality to assess bridge credits, calculate withdrawal fees based on market conditions, and adjust user and vault balances accordingly. |
LibBytes.sol | This library provides functionality to decode and read proposal data for redemption candidates from on-chain storage. It extracts and structures this data into an easily accessible format, focusing specifically on proposals stored using the SSTORE2 contract, which offers optimized storage solutions. |
LibOracle.sol | This library manages oracle interactions for obtaining and validating asset prices, employing circuit breakers for data reliability and handling deviations in fetched prices. It supports functionality to retrieve prices from both Chainlink oracles and a TWAP (Time-Weighted Average Price) mechanism, ensuring accurate and secure price data for the protocol. |
LibOrders.sol | This library orchestrates order management for a decentralized trading platform, providing functions for creating, matching, and canceling limit and market orders, including bids, asks, and shorts. It integrates price verification and updates through oracle checks, manages order queues efficiently using hints for optimized search, and implements complex match-making logic to ensure trades are executed fairly and efficiently within the platform's ecosystem. |
LibSRUtil.sol | This library provides utility functions for handling operations related to short records within a financial trading system. It manages collateral disbursement, checks for minimum ERC debt requirements, facilitates short record transfers, and updates debt based on changing market conditions, ensuring the integrity and proper functioning of short-related transactions. |
UniswapOracleLibrary.sol | This library provides functionality to interact with Uniswap V3's pool oracle, offering methods to calculate token exchange amounts based on pool ticks and to estimate time-weighted average prices (TWAP) using the pool's historical data. It aims to facilitate more accurate and decentralized price quotations within smart contracts. |
The system is designed to facilitate market orders, including limit orders for buying and selling assets, creating short orders, liquidating shorts, and handling the redemption of assets in a decentralized finance (DeFi) environment. It heavily relies on smart contracts for managing orders, assets, vaults, and price oracles. Key features include:
The system is structured around smart contracts that manage the lifecycle of orders and shorts within a DeFi ecosystem. Users interact with these contracts to perform actions such as creating, matching, or canceling orders, as well as managing shorts through creation, liquidation, and redemption processes. Price data is crucial for many operations, fetched from external oracles like Chainlink or Uniswap V3 to determine accurate market prices for assets.
Vaults play a central role in managing user assets, ensuring secure storage, and handling yield distributions. The bridge integration allows for asset deposits and withdrawals across different blockchains, with mechanisms to manage bridge credits and mitigate arbitrage risks.
Overall, the system facilitates a comprehensive DeFi trading and asset management environment, integrating with external services for price data and cross-chain interactions while maintaining a focus on security and user asset management.
Here's an overall sequence diagram depicting the interaction flow within the system based on the provided Solidity code snippets. The diagram follows a typical flow where a user interacts with the system to place orders, manage shorts, and interact with the vault and oracle systems.
Order Handling: Users initiate orders (create, match, cancel) that interact with the order handling contract. This contract may request price data from an oracle and updates the user's balances or order statuses within the vault.
Short Orders: Users can create or exit short positions through the Short Orders contract, which also relies on price data from oracles and interacts with the vault for updates.
Liquidation: Users can liquidate short positions, necessitating price data and vault interactions to process and confirm the liquidation.
Redemption: The redemption process allows users to submit candidates for redemption, potentially disputed, and finally claim redemption, involving price data requests and vault updates.
Bridge Integration: Users can deposit or withdraw assets through the Bridge Integration, which communicates with external bridges and updates the vault accordingly.
This sequence diagram provides a high-level overview of the system's interaction flow, highlighting the dependencies on price oracles and vault management for various user-initiated actions.
This smart contract is designed for handling bid orders within a decentralized finance (DeFi) trading platform. It includes functionalities for creating bid orders, matching these orders against asks or shorts, and managing the order flow based on market conditions and oracle price data.
createBid
asset
: The market for the bid.price
: The price per ERC token in ETH.ercAmount
: The amount of ERC tokens to purchase.isMarketOrder
: Specifies if the order is a market (true) or limit (false) order.orderHintArray
: Array of hint IDs for optimized order placement.shortHintArray
: Array of hint IDs for optimized matching with shorts.createForcedBid
createBid
but is only callable by specific contracts.sender
: The address initiating the bid order.asset
, price
, ercAmount
, shortHintArray
: Similar to createBid
.createBid
, the amounts of ETH filled and ERC left._createBid
createBid
and createForcedBid
.bidMatchAlgo
asset
: The market for the bid.incomingBid
: The bid order to match.orderHintArray
: Optimizes order placement.b
: A memory struct containing matching algorithm parameters.matchlowestSell
matchIncomingBid
_getLowestSell
: Determines the lowest sell order available for matching._shortDirectionHandler
: Manages the directional flow of short order matching based on the bid price and oracle data._createBid
, bidMatchAlgo
, and others interact closely with various libraries (LibAsset
, LibOracle
, LibOrders
, LibShortRecord
) for price data, order handling, and vault management.This contract integrates complex DeFi trading mechanisms, such as market and limit bids, short selling, and automatic order matching. It leverages price oracles for accurate market data and implements gas optimization strategies through order hints. The contract is designed to maintain a secure and efficient trading environment, with safeguards like non-reentrancy checks and asset validation.
This smart contract facilitates the creation of limit short orders within a trading system, specifically tailored for assets traded on a decentralized finance (DeFi) platform.
createLimitShort
Purpose: Allows users to open short positions on a given asset by specifying the price, amount, and initial collateral ratio. This function is designed exclusively for limit shorts.
Parameters:
asset
: The specific market or asset on which the short is being placed.price
: The price at which the user wishes to sell the ERC token, denominated in ETH.ercAmount
: The quantity of the ERC token the user wishes to sell short.orderHintArray
: An array of order hints used for gas optimization during order placement.shortHintArray
: An array of short hints for optimizing matching with shorts above the oracle price.shortOrderCR
: The initial Collateral Ratio (CR) for the short order, converted to a uint16 value for the function input.Logic Flow:
Key Interactions:
LibOrders
, LibAsset
, LibOracle
, LibShortRecord
, LibSRUtil
) to handle order matching, asset validation, oracle price fetching, short record management, and system rule enforcement.This contract is a critical component of the DeFi platform's trading mechanism, enabling users to speculate on price movements by selling assets short. It integrates with the platform's broader financial and operational rulesets, including collateral management, order matching algorithms, and market conditions monitoring, to facilitate secure and efficient trading activities.
This contract enables the liquidation of undercollateralized short positions within a DeFi platform. It is designed to maintain the financial stability of the platform by ensuring all positions are properly collateralized.
PrimaryLiquidationFacet
_dusd
: Address of the platform's stablecoin.liquidate
asset
: The asset being shorted that is subject to liquidation.shorter
: The address of the account holding the short position.id
: The identifier of the short position.shortHintArray
: An array of hints to optimize the matching process for the forced bid.shortOrderId
: The order ID of the short position.gasFee
: The estimated cost of gas incurred by the liquidation process, intended to be partially reimbursed.ethFilled
: The amount of ETH filled during the forced bid process._checklowestSell
: Ensures there are eligible sell orders for liquidation and that prices are within a certain buffer of the oracle price._setLiquidationStruct
: Initializes and returns a struct containing all necessary information for the liquidation process._performForcedBid
: Executes the forced bid on behalf of the short holder, adjusting collateral and debt as needed._liquidationFeeHandler
: Calculates and distributes fees associated with the liquidation._fullorPartialLiquidation
: Determines whether the short position can be partially or fully liquidated based on the outcome of the forced bid.This contract plays a critical role in the risk management framework of the DeFi platform, allowing for the orderly liquidation of positions that fall below required collateralization levels, thereby protecting both the platform and its users from undue financial risk.
This contract facilitates interactions between users and bridge protocols, allowing the deposit and withdrawal of assets across different blockchains or layers within a decentralized finance (DeFi) ecosystem.
BridgeRouterFacet
_rethBridge
and _stethBridge
denote the addresses for RETH and STETH bridge contracts, respectively.getDethTotal
vault
identifies the vault for which the total is requested.getBridges
vault
specifies the vault in question.deposit
bridge
(the bridge through which the deposit is made), and amount
(the quantity of LST being deposited).depositEth
bridge
signifies the bridge to be used for the ETH deposit.withdraw
bridge
(the bridge through which the withdrawal occurs), and dethAmount
(the amount of dETH to be converted and withdrawn).withdrawTapp
bridge
(identifying the bridge for withdrawal) and dethAmount
(the dETH quantity to be withdrawn).maybeUpdateYield
vault
denotes the vault being assessed, and amount
specifies the deposit size._getVault
bridge
specifies the bridge in question.vault
(the vault ID associated with the bridge) and bridgePointer
(a numerical representation for the bridge within the vault)._ethConversion
vault
(the vault ID) and amount
(the dETH quantity).This contract plays a crucial role in bridging assets between different ecosystems, providing liquidity and facilitating cross-chain or layer transactions within the DeFi space. It ensures that assets can move seamlessly across bridges, enhancing interoperability and accessibility for users.
This contract provides mechanisms for users to exit their short positions in various ways, including using assets from their wallet, assets held in escrow, or by placing bids on the market.
ExitShortFacet
exitShortWallet
exitShortErcEscrowed
exitShort
getCollateralRatioNonPrice
Each function within this contract is designed to offer flexibility in managing short positions, allowing users to close their positions based on their preferred method of settlement, whether that's directly from their wallet, using escrowed assets, or through market transactions. The contract also includes safeguards such as checking for valid short records and ensuring that the operations do not result in adverse conditions like insufficient collateral.
This contract facilitates the redemption process, allowing users to propose redemptions of short records, challenge proposed redemptions, and claim redeemed collateral.
validRedemptionSR
proposeRedemption
disputeRedemption
claimRedemption
claimRemainingCollateral
_claimRemainingCollateral
calculateRedemptionFee
This contract integrates with several other components, including asset and short record management, to ensure a controlled and fair process for redeeming short positions within the system. It includes mechanisms for proposing redemptions, disputing proposals, and claiming collateral, all while managing fees and ensuring that transactions comply with the platform's rules.
This library facilitates interactions related to bridge transactions within a decentralized finance protocol. It includes functions for adding and withdrawing digital assets through bridge contracts, assessing bridge credits, calculating withdrawal fees based on market conditions, and managing bridge credit transfers.
addDeth
assessDeth
withdrawalFeePct
transferBridgeCredit
removeDeth
This library integrates with various parts of the protocol, leveraging bridge contracts to facilitate cross-chain or cross-layer transactions, manage user credits, and ensure proper accounting of digital assets within the ecosystem.
This library provides functionalities to decode and interpret byte-encoded data specifically tailored for handling proposal data related to redemption operations in a decentralized finance (DeFi) protocol.
readProposalData
ProposalData
structures.SSTORE2Pointer
: The address pointer provided by SSTORE2 where the byte-encoded proposal data is stored.slateLength
: The number of ProposalData
entries encoded in the byte array. This is used to initialize the array of ProposalData
structures to be returned.ProposalData
structure. This process involves interpreting slices of the byte array as specific data types (e.g., address
, uint8
, uint64
, uint88
) and assigning them to the corresponding fields in a ProposalData
structure.shorter
(address), shortId
(uint8), CR
(uint64), ercDebtRedeemed
(uint88), and colRedeemed
(uint88). Each ProposalData
structure requires 51 bytes, and the function calculates offsets accordingly to read the correct segments of the byte array for each field.ProposalData
structures, each representing a proposal data entry decoded from the byte array.This library plays a critical role in interpreting stored proposal data for redemption operations, facilitating the retrieval and use of structured information from raw byte-encoded storage.
This library provides functionality related to price oracles, specifically fetching, validating, and managing price data for assets in a decentralized finance (DeFi) ecosystem. It interacts with external oracle services (like Chainlink) and implements mechanisms to ensure the reliability and accuracy of price data.
getOraclePrice
asset
: The address of the asset for which the price is being fetched.baseOracleCircuitBreaker
oracleCircuitBreaker
twapCircuitBreaker
setPriceAndTime
: Stores the latest validated price and the timestamp of the update in the contract's storage for a given asset.getTime
: Retrieves the timestamp of the last price update for a given asset.getPrice
: Fetches the latest stored price for a given asset from the contract's storage.getSavedOrSpotOraclePrice
: Returns the stored price if it's recent (less than 15 minutes old) or fetches the current oracle price, validating and applying circuit breakers as necessary.These functionalities ensure the protocol uses accurate, timely, and reliable price data for its operations, incorporating safeguards against incorrect data and providing mechanisms to handle oracle failures or discrepancies.
This library provides functionality related to managing orders in a DeFi ecosystem, specifically for a platform that supports trading, shorting, and other order-based operations. It offers mechanisms for creating, canceling, and matching orders, as well as updating oracle prices and managing short records.
getOffsetTime
convertCR
uint16
into a uint256
format, scaling it to match the contract's expected precision.increaseSharesOnMatch
: Updates share counters when an order is matched, used for distributing token rewards.currentOrders
: Retrieves a list of current orders for a given asset, providing a snapshot of the market.isShort
: Checks if an order is a short order.addBid
, addAsk
, addShort
: Functions for adding bid, ask, and short orders to the respective order books.addSellOrder
: Adds an ask or short order to the market, using the appropriate internal function based on the order type.addOrder
verifyBidId
, verifySellId
, getOrderId
, verifyId
, normalizeOrderType
to validate order placement within the order book, ensuring correct ordering by price and handling order type-specific logic.cancelOrder
, cancelBid
, cancelAsk
, cancelShort
updateOracleAndStartingShortViaThreshold
, updateOracleAndStartingShortViaTimeBidOnly
, updateStartingShortIdViaShort
: Functions to update the oracle price and the starting short order id based on various triggers like price thresholds or time intervals, ensuring the order book remains in sync with the latest market conditions.findOrderHintId
: Finds a hint id for optimized order insertion, aiding in efficient order book updates.sellMatchAlgo
: Matches incoming asks against the highest bids, handling partial fills and updating the order book accordingly.matchIncomingSell
, matchIncomingAsk
, matchIncomingShort
: Final settlement functions for matched orders, adjusting user balances and short records.matchHighestBid
: Matches the highest bid with an incoming sell order, updating match totals and user balances.updateBidOrdersOnMatch
, updateSellOrdersOnMatch
, _updateOrders
: Update the order book upon order matching, removing filled orders and adjusting links in the bid/ask/short lists.handlePriceDiscount
, min
, max
to support order matching logic, price discount adjustments, and basic mathematical operations.This library centralizes the logic related to order handling, including creating, matching, and canceling orders, as well as integrating oracle price data for accurate market operations. It's crucial for the protocol's trading functionality, ensuring users can trade, short, and manage their orders efficiently within the ecosystem.
This library extends functionalities related to handling short records within a DeFi ecosystem. It offers a range of utilities for managing collateral, validating short orders, and adjusting short positions, particularly in response to market changes or user actions.
disburseCollateral
checkCancelShortOrder
checkShortMinErc
checkRecoveryModeViolation
transferShortRecord
updateErcDebt
These utilities are critical for maintaining the integrity and safety of the platform's shorting mechanism, ensuring that users' positions remain compliant with protocol requirements and that the system can adapt to ongoing changes in market conditions and user strategies.
This library offers functionalities to work with the Uniswap V3 pool oracle, enabling the calculation of token exchange amounts based on pool ticks, and estimation of time-weighted average prices (TWAP).
getQuoteAtTick
estimateTWAP
Oracle Reliance: The system's dependency on external oracles (e.g., Chainlink, Uniswap V3 Oracles) for asset prices introduces a central point of failure. If these oracles are manipulated or experience downtime, the platform's pricing mechanism could be severely impacted, leading to potential losses for users.
Admin Controls: The presence of administrative functions within the smart contracts, such as those allowing updates to critical system parameters or the ability to pause certain functionalities, could pose a risk if not decentralized or governed by a broad set of stakeholders.
Market Volatility: The system's reliance on real-time market data for executing trades, managing collateral ratios, and liquidations exposes users to market volatility risks. Sharp, adverse market movements could lead to systemic failures, especially if compounded by oracle latency or inaccuracies.
Liquidity Constraints: The operations involving bridging assets or settling trades depend on underlying liquidity in external pools (e.g., Uniswap). Insufficient liquidity or large trades relative to the pool size could lead to significant slippage, adversely affecting execution prices.
Smart Contract Interdependencies: The system's architecture involves multiple interacting smart contracts (e.g., for handling orders, oracles, asset management). Bugs or vulnerabilities in one contract could potentially compromise the integrity or security of the entire system.
Upgradeability: If the system employs upgradeable contracts, there's a risk of introducing new vulnerabilities during upgrades. Moreover, the process for upgrades needs to be secure and decentralized to prevent malicious changes.
Contract Complexity: The multifaceted logic for handling orders, liquidations, and price information introduces significant complexity. Complex systems are more prone to bugs and unintended behaviors, which could be exploited by malicious actors.
Integration Points: The system's integration with external protocols (e.g., Uniswap, Chainlink) adds layers of complexity and potential failure points. Issues in the integrated protocols, such as smart contract vulnerabilities or disruptions in their services, could indirectly affect this system's functionality and security.
User Experience: The complexity of managing multiple types of orders, understanding collateralization ratios, and interacting with various DeFi protocols could pose risks to less experienced users, potentially leading to mistakes that result in financial loss.
This risk assessment highlights areas where the system might be vulnerable due to centralization, market dynamics, architectural decisions, and the inherent complexities of DeFi ecosystems. Mitigating these risks involves thorough testing, audits, clear governance mechanisms, and continuous monitoring of external dependencies.
The system showcases an intricate blend of DeFi functionalities, leveraging smart contracts for asset management, price oracles, and liquidity provision. While it embodies the innovative spirit of decentralized finance, it also inherits risks associated with centralization, market volatility, architectural complexities, and integrations. Mitigation strategies, including rigorous testing, decentralized governance, and user education, are vital for ensuring its robustness and resilience in the dynamic DeFi landscape.
20 hours
#0 - c4-pre-sort
2024-04-07T20:36:26Z
raymondfam marked the issue as high quality report
#1 - c4-judge
2024-04-17T07:14:44Z
hansfriese marked the issue as grade-a