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: 19/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
The Ditto Protocol is a groundbreaking decentralized stable asset platform on the Ethereum mainnet. It introduces a novel approach to stablecoin generation, leveraging overcollateralized liquid staked Ether (such as rETH, stETH) to mint a USD-pegged stablecoin, designated as dUSD. This process is facilitated through a gas-optimized order book, distinguishing Ditto from conventional stable asset protocols.
The order book is the central component of the Ditto ecosystem, where bidders, shorters, and askers interact:
The BidOrdersFacet
contract plays a critical role in managing bid orders within the Ditto protocol's ecosystem, particularly focusing on the creation and matching of bids in a decentralized stable asset protocol.
onlyDiamond
ModifieronlyDiamond
modifier restricts certain functions to specific addresses, presenting a risk if these addresses are compromised or misused. Privileged users could potentially alter market dynamics or access user funds improperly.onlyDiamond
modifier, but particularly sensitive operations like createForcedBid
.LibOracle
for Price FeedsLibOracle.getPrice(asset)
) for asset pricing introduces the risk of inaccurate or manipulated price data, which could disrupt the order matching logic.bidMatchAlgo
function and any other functionality relying on price data for decision-making.bidMatchAlgo
FunctionbidMatchAlgo
pose a risk of bugs or logical errors, potentially compromising market integrity.bidMatchAlgo
function, with repercussions for the entire marketplace's operation._createBid
are particularly at risk, given their role in complex state transitions and orderbook updates.LibAsset
, LibOrders
, and potentially others not explicitly mentioned but crucial for contract operation.LibOracle
for External DataLibOracle
for critical operations like price validation and order matching presents a risk if the oracle service is disrupted or manipulated.The ShortOrdersFacet
contract is integral to the Ditto Protocol, facilitating the creation of limit short orders within its decentralized stable asset ecosystem.
isNotFrozen
and onlyValidAsset
suggests that administrative controls exist to freeze assets or designate valid assets. Improper admin access to these controls could lead to unilateral freezing of assets or manipulation of valid asset lists, affecting market liquidity and user strategies.shortOrderCR
)createLimitShort
calculates collateral requirements based on the shortOrderCR
parameter. Systemic misconfiguration or exploitation of this parameter could lead to under-collateralized short orders, threatening the protocol's financial stability.LibOracle.getSavedOrSpotOraclePrice
for price data introduces a risk if the oracle provides inaccurate or manipulated price feeds. This could adversely affect short order valuations and the protocol's market integrity.The PrimaryLiquidationFacet
contract is designed for managing the liquidation process within a DeFi protocol. This analysis explores the potential risks across admin abuse, systemic, technical, and integration categories, with a focus on the contract's specific functions and terms.
if (msg.sender == shorter) revert Errors.CannotLiquidateSelf()
ensures a user cannot liquidate their own short position. While this prevents self-liquidation, it assumes that malicious actors won't use secondary accounts to circumvent this restriction, potentially exploiting the system for unintended benefits.dusd
Addressdusd
address. If this contract becomes compromised or requires updates, the hardcoded address poses a significant security risk._performForcedBid
) can have unintended consequences on market prices and liquidity, especially if large positions are liquidated in a short timeframe. This could lead to market volatility or manipulation opportunities.shortHintArray.length
aim to prevent excessive computation, but insufficient protection could allow for gas cost manipulation.liquidate
liquidate
function's intricate logic, which involves multiple conditional paths, external library calls, and state updates, increases the risk of bugs. Specifically, incorrect handling of the shortHintArray
length could lead to unanticipated behaviors, given the function's reliance on this array for processing liquidations.LibShortRecord
for Short Record ManagementLibShortRecord
for managing short records. Any vulnerabilities or inefficiencies in LibShortRecord
directly impact the liquidation process's integrity, particularly in how short records are created, updated, or deleted (_setLiquidationStruct
, _fullorPartialLiquidation
).This analysis identifies specific risks associated with the BridgeRouterFacet
contract, integral to managing cross-chain asset bridges within a DeFi protocol. Risks are categorized into admin abuse, systemic, technical, and integration risks, focusing on the contract's unique functionalities and structures.
onlyDAO
Modifier in withdrawTapp
withdrawTapp
are protected by the onlyDAO
modifier, indicating that only the DAO can execute them. If the DAO's decision-making process is compromised or if the DAO operates without sufficient decentralization, this power could be misused to withdraw assets from the protocol unfairly.rethBridge
and stethBridge
addresses. Should these bridge contracts become compromised or outdated, the BridgeRouterFacet
lacks the flexibility to switch to safer or updated bridges without redeploying the contract.C.MIN_DEPOSIT
might not accommodate fluctuating economic conditions, possibly excluding users due to high thresholds or allowing minimal deposits that could spam the system.deposit
and depositEth
) could lead to discrepancies between expected and actual dethAmount
received._ethConversion
method's adjustments based on vault performance may result in less ETH than anticipated, particularly under negative yield conditions, affecting user trust.maybeUpdateYield
mechanism for dynamic yield adjustments based on deposit sizes could be exploited to manipulate yield rates, disturbing the protocol's economic balance._getVault
for bridge legitimacy could be insufficient, posing risks if a bridge is compromised or functions unexpectedly.deposit
, depositEth
, and maybeUpdateYield
perform critical financial calculations, including gas fee estimations and yield rate updates. Inaccurate calculations or failure to timely update yield rates based on significant deposit events could impact financial outcomes for users._getVault
and _ethConversion
functions rely on correct configuration of bridge addresses and vault parameters. Misconfigurations could lead to incorrect routing of deposits/withdrawals or flawed asset conversions, especially under negative yield scenarios.The ExitShortFacet
contract provides mechanisms for users to exit their short positions through various methods, including wallet balance, escrowed ERC tokens, and market bids. This analysis explores the risks associated with its functionalities.
buybackAmount
will not exceed the existing ercDebt
. Incorrect inputs could lead to negative debt values or misallocation of funds.exitShortWallet
and exitShortErcEscrowed
.exitShortWallet
and exitShortErcEscrowed
post-debt repayment.if (getCollateralRatioNonPrice(short) < e.beforeExitCR) revert Errors.PostExitCRLtPreExitCR()
) hinges on the accurate calculation of these ratios. There's a risk if the calculation does not account for all factors, such as pending yield
updates or fees
not yet applied.exitShort
.IDiamond(payable(address(this))).createForcedBid
, which introduces a dependency on the correct functioning of another contract. If the forced bid fails (e.g., e.ethFilled == 0
), the user's intent to exit the short is not achieved, potentially leaving them in a risky position longer than intended.exitShort
.The RedemptionFacet
contract is a critical component of a DeFi protocol, designed to manage the redemption process for short positions. This facet allows users to propose, dispute, and claim redemptions in a structured and secure manner, interfacing with various aspects of the protocol's ecosystem to ensure accurate and fair operations.
Users can submit proposals for redeeming their short positions by specifying the amount of debt they wish to buy back. The proposal includes a detailed slate of short records (SRs) identified as candidates for redemption, subject to a dispute period. This mechanism ensures that proposals are carefully vetted before execution.
To safeguard against incorrect or malicious redemption proposals, the contract allows other users to dispute proposed redemptions within a specified timeframe. Disputes focus on validating the correctness of the proposed SRs, ensuring that only valid and fair redemptions proceed.
After the dispute period passes without challenges, or if a dispute validates the proposal, the proposer can claim the collateral associated with the redeemed SRs. This function facilitates the return of locked assets to users following successful redemption.
The contract dynamically calculates redemption fees based on several factors, including the total amount of debt being redeemed and the current market conditions. This fee structure is designed to maintain the protocol's economic balance and incentivize fair redemption practices.
SSTORE2
introduces risks related to data integrity and potential for buffer overflow exploits.calculateRedemptionFee
) and collateral ratio assessments employ complex arithmetic. Any faults in these calculations risk incorrect fee assessments or unintended short record closures.LibBytes.readProposalData
and subsequent manipulations pose a risk of data corruption or misinterpretation, especially given the reliance on precise data formats and indexing.The LibBridgeRouter
library is instrumental in bridging assets within a DeFi protocol, facilitating the credit of dETH (decentralized Ethereum) to user accounts, and managing the intricacies of withdrawals across different bridges. This document outlines the specific technical problems identified within the library, emphasizing the need for precision in handling bridge credits, withdrawal fees, and the reliance on oracle data.
VAULT.ONE
and other vaults introduces complexity that might not scale with additional bridge types or vault configurations. This rigid structure could lead to misallocation or oversight in credit management for future assets.vault
and bridgePointer
requires updates for new bridges or vaults, posing scalability and maintenance challenges.IBridge.getDethValue()
for bridge credit validation introduces external dependency risks, potentially affecting withdrawal operations.VAULT.ONE
, could lead to transaction reverts under Errors.MustUseExistingBridgeCredit()
, limiting user flexibility.unitRethTWAP
, unitRethOracle
, and similar variables for stETH calculations could lead to incorrect fee assessments if oracle data is compromised.VAULT.ONE
) necessitates meticulous balance management to ensure fair and accurate credit attribution and transfer.The LibOracle
library serves as a critical component in determining the price of assets within a DeFi protocol, interfacing with both Chainlink oracles and a TWAP mechanism for price data. This analysis delves into specific technical issues inherent to its functions and outlines potential risks tied to external data dependencies and internal logic.
AggregatorV3Interface
) for fetching the latest price data. Reliance on a single external data source increases the risk of price manipulation or failure in data delivery.baseOracle.latestRoundData()
and oracle.latestRoundData()
which, if compromised or inaccurate, can lead to incorrect asset valuation.baseOracleCircuitBreaker
, oracleCircuitBreaker
, and twapCircuitBreaker
) requires precise conditions for activation, which might not cover all edge cases, leading to erroneous price data usage.estimateWETHInUSDC
) is contingent upon sufficient liquidity (IERC20.balanceOf
) and recent trades, with insufficient validation mechanisms for these parameters.The LibOrders
library is designed to facilitate order handling within a trading platform, including creating, matching, and canceling orders. This analysis identifies potential risks and problems using technical terms from the contract.
getOffsetTime()
block.timestamp
, which can be slightly manipulated by miners, potentially affecting timing-based logic.currentOrders(...)
isShort(STypes.Order memory order)
sellMatchAlgo(...)
matchHighestBid(...)
The DittoETH protocol's architecture is designed to facilitate a decentralized finance (DeFi) ecosystem focused on stablecoin trading and liquidity provision. Below is an overview of the core components,
ShortOrdersFacet
)This component is crucial for managing short positions within the DittoETH ecosystem. It allows users to initiate and manage short orders against the protocol's stablecoin, enabling speculative trading and hedging strategies.
PrimaryLiquidationFacet
)Facilitates the liquidation process of undercollateralized short positions. It ensures the system's stability by enforcing collateral requirements and managing the liquidation of positions that fall below the required collateral ratio.
BridgeRouterFacet
)Serves as an interface for integrating external liquidity sources through bridging mechanisms. It allows the DittoETH protocol to interact with other DeFi ecosystems, enhancing liquidity and enabling cross-chain functionality.
Provides oracle services to the DittoETH protocol, fetching external price feeds and ensuring the system operates with accurate and up-to-date market information.
A library that manages the order book for the DittoETH protocol, handling the creation, execution, and cancellation of orders within the trading ecosystem.
ethEscrowed
, ercEscrowed
) must always be non-negative.bridgeCreditReth
and bridgeCreditSteth
within a vault equals the total RETH and STETH deposited.shortOrderCR
) for any short order is within platform-specific bounds.ercDebt
, collateral
, and status.The evaluation of the DittoETH protocol entails a thorough technical examination of its smart contract ecosystem, focusing on functionality, security, and performance. Below is the detailed methodology adopted for this analysis:
ShortOrdersFacet
, PrimaryLiquidationFacet
, and BridgeRouterFacet
.LibOracle
implementation to assess how oracle data is fetched, validated, and used within the protocol.The DittoETH protocol exhibits a commendable modular approach, segmenting its functionality across distinct contracts like BidOrdersFacet
, PrimaryLiquidationFacet
, and RedemptionFacet
. This separation enhances readability and maintainability.
Improvement Suggestion: Implementing the Factory pattern could further streamline the management of these facets, especially in creating similar instances with different parameters.
The protocol utilizes inheritance to share functionalities between contracts, reducing code duplication but potentially complicating interactions.
Improvement Suggestion: Favoring composition over inheritance could simplify contract interactions and enhance clarity.
Utilization of nonReentrant
modifiers across state-changing functions indicates proactive measures against reentrancy attacks.
Improvement Suggestion: Adopt additional checks, such as the Checks-Effects-Interactions pattern, to reinforce protection against unforeseen behaviors.
The protocol incorporates input validation and error handling to ensure that functions behave as expected.
Improvement Suggestion: Expanding the use of custom error types could provide more descriptive error information and reduce gas costs.
Functions involving loops and multiple state accesses present opportunities for optimization. Improvement Suggestion: Reducing state access within loops and utilizing memory variables for intermediate results can significantly lower gas costs.
Efficient data structure usage is crucial for gas optimization. Improvement Suggestion: Evaluating the use of arrays, mappings, and structs, and considering alternatives like EIP-1167 for contract creation, could offer gas savings.
An overall line coverage percentage of 96%
from tests indicates a high level of thoroughness in the testing process, covering the vast majority of the codebase
Improvement Suggestion: Focusing on edge cases and incorporating fuzz testing and property-based testing can reveal deeper issues. Achive 100% test coverage .
Ensuring consistency between inline documentation and external documentation is vital.
Improvement Suggestion: A documentation generation tool that leverages inline comments could automate and ensure documentation consistency.
proposeRedemption
and calculateRedemptionFee
.proposeRedemption
and disputeRedemptio
n is critical. Beyond checking for trivial conditions, validate the integrity and consistency of complex inputs, such as ensuring proposalInput arrays do not contain duplicate entries or invalid addresses.SSTORE2
, such as in proposeRedemption
, optimizing data encoding and choosing the most gas-efficient data types can reduce storage costs. Compact data tightly using Solidity's abi.encodePacked
to reduce the storage footprint.proposeRedemption
, loops are used to iterate over proposal inputs. To optimize gas, consider loading external contract states into memory at the start of a function and working with these in-memory structures as much as possible before writing back to storage.liquidate
function, which involves complex calculations, external calls, and potentially large loops (through shortHintArray), might consume a significant amount of gas. High gas costs can deter users from initiating liquidations, potentially affecting the protocol's health.LibOracle.getPrice
for fetching asset prices, which introduces centralization and manipulation risks if the oracle is compromised or inaccurate.Use multiple oracle sources to fetch asset prices and implement a medianizer to determine the final price. Consider decentralized oracle solutions that aggregate data from various sources.Develop an automated risk management system that dynamically adjusts parameters like collateralization ratios or interest rates based on market conditions and protocol health.
Introduce yield farming and staking opportunities within DittoETH, allowing users to earn rewards by providing liquidity or staking tokens.
70 Hours
69 hours
#0 - c4-pre-sort
2024-04-07T20:36:19Z
raymondfam marked the issue as high quality report
#1 - c4-judge
2024-04-17T07:00:09Z
hansfriese marked the issue as grade-a