DeFi New Narrative? A New Model for Smart Contract Security Without Oracle Protocols

YBB Capital
2023-08-24 15:14:08
Collection
Regarding the future development direction of DeFi, we hope it can continuously capture market share from traditional finance with a safer and more efficient operating method.

Author: @Ac-Core, YBB Capital Researcher

Introduction

Oracles are a crucial factor in the DeFi world. While the security of different protocols is often inherited from the underlying smart contract networks, their normal operation still relies on oracles. If an oracle of a protocol is attacked or compromised, the entire protocol can be manipulated. Recently, new DeFi creators are crafting new narratives by conceptualizing entirely new lending and derivatives architectures, and a commonality among these protocol changes is the move away from reliance on oracles.

Risks and Fixes in DeFi

The greatest allure of DeFi comes from decentralization. Broadly speaking, it is an open financial system of permissionless payment protocols. Compared to traditional finance, its rules, profits, and even risks are disclosed in a relatively "obscure" manner, yet it still possesses a strong degree of openness.

However, after several years of development, the DeFi space has accumulated billions of dollars in thefts [1]. Even the most fervent believers continuously question whether it can become the mainstream of future finance. In 2022 alone, hackers stole over $3.8 billion through DeFi protocols and cross-chain bridges, making it the year with the highest amount of theft in crypto history. If we want to bring a larger group into the crypto world and rely on DeFi in the future, security is the primary factor that needs to be addressed.

Image source: Chainalysis

Risks of Oracles and "Primitives"

The organization Nascent, composed of builders, believes that the concept of "oracle-free protocols" will fundamentally provide a more robust and secure technical architecture for DeFi. Nowadays, DeFi hopes to define itself as "primitives," wishing for more teams to build products or composite protocols on its foundation. Once a contract is mixed with any external dependencies, it inherits all related risks. At the same time, the contract will upgrade to support a larger system ecosystem, and this managed upgrade variable will involve the current and future mutable environment, introducing more risk factors. As the name suggests, the introduction of oracles creates a dependency on external data, which brings potential risks. To this end, Nascent member Dan Elitzer proposed a new definition: to meet the conditions of primitives, it cannot rely on any external factors besides contracts deployed on the blockchain, such as: no governance, contract upgradability, and oracles.

However, the reality is that DeFi protocols that meet this basic definition are extremely rare, with Uniswap V1 being the most representative. From a security perspective, even Uniswap V2 and V3, which align with the aforementioned definition, do not qualify because they allow governance over certain functions, such as closing protocol fees and introducing fee tiers for pools.

That said, this narrow governance function has not triggered systemic risks due to large-scale upgrades present in other protocols. Thus, the reason for the tremendous success of all versions of Uniswap to date is the absence of oracles and full-chain dependencies.

Undoubtedly, Uniswap is the leader in decentralized trading. It has achieved great success and has spawned many experiments in decentralized exchanges. For instance, Uniswap V3 introduced the concept of non-fungible liquidity positions, allowing liquidity providers (LPs) to concentrate their liquidity within a specific range, enabling LPs to capture a larger share of transaction fees generated within that range and profit from it, although impermanent loss can occur with price fluctuations. This has led to more efficient capital usage and specialization among LPs in the market, giving rise to a series of position management tools like Arrakis, Gamma, and Sommelier. While this is very friendly for DEXs, lending protocols still require oracles.

Fast forward to March of this year, the Euler Finance lending protocol suffered a hack, resulting in losses of up to $200 million. It allows users to decide on collateral and borrow, but the issue arose in a specific function that lacked security checks, enabling users to disrupt the fundamental invariants of the lending market. For a detailed account of this attack, please read [2].

For lending protocols, qualified collateral is limited to assets with reliable oracle price feedback. Loan parameters (such as loan-to-value ratio [3]) are managed by the protocol, so any bad debts are the responsibility of the protocol rather than individual lenders. Similarly, derivatives protocols that rely on oracles for pricing, lacking internal price discovery mechanisms, are susceptible to price lag and lack of updates, severely limiting their scale and user experience. As mentioned in the introduction, this also explains why trader Avraham Eisenberg was able to successfully attack Mango Markets and withdraw $116 million from the cryptocurrency trading platform.

Why Uniswap is Safe Today

AMMs can have the simplest fundamental invariants among any DeFi primitives: tokenBalanceX * tokenBalanceY = k (constant product). For example, the Pair interface in Uniswap V2 is implemented based on the following four function invariants:

Mint: Add to k;

Burn: Subtract from k;

Swap: Move x and y, keeping k unchanged;

Skim: Readjust tokenBalanceX * tokenBalanceY to equal k.

The security of Uniswap V2 lies in a simple core invariant, with all functions serving this purpose. The only point of contention is its governance model that can toggle the fee switch, but this does not touch the core invariant; it merely affects the distribution of token balance ownership. It is precisely due to this simplicity in security (non-upgradable smart contracts and fundamental invariants) that Uniswap itself has never been hacked.

Rebuilding Lending Protocols

Image source: Author Balakov

Recently, we have seen many projects emerging for oracle-free lending protocols, such as Ajna, Ethereum Credit Guild, MetaStreet's Automated Tranche Maker, and the hybrid protocol Blend launched in collaboration with Blur and Paradigm [4].

Unlike traditional DeFi lending markets, Gauntlet does not set collateral and does not use a single universal oracle like Chainlink to provide "real" asset price sources for all users and protocol functions. Instead, borrowers need to assess risks to determine the collateral required from them and must update their borrowing standards as asset prices change. It generally works by allowing borrowers to choose specific collateral types they are willing to accept, such as BAYC Tokens and individual Bored Ape NFTs, the reference assets (like USDC) they are willing to provide as collateral, and the ratio of the reference asset to the collateral that they will require for liquidation. Finally, borrowers can post collateral and borrow the reference asset at current market rates.

It is important to note that since both parties have agreed that the liquidation of the loan is determined based on the unit quantity of each asset rather than the dollar price ratio, there is no need for an oracle. However, if the relative dollar value of any asset changes, the lender will adjust the terms of current or future loans to achieve what they consider a safe collateral ratio.

The greatest advantage of these methods is that the protocol is essentially unable to go bankrupt. This is because each lender is ultimately responsible for the repayment capability of their own loans, so there is no concept of "bad debt," which might otherwise be borne by a DAO treasury/insurance fund or handled among lenders.

The Blend hybrid protocol from Blur assumes "the existence of more sophisticated lenders who can participate in complex on-chain and off-chain protocols, assess risks, and use their own funds." This makes sense in the context of Blur as a primary trading venue for professional NFT traders, but it seems much more complex for ordinary users compared to borrowing on Aave or Compound.

New Faces Without Oracles

According to Messari researcher Chase Devens, the definition of oracle-free architecture can be divided into two categories: Peer-to-Peer and AMM-based hybrid types. Their main characteristics are as follows:

Peer-to-Peer

Supports any type of on-chain collateral;

Users bear loan parameters and take on bad debt risks (no longer the contract bearing the risk), borrowers no longer define interest rates and LTV parameters, but instead decide value comparisons themselves, and removing oracles from the protocol's mechanism means these loans can be created with any on-chain collateral.

Requires active management of positions; to ensure that the provided liquidity is effectively utilized, users must actively manage their positions in a manner similar to concentrated liquidity positions in Uniswap V3.

AMM-based Hybrid Type (Lending/Derivatives - LPs as Liquidity Providers)

Supports any type of on-chain collateral;

Underlying LP positions provide pricing data for liquidation and derivative contracts, while also serving as the primary market for liquidations. This allows the protocol to calculate the outcomes of liquidations and derivative contracts from its underlying liquidity pool, essentially making LP positions act like oracles. Additionally, these LP positions provide a primary market for unloading protocol inventory during liquidations or contract expirations, without needing to liquidate collateral on external platforms.

Examples:

Ajna.finance

Ajna is a lending protocol designed for EVM, with no governance, permissions, or external price feeds (oracles). It allows users to borrow against their entire portfolio (including NFTs). Other lending projects have reached critical mass due to two core issues: (1) Token governance systems are insufficient to analyze complex risks; (2) Using external price feedback (oracles) limits the asset range to "blue chips" with liquid secondary markets. These flaws have caused catastrophic losses in the DeFi lending market and limited the ability to support new assets. Ajna addresses these issues through several key innovations:

(1) Lenders provide asset pricing: When lenders use the Ajna protocol, they inform the contract of their willingness to collateralize assets at a certain price. This effectively allows them to input their own lifecycle value and shifts it from governance parameters to market parameters;

(2) Automatic interest rate discovery: Each Ajna market has an equilibrium state determined by internal metrics. If the market is unbalanced, anyone can change the exchange rate by 10% every 12 hours. If not, no changes are made;

(3) Liquidation collateral: Since Ajna has no oracles, it relies on users to inform it when to liquidate loans. This is achieved by requiring liquidators to post collateral to trigger a liquidation. If they are honest, they will be rewarded. If not, they will be penalized.

So what does this mean? These innovations enable Ajna to serve the "entire" ecosystem. Anyone can create a lending market with any asset (even NFTs). There is no longer a cumbersome governance process, and no need to worry about liquidity, secondary markets, and oracles.

Blend

Image source: Achal Srinivasan, Kirby

Blend is a peer-to-peer perpetual lending protocol that supports any collateral, including NFTs. It matches users with borrowing intentions to lenders willing to offer competitive rates through complex off-chain quoting protocols.

By default, the interest rate on Blend loans is fixed and never expires. Borrowers can repay at any time, while lenders can trigger Dutch auctions to seek new lenders at new rates to exit their positions. If the auction fails, the borrower will be liquidated, and the lender will take possession of the collateral. Overall, it features four key characteristics: oracle-free, perpetual, liquid, and peer-to-peer:

Oracle-Free

Many DeFi protocols require oracles to determine when to liquidate positions or set interest rates. For NFTs, for example, their prices are difficult to measure objectively, and timely updates of floor prices on-chain are also very hard to observe. Such solutions often involve trusted parties or trading manipulation. The hybrid protocol avoids any oracle dependency in the core protocol, allowing interest rates and loan ratios to be determined by the lender's willingness, with liquidation triggered by the failure of Dutch auctions;

Perpetual

Some DeFi protocols only support term-limited debt positions. This is inconvenient for borrowers, who need to remember to close or adjust their positions before expiration (or risk penalties, such as NFT confiscation). The manual adjustment process also consumes gas, reducing the profits generated from borrowing. As long as there are lenders willing to lend this amount based on collateral, Blend will automatically adjust the borrowing position, requiring on-chain transactions only when interest rates change or one party wants to exit the position;

Liquid

Some protocols do not support pre-expiration liquidations, which is more convenient for borrowers and reasonable in many use cases. However, this effectively gives borrowers a put option, requiring lenders to make choices between higher rates/lower loans within shorter expiration times to avoid the risk of position liquidation. In Blend, as long as lenders trigger refinancing auctions, NFTs can be liquidated if no one is willing to take on the debt at any rate;

Peer-to-Peer

Some protocols pool lenders' funds together and attempt to manage their assets. This means they heavily rely on on-chain management or centralized management to set parameters. Blend adopts a peer-to-peer model, with each loan matched individually. It does not optimize the simplicity of loan methods but assumes the existence of more complex borrower capabilities to participate in intricate on-chain and off-chain protocols, thus granting them greater control over their assets.

What is the FREI-PI Model

According to Nascent member Brock Elmore, the FREI-PI model stands for "Function Requirements-Effects-Interactions + Protocol Invariants pattern." Taking dYdX's SoloMargin contract (source code) as an example, this is a contract for a lending market and leveraged trading, serving as an excellent example of the FREI-PI model. It is the only lending market in early lending markets without any market-related vulnerabilities.

When reviewing the code below, pay attention to the following abstract concepts:

Input Requirements (_verifyInputs)

Operations (data transformation, state manipulation)

State Requirements (_verifyFinalState)

Image source: Brock Elmore

The commonly used Checks-Effects-Interactions are still in play. However, it is important to note that Checks-Effects-Interactions with additional Checks are not equivalent to FREI-PI; while they are similar, they serve different purposes. Therefore, developers should understand their differences: FREI-PI is a high-level abstraction for protocol security, while CEI is a high-level abstraction for functional security.

The interesting aspect of this contract structure is that users can continuously execute multiple operations at their discretion, including: deposits, borrowing, trading, transfers, liquidations, etc. We assume depositing three different tokens and withdrawing a fourth token while liquidating an account; this series of operations can be completed with a single click.

This is the power of FREI-PI: as long as the core lending market invariant holds at the end of the call, users can do anything they want within the protocol. For this contract, this will be executed in _verifyFinalState, checking the collateral status of each affected account to ensure the protocol is in a better state than when the transaction began.

This function also includes some additional invariants that complement the core invariant, aiding in auxiliary functions like market closure, but the true guarantee of protocol security lies in the core checks.

The entity-centered concept is another challenge of FREI-PI. Using the lending market and assumed core invariant as an example: users cannot take any actions that put any account in an unsafe collateral state. From a technical perspective, this is not the only invariant, but for users, it is the only invariant (understood as still being the core protocol invariant because the user invariant is the core protocol invariant). In lending markets, there are usually two additional invariants:

1. Oracles

Generally, Chainlink is a good choice, as its main function is to provide accurate and relatively accurate real-time information, which can meet the requirements of most invariants. In rare cases of manipulation or accidents, measures to ensure accuracy at the expense of real-time performance may be beneficial (e.g., checking if the last known value is hundreds of percentage points greater than the current value). However, Cream Finance still experienced an attack of $130 million. For more information on oracles, please refer to: Manipulating Uniswap V3 TWAP Oracles [5];

2. Governance

Governance is the trickiest invariant because it is difficult to constrain by conditions, and most of its functions change other invariants, with certain governance actions being unverifiable through FREI-PI. For example, the governance action that disrupted the cETH market in Compound in August 2022 violated the oracle invariant; for details, please read [6].

In practice, each additional invariant makes the protocol harder to protect, so fewer is better. Therefore, complexity is dangerous, and the most important invariant is the core invariant of the protocol. However, as mentioned above, there may also be some entity-centered invariants that must meet the requirements of the core invariant, and the simplest/minimal set of invariants may be safe.

Conclusion: The Future of DeFi

Is building DeFi on non-upgradable primitives and moving away from oracles the optimal solution? After all, the flexibility and usability brought by governance, upgradability, and oracles currently underpin DeFi protocols, allowing the entire market to reach hundreds of billions of dollars. According to Dan Elitzer's perspective mentioned above: governance, upgradability, and oracles are not inherently bad; on the contrary, these elements have significant practical value in a broader context, but they also increase the probability of protocol attacks.

Under the premise of updating functions or improving efficiency based on demand, primitives themselves can also be occasionally replaced. When choosing how to create DeFi protocols, there will be two important choices: should all user data and dependencies on external conditions be entrusted to a more centralized single protocol, delegated to a small number of token holders willing to participate in governance? Or should we value the ownership of every participant in the market, allowing users to decide the protocols and service providers?

Participants and developers in the entire industry are committed to building a more decentralized, permissionless, and highly composable DeFi to enhance the security and resilience of the entire industry. Regarding the future direction of DeFi, we hope it can continuously capture market share from traditional finance through safer and more efficient operational methods.

Explanations and References:

[1] https://rekt.news/leaderboard/ [2] https://medium.com/@omniscia.io/euler-finance-incident-post-mortem-1ce077c28454 [3] https://www.investopedia.com/terms/l/loantovalue.asp [4] htts://www.paradigm.xyz/2023/05/blend [5] https://github.com/euler-xyz/uni-v3-twap-manipulation/blob/master/cost-of-attack.pdf [6] https://medium.com/chainlight/the-suspension-of-compound-finances-ceth-market-causes-and-solutions-b106c2e1c922 http://www.nascent.xyz/idea/youre-writing-require-statements-wrong https://www.nascent.xyz/idea/why-defi-is-broken-and-how-to-fix-it-pt-1-oracle-free-protocols

ChainCatcher reminds readers to view blockchain rationally, enhance risk awareness, and be cautious of various virtual token issuances and speculations. All content on this site is solely market information or related party opinions, and does not constitute any form of investment advice. If you find sensitive information in the content, please click "Report", and we will handle it promptly.
ChainCatcher Building the Web3 world with innovators