DeFi’s New Narrative? A Novel Secure Model for Smart Contracts Without Oracles
Aug.23.2023
Author: YBB Capital Researcher Ac-Core
Word count: This article is over 7,000
Foreword
Prophecies are an important factor in the DeFi world, and while the security of different protocols is usually inherited by the underlying smart contract network, it still relies on the prophecy machine (Oracle) for its proper functioning, and if a protocol’s prophecy machine suffers from an attack or is corrupted, then the entire protocol can be manipulated. Recently new DeFi creators are making new narratives by conceptualising entirely new lending and derivatives architectures, and these protocols are changing in the same way that they are no longer relying on the prognosticator.
DeFi’s Risks and Fixes
DeFi’s greatest attraction comes from its decentralisation, which is broadly defined as an open financial system with permissionless payment protocols. Compared with traditional finance, its rules, profits, and even risks are disclosed in a more “hidden” way, but it still has a very strong degree of openness.
But after several years of development, DeFi has also accumulated billions of dollars in theft [1], and even the most ardent believers continue to question whether it can become the mainstream of the future of finance. Among them is more than $3.8 billion stolen by hackers through the DeFi protocol and cross-chain bridges during 2022 alone, and the largest amount stolen in crypto history. Security is a primary concern if a larger group of people are to enter the crypto world and rely on DeFi in the future.
Source: Chainalysis
Oracle Risks and “Source Code”
Nascent believes that the concept of “Oracle-free” will provide DeFi with a fundamentally more robust and secure technical architecture. Today DeFi prefers to define itself as “Primitives” and wants more teams to build products or portfolio protocols on top of them. Once the contract has any external dependencies, they inherit all the associated risks, and at the same time the contract is upgraded in order to host the larger system ecosystem, and this managed upgrade variable involves the present and future of the changeable environment, which introduces an additional element of risk. As the name suggests the introduction of Oracle creates a dependency on external data and this relationship creates a potential risk. For this reason Dan Elitzer proposed a new definition: in order to qualify as Primitives, a contract cannot be dependent on any external factors other than the contract deployed on the blockchain, e.g., no management, contract scalability, and predicators.
But the reality is that today DeFi protocols that meet this basic definition are very rare, the most representative of which is Uniswap V1, but even Uniswap V2 & V3, which are aligned with the definition proposed by Dan Elitzer above, are ineligible from a security point of view, as they allow for the governance of certain functionalities such as the closure of the protocol’s fees and the introduction of a pools of cost tiers.
Having said that, this narrow governance functionality does not raise systemic risks due to the massive upgrades present in other protocols, so the reason for the great success of Uniswap in all versions to date is the absence of the two key factors of Oracle and full chaining.
Undoubtedly Uniswap is the dominant player in decentralised trading, it has been a huge success and has given birth to many experiments in decentralised exchanges on top of it. For example, Uniswap V3 introduced the concept of non-homogenous liquidity positions, allowing liquidity providers (LPs) to concentrate their liquidity within a specific range, which allows LPs to capture and profit from a larger share of the transaction fees generated by trading within that range, but also incur unremunerated losses here as prices fluctuate. This led to a more efficient use of capital and specialisation of the LP part of the market, and with that came a range of position management tools such as Arrakis, Gamma and Sommelier, and whilst this was very friendly to DEXs, the lending protocols still required a prognosticator.
The time came in March this year, when the Euler Finance lending protocol was hacked to the tune of $200 million in losses. It allows users to post collateral and borrow money and has some unique features. In a nutshell its problem arose from a lack of security checks in a particular function that allowed users to corrupt the fundamental invariants of the lending market. The detailed course of this attack can be read in [2].
For lending protocols, eligible collateral is limited to assets with reliable predictor price feedback. Lending parameters (e.g., loan-to-value ratios [3]) are governed by their protocols, so that any bad loans are the responsibility of the protocols rather than individual lenders. Similarly, derivatives protocols that rely on a prognosticator for pricing that lack an internal price discovery mechanism are susceptible to price lags without updates, which can severely limit their scale and user experience. As mentioned in the introduction this also explains exactly why Avi Eisenberg was able to do the Mango Markets hack last October.
Why Uniswap is currently safe
AMM can have the simplest basic invariant of any DeFi source code (Primitives): tokenBalanceX * tokenBalanceY == k (e.g., constant product). For example, the Pair interface in Uniswap V2 is all implemented based on the following four function invariants:
Mint: add to k;
Burn: subtract from k;
Swap: move x and y, leaving k unchanged;
Skim: realigns tokenBalanceX * tokenBalanceY so that it is equal to k.
Uniswap V2 is safe: a simple core invariant for which all functions serve. The only thing that can be disputed is that it can toggle the governance mode of the fee switch, but this doesn’t touch the core invariant, it just affects the distribution of token balance ownership, and it’s because of this simplicity in their security (non-scalable smart contracts and basic invariants) that Uniswap itself has never suffered from hacking.
Reconstruction loan agreement
Source: Author Balakov
Recently we have seen the emergence of a number of projects for prophetless lending protocols, such as Ajna, Ethereum Credit Guild, MetaStreet’s Automated Tranche Maker, and Blend, a hybrid protocol launched by Blur and Paradig [4].
Unlike traditional DeFi lending markets, Gauntlet is not collateralised, nor does it have a single universal prediction machine like Chainlink that provides a source of “real” asset prices for all users and protocol features. Instead, borrowers need to assess the risk and decide on a certain amount of collateral to demand from the borrower, and must update their borrowing criteria as asset prices move. The way this works is generally that the borrower chooses the specified collateral they are willing to accept, e.g. BAYC Token and individually Bored Ape NFT etc., the referenced assets (e.g. USDC) they are willing to provide to the borrower to use as collateral and the ratio of referenced assets to collateral assets they will require the borrower to liquidate. Eventually the borrower can post the collateral and borrow the referenced asset at the current market rate.
Note that since the borrower and lender have agreed that the loan will be liquidated based on a ratio of the number of units of each asset rather than the USDC, a prognosticator is not required. However, if the relative dollar value of either asset changes, the lender will adjust the terms of the current or future loan to achieve what they consider to be a safe collateral ratio.
The biggest advantage of these methods is that the agreements are virtually insolvency-proof. This is because each lender is ultimately responsible for the solvency of its own loans, so there is no concept of “bad debt” that might have to be absorbed by a DAO treasury/insurance fund or dealt with between lenders.
Blur’s Blend hybrid protocol assumes “the existence of more sophisticated lenders capable of engaging in complex on- and off-chain protocols, assessing risk, and using their own funds”. This makes sense in the context of Blur’s role as the primary trading venue for professional NFT traders, but for the average user it seems much more complicated than borrowing on Aave or Compound.
New faces without Oracle
According to the definition of Messari researcher Chase Devens, the definitional architectures of prognosticator-less machines can be divided into two categories, namely Peer-to-Peer (P2P) and the hybrid type based on AMM. The main features of both of them are as follows:
Peer-to-Peer
Supports any on-chain collateral type
The user assumes the parameters of the loan and bears the risk of bad debt (no longer the contract assumes the risk), the borrower no longer defines the interest rate and LTV parameters but determines the value comparison for themselves, and the removal of the prognosticator from the protocol’s mechanics means that these loans can be created from any on-chain collateral.
Positions need to be actively managed, and to ensure that the liquidity provided is utilised efficiently, users must actively manage their positions in a similar way to Uniswap V3’s centralised liquidity positions.
Underlying LP positions provide pricing data for clearing and derivative contracts, as well as being the primary market for liquidation positions. Enables the protocol to calculate the outcome of cleared and derivative contracts from its underlying pool of liquidity, essentially making the LP positions themselves like a prognosticator. In addition, these LP positions provide a type of primary market for offloading protocol inventory during liquidation or contract expiration, rather than requiring collateral to be cleared on an external platform.
Examples:
Ajna.finance
Ajna is a lending protocol designed for EVMs, with no governance, permissions or external price feeds (prognosticators). It can be used to lend our entire portfolio (including NFT). Two core problems with other lending programs that have reached critical mass: (1) Token governance is insufficient to analyse complex risks (2) The use of external price feeds (predicators) limits the scope of the asset to “blue chips” with a liquid secondary market. These shortcomings caused catastrophic losses in the DeFi lending market and limited the ability to support new assets. Ajna addressed these issues through a number of key innovations:
(1) Lenders Provide Asset Pricing: When lenders use the Ajna protocol, they tell the contract how much they are willing to pledge assets for. This effectively allows them to input their life cycle value and transform it from a governance parameter to a market parameter;
(2) Automatic interest rate discovery: In every Ajna market there is an equilibrium determined by internal indicators. If the market is out of equilibrium, anyone can change the rate by 10% every 12 hours. If not, no change is made;
(3) Liquidation Margin: Since Ajna does not have a prediction machine, it relies on the user to tell it when to liquidate a loan. This is done by having the liquidator post a margin to trigger liquidation. If they are honest, they are rewarded. If not, they are penalised.
So what’s the point? These innovations allow Ajna to serve the “whole” ecosystem. Anyone can create a lending marketplace with any asset (even NFTs). No more struggling through the governance process and no more worrying about liquidity, secondary markets and prediction machines.
Blend is a peer-to-peer, perpetual lending protocol that supports any collateral, including NFTs, and matches households interested in borrowing with lenders willing to offer competitive rates through a complex off-chain offer protocol.
By default, Blend loans have a fixed interest rate and never expire. The borrower can repay the loan at any time, and the lender can exit its position by triggering a Dutch auction to find a new lender with a new interest rate. If the auction fails, the borrower will be liquidated and the lender will take possession of the collateral. The overall four main characteristics are that it is not dependent on a prognosticator, it is open-ended, it is liquid, and it is peer-to-peer:
No prognosticator
Many DeFi protocols require a prognosticator to determine the timing of liquidation positions or interest rate determination, in the case of NFT for example its price is very difficult to measure objectively, and in time the floor price is very difficult to observe on the chain, a solution that usually requires the involvement of a trusted party or manipulation of the trading strategy. The hybrid protocol avoids any reliance on a prognosticator in the core protocol, leaving interest rates and loan ratios to be determined by the lenders’ willingness to condition, and liquidation triggered by the failure of a Dutch auction;
Open-ended
Some DeFi protocols only support maturing debt positions. This is inconvenient for borrowers, who need to remember to close or adjust their positions before maturity (or risk facing penalties such as forfeiture of NFTs). The process of manually adjusting the position also consumes Gas, which also reduces the revenue generated by the borrowing. Blend automatically adjusts the borrowing position whenever a lender is willing to lend the amount based on collateral, and the only time an on-chain transaction is required is when interest rates change or when one of the parties wants to exit the position;
Liquidability
Some protocols do not support liquidation before maturity, which is more convenient for the borrower and makes sense in many use cases. However, this effectively gives the borrower a put option, and for the lender a choice needs to be made between a shorter maturity and a higher rate/lower loan to avoid the risk of the position being liquidated. In Blend, as soon as the lender triggers a refinance auction, the NFT can be liquidated with no one willing to take over the debt at any rate;
Peer-to-peer
Some of these agreements are pooling lenders’ funds and trying to manage their assets for them. This means there can be a heavy reliance on on-chain management or centralised management to set the parameters.Blend uses a peer-to-peer model and each loan is individually matched, it also doesn’t optimise the simplicity of the lending approach but rather the assumption that there is a more complex borrower scenario and thus the ability to engage in complex on-chain and off-chain protocols and thus have greater access to their assets.
What is the FREI-PI model
The FREI-PI pattern, as explained by Brock Elmore, is: “Function Requirements-Effects-Interactions + Protocol Invariants pattern”. “The SoloMargin contract (source code) for dYdX, a lending market and leveraged trading contract, is an excellent example of the FREI-PI model. This is the only early lending market that does not have any market-related vulnerabilities.
Note the following abstractions when viewing the code below:
Input requirements ( _verifyInputs )
manipulation ( data transformation, state manipulation )
State requirements ( _verifyFinalState )
Image source : Brock Elmore
The Checks-Effects-Interactions commonly used here are still being performed. However, it should be noted that Checks-Effects-Interactions with additional Checks are not the same as FREI-PI, although they are similar but serve different goals. For this reason developers should understand the difference: FREI-PI is a high-level abstraction for protocol security, while CEI is a high-level abstraction for functional security.
The interesting thing about this contract structure is that the user can perform as many operations as he/she wishes in a row: deposits, lending, trading, transfers, clearing, etc. We assume that 3 different types of deposits are made. Let’s assume that you deposit 3 different tokens and take out a fourth token and liquidate your account, all 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, the user can do whatever they want within the protocol, and the user has not taken any action to put any account into an insecure or more insecure collateral situation. For this contract, this is performed in _verifyFinalState, which checks the collateralisation of each affected account to ensure that the protocol is better than it was at the start of the transaction.
There are some additional invariants included in this function that complement the core invariants and help with ancillary functions such as closing the market, but it is the core checks that really secure the protocol.
One of the entity-centred concepts is another difficult problem for FREI-PI, using the lending market and the assumed core invariant as an example: the user cannot take any action that puts either account into an insecure collateral state. This is not the only invariant from a technical point of view, but it is the only invariant for the user (which can be interpreted as still being a core protocol invariant, since a user invariant is a core protocol invariant). There are usually two additional invariants in lending markets:
1. Prophecy machine
In general Chainlink is a good choice, and its main function is to provide accurate and relatively accurate real-time information, which can satisfy most invariants. In the rare case of manipulation or accidents, it may be beneficial to reduce real-time safeguards to ensure accuracy (e.g. checking that the last known value is not hundreds of percentage points greater than the current value). Still, Cream Finance incurred a $130 million breach. For more information on prophecy machines see: manipulating the Uniswap V3 TWAP prophecy machine [5];
2. Governance
Governance is the trickiest invariant because it is difficult to subject to conditioning and most of its effect is to change other invariants, and because some governance cannot be verified by FREI-PI at the time of operation. Administrators violate invariants, as exemplified by Compound’s governance operation that disrupted the cETH market in August 2022, an upgrade that violated the invariants of the prognosticator, read more in [6].
In practice, each additional invariant makes the protocol more difficult to protect, so fewer should be better. Thus complexity is dangerous and the most important invariants are those at the core of the protocol, but as mentioned above there will also be entity-centred invariants that must satisfy the core invariants and the simplest/minimal set of invariants may be safe.
Summary: The Future of DeFi
Is it optimal to build DeFi on top of unscalable Primitives and away from the Predictor? After all, the flexibility and ease-of-use of the DeFi protocol today, thanks to governance, scalability, and predicators, has led to a market size of hundreds of billions of dollars. According to Dan Elitzer, governance, scalability and predicators are not inherently bad — on the contrary, these elements have great practical value in a broader context — but they also increase the probability of attacks on the protocol.
The source code (Primitives) itself is open to occasional replacement, subject to updating functionality or improving efficiency as required. There will be two important choices to be faced when choosing how to create the DeFi protocol: hand over all users’ data and dependence on external conditions to a more centralised single protocol and delegate it to a small group of Token holders willing to participate in governance? Or value the ownership of each participant in the market? Let users decide on their own protocols and service providers.
Participants and developers across the industry are committed to building a more decentralised, permissionless, and highly combinatorial direction of development, which can improve the security and resilience of the industry as a whole. Regarding the future direction of DeFi, we hope it can continue to capture the market share of traditional finance with more secure and efficient operation.
About YBB
YBB is a web3 fund dedicating itself to identify Web3-defining projects with a vision to create a better online habitat for all internet residents. Founded by a group of blockchain believers who have been actively participated in this industry since 2013, YBB is always willing to help early-stage projects to evolve from 0 to 1.We value innovation, self-driven passion, and user-oriented products while recognizing the potential of cryptos and blockchain applications.
YBB Capital is a venture capital firm focused on blockchain and Web3 investments. The content on this website is for informational purposes only and does not constitute an offer to sell or a solicitation of an offer to buy any security or financial product. Any investments or portfolio companies mentioned are not representative of all investments, and there is no guarantee of future results. Information on this site may include forward-looking statements and is provided "as is" without any warranties, express or implied. YBB Capital does not provide investment, legal, or tax advice. Website access is limited to jurisdictions where such access is lawful. Users are responsible for complying with applicable local regulations.