<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yaron Velner on Medium]]></title>
        <description><![CDATA[Stories by Yaron Velner on Medium]]></description>
        <link>https://medium.com/@yaron_velner?source=rss-f9716a559e68------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4wc5mMqfaMTZO6vi.jpg</url>
            <title>Stories by Yaron Velner on Medium</title>
            <link>https://medium.com/@yaron_velner?source=rss-f9716a559e68------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 05:57:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yaron_velner/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Relend Network: The Bank of L2s]]></title>
            <link>https://medium.com/relend-network/relend-network-the-bank-of-l2s-6df2af16de9a?source=rss-f9716a559e68------2</link>
            <guid isPermaLink="false">https://medium.com/p/6df2af16de9a</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[lending]]></category>
            <dc:creator><![CDATA[Yaron Velner]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 08:41:45 GMT</pubDate>
            <atom:updated>2024-11-22T08:41:45.562Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*NXdGilT6bcpis6CL" /></figure><p>The cambrian explosion of new L2s, with 73 L2 blockchains listed on <a href="https://l2beat.com/scaling/summary">L2beat</a>, and <a href="https://cointelegraph.com/news/ethereum-layer2-defi-blockchain-adoption">82 more in the pipeline</a>, makes it harder for each of them to succeed. Similar to traditional early stage economies, the lack of liquidity and TVL makes it difficult to bootstrap meaningful economic growth.</p><p>In the traditional world, banks inject liquidity into well established economies, but are reluctant to operate in growing economies due to high default risk.</p><p>The high risk stems from the lack of transparency in the environment the bank operates.</p><p><a href="https://ethereum-magicians.org/t/erc-7770-fractional-reserve-token/21103">ERC-7770</a> defines the standard for a fractional reserve L2 bridge, which enables Relend Network to become the bank of L2s by injecting liquidity and TVL to support new ecosystems.</p><p>$100m of user deposits will allow Relend network to provide $10m TVL for up to 100 partner L2s. Of those 100 L2s, the successful ones will foster the adoption of Relend Network’s fractional reserve banking system. And thanks to the transparency and security standards of blockchain L2s, the cost of providing liquidity to the less successful networks will be close to zero.</p><p>In the next section we give a brief recap ofrelending as a concept and how fractional reserve bridging is applied to a single L2. In the section that follows it, we extend the architecture to a multi-L2 bank.</p><h3>ERC-7770 and fractional reserve bridges</h3><p>As with any other L2 bridge, users bridge their asset (e.g., USDC) from an L1, and the bridge application mints them an L2 USDC for their L2 account.</p><p>In addition, fractional reserve bridges can also mint assets as a (collateralized) loan. For example, mint USDC vs an ETH collateral.</p><p>The minted USDC is fully fungible with the bridged USDC, and as long as the minted USDC remains in the L2, the bridge can provide additional USDC loans.</p><p>As the total supply of USDC in the L2 could be higher than the amount that was bridged from the L1, not all USDC can immediately be bridged back to the L1. However, as the bridged supply gets smaller, it increases the borrow interest rate, which encourages more users to bridge to the L2, and borrowers to repay their loan (which in turn burns the repaid USDC, reducing the L2 supply).</p><p>Such an architecture allows any new L2 to immediately start with a $10m supply side TVL lending market, simply by minting USDC to a local lending market, and to x10 its available liquidity w.r.t the amount of bridged assets, relending the same USDC ten times.</p><p>However, the relending is only possible when borrowers choose to keep their borrowed USDC within the L2. While operating in a silo, thishappens when borrowers decide to sell the USDC on the local dex, or transfer the USDC as payment in the L2.</p><p>This works well for L2s that are successful from day 1, however, the rest will still strive to bootstrap their ecosystem and keep the borrowed assets within their ecosystem.</p><p>In the next section we present how the multi-L2 architecture enables the relending effect for early stage networks.</p><h3>Multi-L2 setup</h3><p>The ability to relend is determined by the fractional reserve ratio. Which stands for the ratio between the reserve supply (assets in the bridge) and total assets minted. When adopting a multi-L2 setup, we get a <em>local fractional reserve ratio</em>, and a <em>global fractional reserve ratio</em>.</p><p>The local ratio takes into account only the assets that were bridged and minted in a single L2, and the global ratio is the weighted average among allL2 partners.</p><p>When working in silos, it is important to maintain a reasonable local fractional reserve ratio, in order to allow users to be able to bridge back to the L1 in a timely manner. A multi-L2 framework can take advantage of a multi-chain message passing protocols like layer zero and chainlink’s CCIP, and create a unified bridge. In such a setup, the global fractional reserve ratio is the key metric for allowing quick bridging, for allL2 partners.</p><p>As a result, the relending effect is maintained, as long as the borrowed USDC is kept in a partner’s L2, which immediately amplifies the available liquidity of each L2.</p><p>Moreover, it allows Relend Network to safely seed TVL in new L2s with millions of dollars, even before the first user deposit was made.</p><h3>Super lenders</h3><p>The multi-L2 bridge will accept deposits both from normal L2 users, who bridge their assets into an L2 so they can use it there, and from super lenders who lock their assets in the bridge and in return receive higher interest rates.</p><p>As every $ can be borrowed 10 times, super lenders will get above market return.</p><h3>Security and risk management</h3><p>The multi-L2 bank will seed liquidity only for L2s that adhere to certain security requirements. E.g., using a known L2 stack, with enabled fraud proof mechanism, sufficient time lock duration for upgrades, and a recognized sequencer operator.</p><p>Furthermore, the bank will inject the liquidity only into lending markets with secure smart contract code and an eligible risk management framework.</p><p>The whitelisting of eligible L2s will be done by the Relend Network community, and eventually by the Relend Network DAO.</p><h3><strong>Relend Network</strong></h3><p>Twitter:<a href="https://x.com/relend_network"> https://x.com/relend_network</a></p><p>Telegram:<a href="https://t.me/relend_network"> https://t.me/relend_network</a></p><p>Bot: <a href="https://t.me/relendbot">@relendbot</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6df2af16de9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/relend-network/relend-network-the-bank-of-l2s-6df2af16de9a">Relend Network: The Bank of L2s</a> was originally published in <a href="https://medium.com/relend-network">Relend Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arbitraging thUSD’s Stability Pool for Fun and Profit]]></title>
            <link>https://medium.com/b-protocol/arbitraging-thusds-stability-pool-for-fun-and-profit-95dad15444d3?source=rss-f9716a559e68------2</link>
            <guid isPermaLink="false">https://medium.com/p/95dad15444d3</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[risk-management]]></category>
            <dc:creator><![CDATA[Yaron Velner]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 13:52:07 GMT</pubDate>
            <atom:updated>2024-07-14T11:12:03.194Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LmJI9AntRwwW8glW" /></figure><p>Threshold USD integrated B.Protocol’s Backstop Automated Market Maker (B.AMM) to manage its thUSD stability pool deposits. The motivation for the integration is to increases the stability pool capital efficiency and to support higher liquidation volume over time (e.g., see <a href="https://medium.com/risk-dao/analyzing-and-modeling-stability-pool-dynamics-b9161b3776f8">here</a>).</p><p>At its core, the process relies on arbitrage bots who supply thUSD in return for a discounted ETH or tBTC.</p><p>In this post, we explain how bots could arbitrage the B.AMM, and present an open source smart contract to facilitate such an arbitrage.</p><h3>Buying discounted ETH</h3><p>Every liquidation of ETH collateral takes some thUSD from the stability pool, and gives some ETH in return. The B.AMM offers the ETH for sale, in return to thUSD. The ETH is offered with a varying discount over chainlink market price, where the discount depends on the quantity of ETH that is available for sale. The bigger the quantity is, the higher the discount. The reader can find more technical details on the discount formula <a href="https://docs.bprotocol.org/technical-documentation/v2">here</a>.</p><h4>How to arbitrage?</h4><p>B.AMM address (Ethereum mainnet):</p><ul><li>BAMM address: <a href="http://0xf4Bd4B8227F4EBB00c140df413306A4FA78542D6">0xf4bd4b8227f4ebb00c140df413306a4fa78542d6</a></li></ul><p>Price query function: <strong>getSwapCollateralAmount(uint256 thusdQty)</strong></p><p>Swap function: <strong>swap(uint256 thusdAmount, uint256 minCollateralReturn, address payable dest)</strong></p><p>Arbitrage bot smart contract reference:</p><ul><li>Deployed address: <a href="https://etherscan.io/address/0xfbea9aaa9a822aedd429fdab3099a2dba942f196#code">0xfbea9aaa9a822aedd429fdab3099a2dba942f196</a></li><li>Arbitrage function: <strong>swap(uint ethQty, address bamm, address payable profitReceiver)</strong></li><li><strong>ethQty</strong>: the amount of ETH to buy in the arbitrage</li><li><strong>bamm</strong>: the B.AMM address that is used in the arbitrage</li><li><strong>profitReceiver:</strong> the destination address for the profit.</li></ul><p>A potential backend implementation would be to call the swap function offchain with various sizes, and to execute a tx when it is not expected to revert. The backend can also be implemented with <a href="https://app.gelato.network/">Gelato</a>.</p><h3>Buying discounted tBTC</h3><p>Every liquidation of tBTC collateral takes some thUSD from the stability pool, and gives some tBTC in return. The B.AMM offers the tBTC for sale, in return to thUSD. The tBTC is offered with a varying discount over chainlink market price, where the discount depends on the quantity of tBTC that is available for sale. The bigger the quantity is, the higher the discount. The reader can find more technical details on the discount formula <a href="https://docs.bprotocol.org/technical-documentation/v2">here</a>.</p><h4>How to arbitrage?</h4><p>B.AMM address (Ethereum mainnet):</p><ul><li>BAMM address: <a href="https://etherscan.io/address/0x920623AcBa785ED9a70d33ACab53631e1e834675#code">0x920623AcBa785ED9a70d33ACab53631e1e834675</a></li></ul><p>Price query function: <strong>getSwapCollateralAmount(uint256 thusdQty)</strong></p><p>Swap function: <strong>swap(uint256 thusdAmount, uint256 minCollateralReturn, address payable dest)</strong></p><p>Arbitrage bot smart contract reference:</p><ul><li>Deployed address: <a href="https://etherscan.io/address/0x067a0209c6e03f9a077d967e48b410b7bf811ec9">0x067a0209c6e03f9a077d967e48b410b7bf811ec9</a></li><li>Arbitrage function: <strong>swap(uint btcQty, address bamm, address payable profitReceiver)</strong></li><li><strong>btcQty</strong>: the amount of WBTC to buy in the arbitrage. 8 decimals should be used to encode the qty. The WBTC is later exchanged to tBTC.</li><li><strong>bamm</strong>: the B.AMM address that is used in the arbitrage</li><li><strong>profitReceiver:</strong> the destination address for the profit.</li></ul><p>A potential backend implementation would be to call the swap function offchain with various sizes, and to execute a tx when it is not expected to revert. The backend can also be implemented with <a href="https://app.gelato.network/">Gelato</a>.</p><h3>Disclaimer</h3><p>The reference bot code comes with no warranty. Using the bots does not require any funds, however gas fees could be lost in the event of unsuccessful arbitrage. Users should set reasonable gas prices when using the bots.</p><h3>About B.Protocol</h3><p>B.Protocol has been building open-source protocols and infrastructure for risk mitigation and assessment for the DeFi ecosystem since 2020. Through our research arm, <a href="http://riskdao.org/">RiskDAO</a>, and its novel risk framework, we have supported over a dozen DeFi protocols with risk analysis, research, audits, and monitoring. Our <a href="https://risk-oracle.bprotocol.org/">Risk Oracle</a>, together with the <a href="https://twitter.com/bprotocoleth/status/1682319285190811648?s=20">SmartLTV formula</a>, and the <a href="https://medium.com/risk-dao/announcing-the-risk-level-index-ca5dcef95303">Risk Level Index</a> automate the process of setting risk parameters for lending platforms in a transparent way, building the next generation of DeFi risk management infrastructure.</p><p><a href="https://bprotocol.org/">Website</a> | <a href="https://twitter.com/bprotocoleth">Twitter</a> | <a href="https://discord.com/invite/bJ4guuw">Discord</a> | <a href="https://medium.com/b-protocol">Medium</a> | <a href="https://github.com/backstop-protocol">Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95dad15444d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/b-protocol/arbitraging-thusds-stability-pool-for-fun-and-profit-95dad15444d3">Arbitraging thUSD’s Stability Pool for Fun and Profit</a> was originally published in <a href="https://medium.com/b-protocol">B.Protocol</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A complexity measure for smart contracts]]></title>
            <link>https://medium.com/risk-dao/a-complexity-measure-for-smart-contracts-13fa5aed5572?source=rss-f9716a559e68------2</link>
            <guid isPermaLink="false">https://medium.com/p/13fa5aed5572</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Yaron Velner]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 12:00:53 GMT</pubDate>
            <atom:updated>2023-10-17T12:00:53.819Z</atom:updated>
            <content:encoded><![CDATA[<p>Measuring the complexity of a computer software can predict the expected testing and maintenance costs, as well as the likelihood for bugs.</p><p>McCabe’s Cyclomatic complexity is the most popular complexity measure among industrial software analysis tools. It measures the number of different paths in a software code (formally, the number of linearly independent paths). Having path testing in mind, this metric fully predicts the amount of such tests that will be required for a standard program.</p><p>For smart contracts, however, testing is only part of the quality assurance process. Having complex interactions with external contracts and storage dictates a manual review process that takes into account all the possible different interactions. Hence, we propose a new complexity measure, namely, the smart contract cyclomatic complexity. This complexity counts the number of different paths that triggers a change in the blockchain state (e.g., write to storage, send ETH, or perform state changing external calls).</p><p>In this research, we give a formal definition for the cyclomatic complexity of smart contracts, we implement an open source tool, on top of the <a href="https://github.com/Ackee-Blockchain/woke">woke framework</a> to automatically calculate the complexity of a single smart contract, and we run the tool on MakerDAO’s dss system.</p><h3>Formal definition</h3><h4>Control flow graph</h4><p>A control-flow graph (CFG) is a representation, using graph notation, of all paths that might be traversed through a program during its execution.</p><p>Below is an example of a solidity function, and the control flow graph that woke generated for it.</p><pre>function abs(uint a, uint b) public returns(uint) {<br>  uint result;<br>  if(a &gt; b) {<br>    result = a - b;<br>  else {<br>    result = b- a;<br>  }<br><br>  return result;<br>}     </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*USNfAftbbzkaeweC" /><figcaption>A control flow graph</figcaption></figure><p>To analyse a full contract, we add an auxiliary root node, with an edge to the entry node of every external and public function. In addition, we also connect the function calls with their respective entry nodes.</p><h4>Linearly independent paths</h4><p>The set of all linearly independent paths is the maximal set of program execution paths (w.r.t inclusion) such that in every path there is one edge that does not occur in any of the other paths.</p><p>For the purpose of smart contract complexity, we extend this definition, and define the <strong>set of linearly independent paths w.r.t blockchain state changes</strong>. This is defined as the maximal set of runs such that in every run there is one blockchain state change that does not occur in any of the other paths.</p><h4>Smart cyclomatic complexity</h4><p>The smart cyclomatic complexity of a section of source code is the number of linearly independent paths w.r.t blockchain state changes within it.</p><h3>Implementation</h3><p>We implemented a printer to the <a href="https://github.com/Ackee-Blockchain/woke">woke static analysis framework</a>. Our code is available <a href="https://gist.github.com/yaronvel/1202bc94935afdd267e026a468adfe0b">here</a>. We thank our friends from the <a href="https://t.me/wokegroup">woke telegram group</a> for their great technical support and walkthrough.</p><h3>Experimental results</h3><p>We ran our analysis on MakerDAO’s core smart contracts (dss), on each contract separately. The dss consists of 15 smart contracts, and can be found <a href="https://github.com/makerdao/dss/tree/master/src">here</a>.</p><p>For each contract, we plotted the full control graph. The entry node is labelled in green, and state changing nodes are labelled in red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*Xgiy8Xhf4N9iATBc" /><figcaption>The full control flow graph of jug.sol</figcaption></figure><p>We then stripped away all the non state changing nodes that do not contain any branching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*1FtftGMm3l5ZZn2r" /><figcaption>A control flow graph of jug.sol, after stripping away all nodes that do not change blockchain states.</figcaption></figure><p>We calculate the cyclomatic complexity for both graphs, and get the classic and smart cyclomatic complexities.</p><p>The results are depicted in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*VYaClU2IXmutqcsQW1aiEw.png" /></figure><p>The <strong>jug</strong> smart contract has the lowest ratio between smart and classic complexity. This is because it contains very little logic other than a complex function for exponent calculation. This function contains a lot of branching statements, however it is a pure function that does not change any state.</p><p>Another interesting observation is that the <strong>clip</strong> and <strong>end</strong> contracts complexity is significantly higher than the one of the <strong>vat</strong>, despite having similar classic complexity. And indeed, few bugs were already <a href="http://forum.makerdao.com/t/overlooked-vectors-for-post-shutdown-governance-attacks-postmortem/20696">detected</a> (and patched) in the end contract, and the <strong>clip</strong> contract is a fix to the old MakerDAO’s liquidation mechanism, which was deprecated due to an economical bug. This is in sharp contrast to the <strong>vat</strong> contract that is live since the inception of DAI 2.0, and never had any significant issues.</p><h3>About Risk DAO</h3><p>Risk DAO is a service DAO focused on providing a new, open-source risk assessment framework, associated audits, and dashboards to stress test, monitor, and manage risk in DeFi lending and borrowing protocols as well as L1 and L2 networks.</p><p>You can follow us on Twitter <a href="https://twitter.com/Risk_DAO">here</a>. You can join our Discord <a href="https://discord.com/invite/NYyeDQDDvM">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13fa5aed5572" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risk-dao/a-complexity-measure-for-smart-contracts-13fa5aed5572">A complexity measure for smart contracts</a> was originally published in <a href="https://medium.com/risk-dao">Risk DAO</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Smart Contract Formula for LTV ratio]]></title>
            <link>https://medium.com/risk-dao/a-smart-contract-formula-for-ltv-ratio-a60a8373d54d?source=rss-f9716a559e68------2</link>
            <guid isPermaLink="false">https://medium.com/p/a60a8373d54d</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[risk-assessment]]></category>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Yaron Velner]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 13:34:57 GMT</pubDate>
            <atom:updated>2023-06-04T13:34:57.002Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Determining the correct Loan-To-Value (LTV) of a collateral asset is crucial to balance the loan’s default risk and the usability of the lending platform.</p><p>This is done by running excessive daily simulations and integrating a domain specific knowledge.</p><p>In a new <a href="https://github.com/Risk-DAO/Reports/blob/main/a-smart-contract-ltv-formula.pdf">research paper</a>, we try to find a simple “Uniswap-like” formula for the LTV ratio. We present a simple formula that can be calculated by a smart contract (e.g., when coupled with B.Protocol’s planned on-chain data oracle).</p><p>With the formula, one has to decide on a value of a Confidence level, instead of a value to the LTV. This process is more efficient as once the level is selected, the LTV ratio could change automatically based on the market conditions (volatility and liquidity).</p><p>Moreover, once such data is available on-chain (e.g., via B.Protocol oracle), it will be possible for a smart contract to automatically decide on the LTV ratio of assets, and change it dynamically over time. Hence, the formula can reduce a lot of future decision making overhead, and give rise to a more automated and permissionless lending market.</p><p>The formula can also be used as a ranking formula, comparing the different risks between different configurations and platforms. For example, a new platform can estimate the average confidence level of an existing project, and decide if they want to take similar or different risks with their assets. Existing platforms can give more transparency to their community about which asset configurations are currently less or more risky.</p><p>In the full paper we analyze the confidence level of the assets in Compound III USDC market.</p><h3>The formula</h3><p>Aiming for the simplest possible formula, we abstract smart contract security considerations, and assumptions on user behaviour. However, as mentioned above, formula has an adjustable confidence parameter that could compensate for these aspects.</p><p>At the core level, the goal of setting an LTV ratio that is smaller than 1, is to compensate for the potential price decrease during the liquidation process (which need not be in a single tx, and could take time).</p><p>For this purpose, we aim to answer the following question:</p><blockquote>How much will the price decrease before a liquidation is fully executed?</blockquote><p>This is a very open ended question, as even the size of the liquidation is unknown.</p><p>For this purpose, we make the following three assumptions:</p><ol><li>There is a discrete basic time unit, and the price follows a log-normal random walk distribution. We note that in particular, there is an implicit assumption that a liquidation will not change the price of the asset, however, a different assumption could potentially be embedded at the confidence level factor.</li><li><strong>DEX liquidity.</strong> We define liquidity as the total quantity that is available for sale with a given price slippage. We assume that every time the liquidity is depleted, it will be fully restored after a constant time interval T. This can be justified, e.g., by traders/bots arbitraging the existing DEX liquidity with Binance orderbook, and/or for additional liquidity to come from another chain (if the lending market is on an L2). As usual, the confidence parameter will also embed the confidence in this assumption.</li><li><strong>Liquidation sizes</strong>. The size of liquidation that a lending market should be prepared for, is proportional to the total debt in the system. We note that in practice, the current user account composition also has a great effect on this parameter, however, as a design choice, we chose to abstract away the current user composition.</li></ol><p>Given the above assumptions, the proposed formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*NI_JiFMnGAxK18eik6-ezQ.png" /></figure><p>Where:</p><ul><li>σ is the price volatility between the collateral and debt asset (normalized to the base asset price).</li><li>β is the liquidation bonus.</li><li>ℓ is the available dex liquidity with a slippage of β.</li><li>d is the borrow cap of the debt asset.</li><li>c is a confidence level factor. The higher c is, the odds for insolvency are decreasing.</li></ul><p>We prove the correctness of the formula in the paper.</p><h3>Experimental results</h3><p>99.9\% of all DeFi liquidations are executed in a single transaction. And thus we take real liquidation data from Binance Futures ETH-USD pair. In order to test different volatility levels, we amplify the price changes and multiply them by a stretching constant that ranges between 0 and 2.</p><p>The most synthetic part in our experiments is the behavior of DEX liquidity. We follow the formula assumption that there is a fixed DEX liquidity size, which is restored every 30 minutes.</p><p>We take the 3 worst months (in terms of liquidations) in the history of Binance Futures, namely, January 2020, March 2020 and February 2021.</p><p>Having price trajectory and liquidation time and sizes in hand, we simulate the DEX liquidity, and the behavior of the liquidators. And keep track of the maximum price drop of an open liquidation.</p><p>The results are depicted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*D8UkA80Lq3iYAY63S_O69w.png" /><figcaption>Comparison of simulation results and the results of the formula. For x=0.2, we take all the input parameters for which the simulated max price decrease (max drop) is 0.2, and then plot, in the y axis, the different results and formula give. The red line draws the ideal outcome, i.e., an y=x curve, where the formula returns exactly the same results as the simulation. The R² score is calculated w.r.t the red line.</figcaption></figure><h3>About Risk DAO</h3><p>Risk DAO is a service DAO focused on providing a new, open-source risk assessment framework, associated audits, and dashboards to stress test, monitor, and manage risk in DeFi lending and borrowing protocols as well as L1 and L2 networks.</p><p>You can follow us on Twitter <a href="https://twitter.com/Risk_DAO">here</a>. You can join our Discord <a href="https://discord.com/invite/NYyeDQDDvM">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a60a8373d54d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risk-dao/a-smart-contract-formula-for-ltv-ratio-a60a8373d54d">A Smart Contract Formula for LTV ratio</a> was originally published in <a href="https://medium.com/risk-dao">Risk DAO</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking the Curve: The Impact of Stablecoin Depegging on Liquidity and Liquidations]]></title>
            <link>https://medium.com/risk-dao/breaking-the-curve-the-impact-of-stablecoin-depegging-on-liquidity-and-liquidations-fed0cda8c664?source=rss-f9716a559e68------2</link>
            <guid isPermaLink="false">https://medium.com/p/fed0cda8c664</guid>
            <category><![CDATA[curve-finance]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Yaron Velner]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 20:23:03 GMT</pubDate>
            <atom:updated>2023-03-22T20:54:20.367Z</atom:updated>
            <content:encoded><![CDATA[<p>Stable coin liquidity heavily relies on the properties of Curve Finance’s stable swap formula. We ran our simulation model for liquidations of stable assets, and visualised how the curve inventory size, and the re-pegging velocity affects the ability to liquidate.</p><p>We consider an abstract setup, where a generic (imaginary) stable coin, namely USDX, is traded vs USDC on Curve, and a generic lending market lets users borrow USDX against an ETH collateral. Further, the system always prices USDX at $1. This framework is applicable, e.g., to LUSD, MIM, and to some extent also DAI. The simulation could also handle floating oracle price (i.e., not always $1), but in this case, further assumptions on how quickly the oracle is being updated are needed.</p><p>During a liquidation process, USDX is supplied in return to ETH collateral, and then the liquidator immediately sells the ETH back to USDX. The ETH to USDX sale is typically done by first selling ETH to USDC, say on Uniswap, and then selling USDC to USDX on a Curve.</p><p>We assume a liquidation bonus of 10%, and thus, the liquidator can execute the liquidation if and only if she can sell on Uniswap and Curve with an aggregated slippage of 10% (technically, the price of the last wei should not be lower by more than 10% from the oracle price).</p><h3>Simulation run</h3><p>In a run, we plot:</p><ol><li>Price trajectory (in red)</li><li>Liquidation sequence (blue)</li><li>Open liquidations (yellow)</li><li>The price in Curve (green)</li><li>The Curve USDX balance (purple)</li><li>The total liquidity that is available for ETH to USDX liquidations (black)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pU-XHGvn-KqUFdV6" /></figure><p>In a liquidation, the liquidator has to buy USDX, and therefore it immediately increases the price on Curve. However, when USDX is traded above $1, it is unclear how long it will take to re-peg. In the absence of any physical constraints (e.g., DAI’s PSM), we observed that it could historically take days and even weeks (e.g., LUSD).</p><p>We assume an exponential decay model, where the Curve imbalance is slowly decaying with a half life period of X days, i.e., after X days, it will be halved (assuming no further liquidations).</p><p>In the above simulation, the first few simulations decreased the USDX balance in Curve, but did not have a big impact on the price. Hence, the available liquidity for liquidations was still dominated by the USDC/ETH liquidity. However, additional liquidations occurred before the Curve balance retained to normal ratio. And the later liquidations choked the Curve pool, and effectively drained the available liquidity.</p><p>In the simulation depicted below, we double the half life parameter, namely, the price recovery time is slower</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/0*YviM5dFX7YUsJIQ-" /></figure><p>Now we see that the price does not re-peg until the end of the simulation, and as a result, some of the liquidations remain open until the end of the simulation.</p><p>Finally, we ran the simulation with double the amount of Curve balance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wYkfoCltAP569PNG" /></figure><p>In this scenario, all the liquidations are handled in a timely manner, and the price of USDX never exceeds 1.05.</p><h3>About Risk DAO</h3><p>Risk DAO is a service DAO focused on providing a new, open-source risk assessment framework, associated audits, and dashboards to stress test, monitor, and manage risk in DeFi lending and borrowing protocols as well as L1 and L2 networks.</p><p>You can follow us on Twitter <a href="https://twitter.com/Risk_DAO">here</a>. You can join our Discord <a href="https://discord.com/invite/NYyeDQDDvM">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fed0cda8c664" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risk-dao/breaking-the-curve-the-impact-of-stablecoin-depegging-on-liquidity-and-liquidations-fed0cda8c664">Breaking the Curve: The Impact of Stablecoin Depegging on Liquidity and Liquidations</a> was originally published in <a href="https://medium.com/risk-dao">Risk DAO</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Case for an On-Chain Risk Oracle]]></title>
            <link>https://medium.com/b-protocol/the-case-for-an-on-chain-risk-oracle-a5a44bf9048b?source=rss-f9716a559e68------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5a44bf9048b</guid>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Yaron Velner]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 09:54:11 GMT</pubDate>
            <atom:updated>2022-12-28T14:15:53.878Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>DeFi has seen tremendous growth in recent years, with billions of dollars in assets being locked into various DeFi platforms. However, to date, those billions of dollars risk management is somewhat opaque and the managing platform has a clear conflict of interest between its risk exposure and the growth of the platform.</p><p>To address this need, our community <a href="https://forum.bprotocol.org/discussion/8601-lets-build-an-onchain-risk-oracle-for-defi">has proposed</a> to develop an on-chain risk oracle. Such oracles could provide objective pieces of information in a transparent and decentralised manner. With that in hand, smart contract devs could use it in their dapps and mitigate conflict of interest concerns, growing trust among their user base.</p><p>B.Protocol has been building risk mitigation tools for over two years, and works closely with numerous DeFi platforms. Leading an initiative for a new on-chain risk oracle DeFi primitive seemed like a natural next step on our roadmap.</p><p>In this post, we will explain what the Risk Oracle is, why it is important for DeFi to have an on-chain risk feed, how the Risk Oracle is designed, and who could benefit from it.</p><h3>The need for an on-chain risk oracle</h3><p>DeFi platforms manage billions of dollars in user funds. In most cases, e.g, lending markets and yield aggregators, the protocol owners (a DAO or a multisig) have the authority to use or lend the funds in order to generate yield. This gives rise to the following issues:</p><ol><li>The platforms might decide to take an excessive risk in order to increase the user and /or the platform’s yield. A yield aggregator might deposit user funds into risky platforms, a lending market might decide to list a risky asset due to high demand, etc.</li><li>The need for users to trust the platform’s risk management creates an entry barrier for new teams and DAOs, and leads to inefficient markets. Since it takes a long time for teams to build trust in their risk management capabilities and the robustness of their DAO in making the right decisions, users will favour lower yield (or higher fee) platforms that are more reputable.</li><li>The platform’s risk mitigation actions (e.g., delisting a risky asset due to changes in market conditions) are typically guarded by timelock and a tedious governance process which prevents taking action in a timely manner, though these actions are often time sensitive. .</li></ol><p><strong>An on-chain risk oracle can help mitigate the above concerns.</strong></p><p>By integrating a risk feed into its protocol, a yield aggregator platform can verify to its users, by code, that a specific strategy is limited to deploying capital only in protocols and assets with a minimum pre-defined risk rating. This can help users choose strategies that align with their risk appetite and help align ROI expectations, as well as to adjust the risk of losses due to unexpected events or changes in market or platform conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlQuX4bXUb7xF89qdoP8JQ.png" /></figure><p>For example, a user who is comfortable with higher levels of risk may choose a strategy that deploys capital into lending protocols which provide higher APYs but with a lower risk rating (e.g. rated B rather than AA), while a user who is more risk-averse may choose a strategy that deploys capital into protocols with a stronger risk rating but lower APYs.</p><p>By using an on-chain risk oracle, the yield aggregator smart contract can verify the risk rating of the protocols or assets that are included in the strategy, and can even be coded to pull out funds and deploy them into another platform in case the platform’s rating is suddenly dropped due to changes in market or platform conditions.</p><p>Other use cases for an on-chain risk oracle can be</p><ul><li>A lending market that codes a restriction that prevents it from listing a new risky (volatile) asset;</li><li>DAOs that enforce their treasury managers through smart contracts to invest only in platforms that meet their risk appetite;</li><li>Lending platforms that can automatically set their reserve rates (fees) dynamically according to risk rating changes.</li></ul><p>Other use cases that will be revealed with time.</p><h3>Oracle architecture</h3><p>In order for the risk oracle to be decentralised and transparent, it should use an open source code whose output can be verified by anyone who wishes to run them. Such a risk framework is the one published by <a href="https://github.com/Risk-DAO">RiskDAO</a>, which is suggested to be the first framework to be used by the risk oracle, though we anticipate more risk frameworks will join as open source data providers to the oracle as the network grows.</p><p>A network of independent validators will run the required software to provide risk ratings according to a set of pre-decided risk parameters, and the consensus result will be published on-chain by the oracle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*ZRZIC2aIIAdY7lS-" /><figcaption><strong>Risk Oracle High-Level Design</strong></figcaption></figure><p>To ensure the integrity of the process and align the incentives of the validators, the risk oracle would implement a staking and slashing mechanism. Validators will be required to stake tokens, and in the event that their result deviates too much from other validators, their staked tokens will be slashed and distributed as rewards pro rata to other validators and network participants. Fees can be collected for reading the risk oracle feed (might be subsidized during initial stages to drive more traction), and other incentives might be proposed upon launch.</p><h3>Oracle feed examples</h3><p>The initial set of objective risk parameters that can be used to assess the risk of lending platforms is as follow:</p><ol><li><strong>Liquidations at risk</strong> (normalized by TVL): This metric reflects liquidated positions the lending platform would process in a Worst Day simulation. Worst Day simulates the current state of the platform during the biggest price drop in ETH history, normalizing other assets according to their volatility w.r.t ETH.</li><li><strong>Existing bad debt</strong> in the platform: Some platforms operate with existing bad debt that was accrued historically through hacks or exploits, but many times is not published publicly.</li><li><strong>Risky tokens</strong> listed on the platform: This metric considers the on-chain liquidity and the volatility of risky tokens listed on the platform as they can impose risk contagion.</li><li><strong>Borrowing and lending caps</strong>: This metric considers whether the platform has borrowing or lending caps, and how high or low these caps are set, w.r.t. Market liquidity and other factors.</li><li><strong>Smart contract updates</strong>: This metric tracks when the platform’s smart contracts were last changed and whether there are any planned or forecasted updates in the near future. Recently updated contracts can impose a higher risk exposure as the new contracts are yet to be battle tested.</li><li><strong>Price oracles</strong>: This metric considers the price feeds used by the platform, including their stability and trustworthiness.</li></ol><p>More parameters can be added and others can be replaced as the system matures.</p><h3>Another lego piece for making DeFi platforms more robust</h3><p>The idea of a new DeFi primitive that publishes risk rating on-chain doesn’t come from a void. <a href="https://www.bprotocol.org/">B.Protocol</a> community was founded in mid 2020 (after “Black Thursday” events) with one main goal — providing safer ways for the DeFi ecosystem to scale. The core values we stick to are keeping everything we build open-sourced and decentralized, aiming to drive more traction into the ecosystem by providing new and innovative risk-mitigating DeFi primitives others can build on.</p><p>Since then we have released our <a href="https://app.bprotocol.org/">Backstop</a> product, a robust liquidation engine that enables lending platforms to better secure their lenders’ funds, minimize the potential of accruing bad debt in the protocol, and facilitate better capital efficiency for borrowers — and doing all that while letting their users gain from liquidating unsafe positions from the platform. At the peak of the last bull market, the Backstop was trusted with over $300m of Backstoppers’ funds, coming from private users, funds, and DAOs.</p><p>After the Luna/UST crash, and from our experience talking with dozens of lending platforms, we realized there is a lack of knowledge and open-source tools for proper economic risk management. As a result, we launched <a href="https://twitter.com/Risk_DAO">RiskDAO</a> together with 1kx research arm and other researchers and devs.</p><p>RiskDAO is dedicated to providing open-source tools, dashboards, and monitoring systems that give better transparency into lending platforms, stablecoins, and alt-L1s and L2 networks. By running simulations of tens of thousands of data points, RiskDAO provides real-time information and recommendations that help to set and manage better risk factors in the platforms that use its services. RiskDAO also provides some of its tools as public goods for anyone to use, such as the <a href="https://bad-debt.riskdao.org/">Bad Debt Dashboard</a>.</p><p>We encourage discussions and feedback from the community on this new concept of an on-chain risk rating oracle, which can be made on the B.Protocol <a href="https://discord.gg/bJ4guuw">Discord</a>.</p><h3>Conclusion</h3><p>The on-chain Risk Oracle is an important new DeFi primitive that aims to provide a way for devs to integrate the risks associated with DeFi into their protocol’s smart contracts. By using it, protocols can build risk-informed solutions that can scale safely and maintain user trust.</p><p>We are excited to see how the risk oracle will be used in the DeFi ecosystem and encourage readers to learn more about it by joining the B.Protocol community on <a href="https://discord.gg/bJ4guuw"><strong>Discord</strong></a> for discussions and feedback. If you are interested in staying updated on the progress of RO and our future plans, be sure to follow us on <a href="https://twitter.com/bprotocoleth">Twitter</a> and subscribe to our <a href="https://defilending.substack.com/">State of DeFi Lending newsletter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5a44bf9048b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/b-protocol/the-case-for-an-on-chain-risk-oracle-a5a44bf9048b">The Case for an On-Chain Risk Oracle</a> was originally published in <a href="https://medium.com/b-protocol">B.Protocol</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximizing Your Interest: The Key to Optimal Rates is Total Borrowing Size]]></title>
            <link>https://medium.com/risk-dao/maximizing-your-interest-the-key-to-optimal-rates-is-total-borrowing-size-27bc29c64e39?source=rss-f9716a559e68------2</link>
            <guid isPermaLink="false">https://medium.com/p/27bc29c64e39</guid>
            <category><![CDATA[interest-rates]]></category>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Yaron Velner]]></dc:creator>
            <pubDate>Mon, 19 Dec 2022 11:33:47 GMT</pubDate>
            <atom:updated>2022-12-19T11:33:47.078Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Tldr: In a </strong><a href="https://github.com/Risk-DAO/Reports/blob/main/Interest%20rate%20optimization.pdf"><strong>new research paper</strong></a><strong>,</strong> <strong>we show that current interest rate curves are not suitable for optimising lending market KPIs such as revenue and TVL, and suggest new forms of curves that are likely to do a better job.</strong></p><p>Since on-chain order books are infeasible, DeFi lending markets decide on the borrower interest rate according to the <em>utilization ratio</em> between total supply (deposits) and total borrowing (debt). By doing so they hope to reflect the market demand curve (similar to how DEX AMMs work) and to mitigate high utilization ratio.</p><p>Having optimal utilization ratio in mind, they set an interest rate curve hoping that with this curve the market will converge to the optimal utilization. In practice, as there are many unknowns, this approach does not result in optimal utilization ratio. In a <a href="https://github.com/Risk-DAO/Reports/blob/main/Interest%20rate%20optimization.pdf">new research paper</a>, we show that even in theory this approach is not optimal, and suggest that the interest rate should be either a constant number or a function that depends on the total borrowing size, and should depend on utilization only once it exceeds the optimal utilization ratio.</p><h3>Lending market KPIs</h3><p>Lending markets aim to maximize their revenues and minimize their risk. Another key metric that is important for visibility and growth is to increase the market TVL (and here we define the TVL as the total amount of deposits).</p><p>In the context of interest rate curves, risk may arise when the market utilization is very high, and this can be mitigated by setting up a very high interest rate when the utilization is too high. Hence, for the rest of the blog post we focus only on revenues and TVL.</p><p>It is an easy observation that the amount of deposits is expected to increase as the suppliers interest rate goes up. Furthermore, the protocol revenues are taken as a fee on the supplier interest rate. Hence, maximizing the supplier interest rate will optimize both the protocol revenues and TVL, and therefore it should be the main objective when setting up an interest rate curve.</p><p>In the paper we prove that this goal is equivalent to maximizing the multiplication of total borrowing size with the borrowing interest rate.</p><p>We say that an interest rate is optimal, if it maximizes the above.</p><h3>Theoretical model</h3><p>We assume that the demand for supply and borrow depends on the supplier and borrower interest rate. And show that if these demands can be approximated by two linear functions (one for supply and one for borrow) then the optimal interest rate is obtained when the demand for borrow is half the demand that exists when interest rate is 0.</p><p>We show that setting up a constant interest rate function that is optimal requires less information about the supply and borrow demand functions, in comparison to a linear interest rate curve that depends on the utilization. We further show that if the interest rate function depends on the total borrowing size, then even less information is needed.</p><p>We show that some of the conclusions hold even if the supply and borrow demand functions are non linear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/0*rft3cAxvO-IOzvDr" /><figcaption>The convergence of supply (green dots) and borrow (red dots) given demand functions and interest rate function</figcaption></figure><h3>Practical implications</h3><p>Platforms rarely have full information about their users’ demand function. Hence, we cannot prove that our model strictly outperforms current practices.</p><p>However, we believe that current practices that aim to optimize utilization, rather than key metrics such as revenue and growth (TVL) are arbitrary at best.</p><p>In addition, our approach requires platforms to reason only about how borrowers would behave, while the current practice requires them to have information on both suppliers and borrowers behaviour.</p><h3>About Risk DAO</h3><p>Risk DAO is a service DAO focused on providing a new, open-source risk assessment framework, associated audits, and dashboards to stress test, monitor, and manage risk in DeFi lending and borrowing protocols as well as L1 and L2 networks.</p><p>You can follow us on Twitter <a href="https://twitter.com/Risk_DAO">here</a>. You can join our Discord <a href="https://discord.com/invite/NYyeDQDDvM">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27bc29c64e39" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risk-dao/maximizing-your-interest-the-key-to-optimal-rates-is-total-borrowing-size-27bc29c64e39">Maximizing Your Interest: The Key to Optimal Rates is Total Borrowing Size</a> was originally published in <a href="https://medium.com/risk-dao">Risk DAO</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Could Drain an Entire Blockchain: Post Mortem on a Bug in Godwoken Chain]]></title>
            <link>https://medium.com/risk-dao/how-i-could-drain-an-entire-blockchain-post-mortem-on-a-bug-in-godwoken-chain-2451f83f72d2?source=rss-f9716a559e68------2</link>
            <guid isPermaLink="false">https://medium.com/p/2451f83f72d2</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[risk]]></category>
            <category><![CDATA[bug-disclosure]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Yaron Velner]]></dc:creator>
            <pubDate>Wed, 16 Nov 2022 15:16:46 GMT</pubDate>
            <atom:updated>2022-11-16T15:16:46.021Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3ByCg8yd3_0xOi4J" /></figure><p>Last month, I accidentally found that it is possible to undo the effect of EVM reverts in the Godwoken blockchain. This would allow me to flash loan its entire local DEX TVL without paying it back, and effectively drain the entire $7m TVL of the Godwoken chain.</p><p>I immediately reported the issue to the Godwoken team, the bug was quickly patched, and a bug bounty was awarded. In this post, we describe the chain of events that led to the discovery of the bug. We illustrate how it could have been exploited, and how it was quickly patched.</p><h3>Timeline</h3><p>The events took place at the date of 18/10/2022, while I was debugging the integration of B.Protocol with the Hadouken Finance lending market.</p><p><strong>11:21:45 UTC</strong> I deployed a smart contract that would call B.Protocol liquidate function, and return a different value if the function reverts. The contract was executed, and it returned a value of 8.</p><pre>try yyy.liquidateBorrow{gas: gasLimit}(borrower, amount, collateral) {<br>  return 7;<br>}<br>catch {<br>  return 8;<br>}</pre><p><strong>12:43:29 UTC </strong>Hadouken Finance team made a direct call to B.Protocol smart contract and it reverted with error: <strong>“ReentrancyGuard: reentrant call”</strong>. This type of error suggested a potential bug in the reentrancy guard mechanism, however this piece of code was authored by open-zeppelin and it is extremely battle tested.</p><p><strong>13:48:00 UTC</strong> In an attempt to narrow down the complexity of the setup, I deployed two simple contracts, namely, <strong>DebugAAA</strong> and <strong>DebugBBB</strong>, depicted below:</p><pre>contract DebugAAA {<br>  uint public state = 1;<br>  function test() external {<br>    state = 2;<br>    revert();<br>  }<br>}</pre><pre>contract DebugBBB {<br>  function test(DebugAAA a) external returns(uint) {<br>   try a.test{gas: 100000}() {<br>     return 8;<br>   }<br>   catch {<br>     return 9;<br>   }<br>   }<br>}</pre><p>I deployed both contracts, and then called <strong>BBB.test(a)</strong>, and read <strong>a.state()</strong>, it returned a value of 2, which indicated that the effect of the <strong>revert</strong> function was cancelled.</p><pre>async function testAAA() {<br>  const a = await artifact.require(&quot;DebugAAA&quot;).new()<br>  const b = await artifact.require(&quot;DebugBBB&quot;).new()<br><br>  console.log((await a.state()).toString()) // 1<br>  <br>  await b.test(a.address)<br>  <br>  console.log((await a.state()).toString()) // 2<br>}</pre><p><strong>13:52:01 UTC</strong> I reported the findings to Godwoken devs.</p><p><strong>14:40:39 UTC </strong>Godwoken confirmed the bug.</p><p><strong>2022–10–19 14:19:19 UTC</strong> The bug was patched.</p><h3>Severity of the bug</h3><p>At the time of disclosure, the Godwoken chain had one popular dapp, namely Yokaiswap, with over $7m TVL (according to <a href="https://defillama.com/protocol/yokaiswap">DeFi Llama</a>). In addition, Hadouken Finance was about to launch its lending market on Godwoken.</p><p>Yokaiswap is a Uniswap v2 fork, and the Hadouken code is based on Aave v2. With the bug we found, it was possible to drain both of these dapps in the following way:</p><h3>Exploiting the bug to drain Uniswap v2 forks</h3><p>Uniswap v2’s <a href="https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2Pair.sol#L159">swap</a> function implements an exchange between <strong>tokenIn</strong> and <strong>tokenOut</strong>.</p><p>However, it first <a href="https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2Pair.sol#L170">transfers</a> the out token(s) to the user:</p><pre>170 if(amount0Out &gt; 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens<br>180 if(amount1Out &gt; 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens</pre><p>and only then it <a href="https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2Pair.sol#L182">verifies</a> the user transferred the in token(s) to the reserve:</p><pre>182 require(balance0Adjusted.mul(balance1Adjusted) &gt;= uint(_reserve0).mul(_reserve1).mul(1000**2), &#39;UniswapV2: K`);</pre><p>The following piece of code would drain the entire reserve balance.</p><pre>try uniReserve.swap(<br>  token0.balanceOf(address(uniReserve)),<br>  token1.balanceOf(address(uniReserve)),<br>  0xMe, bytes(0)<br>)</pre><p>Indeed in lines 170 and 171 (of the Uniswap code) the reserve will transfer its entire balance to the attacker. It will revert in line 182. However, due to the bug the state will not be reverted, and the attacker balance will contain the transferred tokens.</p><h3>Exploiting the bug to drain Aave v2 forks</h3><p>Aave v2 has a built-in flashloan function that could have been exploited in the same way as in the uniswap attack. However, this feature was disabled by Hadouken Finance. A different attack vector was to exploit the <a href="https://github.com/aave/protocol-v2/blob/master/contracts/protocol/lendingpool/LendingPool.sol#L236"><strong>repay</strong></a> function. Aave v2’s repay function only pulls the user funds at the <a href="https://github.com/aave/protocol-v2/blob/master/contracts/protocol/lendingpool/LendingPool.sol#L283">end</a> of the execution. After that it only does one additional call, namely, <a href="https://github.com/hadouken-project/lending-contracts/blob/d21b5be0e9a52a64513ef5d1afa500095eee0358/contracts/protocol/lendingpool/LendingPool.sol#L293"><strong>handleRepayment</strong></a>, however, this function has an empty logic. Hence, the repay function would revert only at the end of the execution, and thus, when wrapping it with a try/catch clause, it would still wipe the user’s debt.</p><p>The draining is completed by repeatedly borrowing more after each (fake) debt repay call.</p><h3>Patching the bug</h3><p>The root cause for the bug is that evmone (the EVM implementation Godwoken is using) requires the ‘host’ to revert the call failure (include logs, account state, and other state changes make inside the call), in the buggy version they ignored this mechanism (and assumed the evmone will do the reverting job between calls), and only handled the whole transaction level reverting.</p><p>In less than 24 hours after my initial report, the Godwoken dev team was able to find the root cause, and quickly <a href="https://github.com/godwokenrises/godwoken-polyjuice/compare/1.4.1...5f146f764067afb103f2ee9c7705e4a77e63beed">patched</a> it with a workaround that reverts the entire tx whenever an internal tx fails (and thus, effectively nullifies the try/catch sematics).</p><p>The team is working on a complete fix, which may come out in a few days:</p><ol><li>Design two Godwoken syscalls that help control the state revert logic.</li></ol><p>2. The two syscalls will be called around an inner EVM call if needed.</p><h3>About Risk DAO</h3><p>Risk DAO is a service DAO focused on providing a new, open-source risk assessment framework, associated audits, and dashboards to stress test, monitor, and manage risk in DeFi lending and borrowing protocols as well as L1 and L2 networks.</p><p>You can follow us on Twitter <a href="https://twitter.com/Risk_DAO">here</a>. You can join our Discord <a href="https://discord.com/invite/NYyeDQDDvM">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2451f83f72d2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risk-dao/how-i-could-drain-an-entire-blockchain-post-mortem-on-a-bug-in-godwoken-chain-2451f83f72d2">How I Could Drain an Entire Blockchain: Post Mortem on a Bug in Godwoken Chain</a> was originally published in <a href="https://medium.com/risk-dao">Risk DAO</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arbitraging Chicken Bonds’ Stability Pool for Fun and Profit]]></title>
            <link>https://medium.com/b-protocol/arbitraging-chicken-bonds-stability-pool-for-fun-and-profit-e640ae51a76f?source=rss-f9716a559e68------2</link>
            <guid isPermaLink="false">https://medium.com/p/e640ae51a76f</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Yaron Velner]]></dc:creator>
            <pubDate>Wed, 09 Nov 2022 18:03:09 GMT</pubDate>
            <atom:updated>2022-11-09T18:03:09.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/434/0*1JiROo5OgXBP9OwY" /></figure><p>The Chicken Bonds protocol integrated B.Protocol’s Backstop Automated Market Maker (B.AMM) to manage its LUSD stability pool deposits. The motivation for the integration is two-folds. First: the B.AMM increases the stability pool capital efficiency and can support higher liquidation volume over time (e.g., see <a href="https://medium.com/risk-dao/analyzing-and-modeling-stability-pool-dynamics-b9161b3776f8">here</a>). Second: The B.AMM auto-compounds the liquidation proceeds and the LQTY rewards, and offloads these core algorithmic components from the Chicken Bonds protocol.</p><p>At its core, the auto-compounding process relies on arbitrage bots who supply LUSD in return for a discounted price ETH or LQTY.</p><p>In this post, we explain how bots could arbitrage the B.AMM, and present an open source smart contract to facilitate such an arbitrage.</p><h3>Buying discounted ETH</h3><p>Every liquidation in the Liquity protocol takes some LUSD from the stability pool, and gives some ETH in return. The B.AMM offers the ETH for sale, in return to LUSD. The ETH is offered with a varying discount over chainlink market price, where the discount depends on the quantity of ETH that is available for sale. The bigger the quantity is, the higher the discount. The reader can find more technical details on the discount formula <a href="https://docs.bprotocol.org/technical-documentation/v2">here</a>.</p><h4>How to arbitrage?</h4><p>B.AMM address (Ethereum mainnet):</p><ul><li>Chicken bonds’ B.AMM: <a href="https://etherscan.io/address/0x896d8a30C32eAd64f2e1195C2C8E0932Be7Dc20B">0x896d8a30C32eAd64f2e1195C2C8E0932Be7Dc20B</a></li><li>Classic B.AMM: <a href="https://etherscan.io/address/0x00FF66AB8699AAfa050EE5EF5041D1503aa0849a">0x00FF66AB8699AAfa050EE5EF5041D1503aa0849a</a></li></ul><p>Price query function: <strong>getSwapEthAmount(uint lusdQty)</strong></p><p>Swap function: <strong>swap(uint lusdAmount, uint minEthReturn, address dest)</strong></p><p>Arbitrage bot smart contract reference:</p><ul><li>Deployed address: <a href="https://etherscan.io/address/0x12c60B3170Fb43E6A8f8ba2d843621c19324329E">0x12c60B3170Fb43E6A8f8ba2d843621c19324329E</a></li><li>Arbitrage function: <strong>swap(uint ethQty, address bamm)</strong></li><li><strong>ethQty</strong>: the amount of ETH to buy in the arbitrage</li><li><strong>bamm</strong>: the B.AMM address that is used in the arbitrage</li></ul><p>A potential backend implementation would be to call the swap function offchain with various sizes, and to execute a tx when it is not expected to revert. The backend can also be implemented with <a href="https://app.gelato.network/">Gelato</a>.</p><h3>Buying discounted LQTY</h3><p>For long durations, the amount of ETH liquidations is typically much bigger than the amount of LQTY yield. However, the LQTY yield stream is more continuous, and thus an arbitrage is expected to be executed multiple times per week.</p><p>The B.AMM sells the LQTY according to a 24 hours Uniswap TWAP oracle. And thus, arbitrage prices are expected whenever the 24 hours TWAP price is lower than the current LQTY price.</p><h4>How to arbitrage?</h4><p>LQTY seller address (Ethereum mainnet):</p><ul><li>The LQTY seller address may change over time. It can be fetched from the <a href="https://etherscan.io/address/0x896d8a30C32eAd64f2e1195C2C8E0932Be7Dc20B">Chicken bonds’ B.AMM</a> by calling the <strong>gemSeller() </strong>function. At the time of writing, the current LQTY seller address is <a href="https://etherscan.io/address/0x7605aaA45344F91315E0C596Ab679159784F8b7b">0x7605aaA45344F91315E0C596Ab679159784F8b7b</a></li><li>The Classic B.AMM does not sell its LQTY.</li></ul><p>Price query function: <strong>getSwapGemAmount(uint lusdQty)</strong></p><p>Swap function: <strong>swap(uint lusdAmount, uint minGemReturn, address dest)</strong></p><p>Arbitrage bot smart contract reference:</p><ul><li>Deployed address: <a href="https://etherscan.io/address/0xf9a0e641c98f964b1c732661fab9d5b96af28d49">0xf9a0e641c98f964b1c732661fab9d5b96af28d49</a></li><li>Arbitrage function: <strong>swap(uint lqtyQty, address reserve, address lqtyDest, uint minLqtyProfit)</strong></li><li><strong>lqtyQty</strong>: the amount of LQTY to buy in the arbitrage</li><li><strong>reserve</strong>: should be set to 0x4f73ad319193320ED20eeFAEFb8F30B89b05b8B6</li><li><strong>lqtyDest</strong>: the arbitrage generates LQTY profit, and sends the excess LQTY to the specified address</li><li><strong>minLqtyProfit</strong>: the minimum acceptable arbitrage profit</li></ul><p>A potential backend implementation would be to call the swap function offchain with various sizes, and to execute a tx when it is not expected to revert. The backend can also be implemented with <a href="https://app.gelato.network/">Gelato</a>.</p><h3>Tips and Tricks</h3><p>The reference arbitrage bot is suboptimal in (at least) two aspects:</p><ol><li>It buys LUSD with USDT or USDC only on Curve Finance, and ignores other LUSD liquidity sources, such as Uniswap v3.</li><li>It sells LQTY only to ETH, and ignores other liquidity sources, e.g., LQTY/WBTC reserves on uniswap.</li></ol><p>Improving the above, could improve both the gas consumption and the trade profitability.</p><h3>Disclaimer</h3><p>The reference bot code comes with no warranty. Using the bots does not require any funds, however gas fees could be lost in the event of unsuccessful arbitrage. Users should set reasonable gas prices when using the bots.</p><h3>About B.Protocol</h3><p>B.Protocol is building a Backstop DeFi primitive, unlocking higher capital efficiency in the ecosystem. By democratizing liquidation systems it shifts MEV and bot profits to the hands of the community.</p><p>Lending platforms that integrate with B.Protocol democratize their liquidation system, provide a stronger safety net to their lenders, and enable higher collateral factors for its borrowers.</p><p>With B.Protocol, anyone can participate in the lucrative business of liquidations, tapping into the $1B/Year market of DeFi liquidations, on its growth path to the $100B/Year of liquidations made in CeFi.</p><p><a href="https://bprotocol.org/">Website</a>,<a href="https://docs.bprotocol.org/"> Docs</a>,<a href="https://discord.com/invite/bJ4guuw"> Discord</a>,<a href="https://twitter.com/bprotocoleth"> Twitter</a>,<a href="https://www.youtube.com/channel/UC-CnO7vIZrGd6HgIw0U0mIQ"> YouTube</a>,<a href="https://www.reddit.com/r/bprotocol/"> Reddit</a>,<a href="https://forum.bprotocol.org/"> Forum</a>,<a href="https://github.com/backstop-protocol"> GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e640ae51a76f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/b-protocol/arbitraging-chicken-bonds-stability-pool-for-fun-and-profit-e640ae51a76f">Arbitraging Chicken Bonds’ Stability Pool for Fun and Profit</a> was originally published in <a href="https://medium.com/b-protocol">B.Protocol</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Double Parachute Model: a mathematical model for using debt-backed stable coins as collaterals]]></title>
            <link>https://medium.com/risk-dao/the-double-parachute-model-a-mathematical-model-for-using-debt-backed-stable-coins-as-collaterals-5f99fb08ae18?source=rss-f9716a559e68------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f99fb08ae18</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[usdc]]></category>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[gearbox]]></category>
            <dc:creator><![CDATA[Yaron Velner]]></dc:creator>
            <pubDate>Mon, 07 Nov 2022 19:58:00 GMT</pubDate>
            <atom:updated>2022-11-07T19:58:00.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9Py-owXHJINxYQrT0OUvA.png" /></figure><p>Debt-backed stable coins such as DAI, LUSD, sUSD and FRAX, are a source for passive yield in DeFi (e.g., as Curve LP, or in Yearn Vaults), and users could benefit from a highly leveraged position of such assets. If the leverage is done vs another stable coin such as USDC, then the liquidation risk for the user is considered small (for as long as the collateral stable coin retains its peg).</p><p>Hence, lending markets would benefit from providing high leverage to such users, however would risk bad debt accrual if the collateral stable coin loses the peg. Such bad debt can be mitigated by setting a proper liquidation threshold (aka collateral factor, aka LTV) that would allow the platform to properly liquidate the collateral as it is being deppeged. But in return, it would also limit the amount of leverage that a user can take.</p><p>In this blog post, we present a mathematical model to reason about the liquidation thresholds of a stable collateral asset. To the best of our knowledge, this is the first research on this matter. The framework we present assumes there already exists a mathematical model that reasons about liquidation thresholds of volatile assets, and uses that model as a black box. Hence, this new framework can be applied to any existing stress testing environment.</p><p>The model is presented for the setup of the Gearbox leverage protocol, and we focus on the scenario where USDC is borrowed against a stable coin collateral.</p><h3>The Double Parachute Model</h3><p>The LUSD stable coin is fairly elegant as it is backed by a single collateral, namely, ETH, and it has a built-in mechanism where users’ bad debt is socialised among all borrowers. Hence, we demonstrate our framework with the use of LUSD, but similar principles hold when analysing DAI and sUSD.</p><p>The Double Parachute Model (DPM) aims to simulate the bad debt that would result from permanent price depegging, and it ignores temporary deppegs that occur due to thin liquidity (we address those as well in the next section). In such a setup, the LUSD price is only affected by its percentage of ETH backing, and thus we can view a user position with LUSD collateral and USDC debt, as a position where the de facto collateral asset is ETH (and the debt is still USDC).</p><p>However, the user position is special as both Liquity (the protocol that operates LUSD) and the lending market (in our case Gearbox) will try to prevent the accrual of bad debt.</p><p>As illustrated in the figure below, as ETH price goes down, a first line of mitigation will be activated, and Liquity will try to prevent bad debt accrual in the LUSD system. Only if/when Liquity fails, and ETH price continues to go down, then the bad debt of the LUSD system will decrease the price of LUSD itself, and at this point the Gearbox system will kick in and will try to mitigate the bad debt on their own platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bnp6SDc7lyd3oIju" /></figure><p>In the double parachute analogy, the first parachute is Liquity, and its strength is dictated by the ETH backing it currently has. The second parachute is Gearbox, and its strength originates from the configured liquidation threshold where lower threshold is a stronger protection. In particular, when the ETH to LUSD backing ratio is sufficiently high, the second parachute can be degenerated and set to 100% (minus applicable liquidation penalties and known oracle deviation).</p><h4>Formal framework</h4><p>Formally, we see the LUSD system as a single user with X amount ETH collateral and Y amount of LUSD debt. We stress test the LUSD system to find the expected value at risk/amount of bad debt, and this can be done by any standard stress test environment. Then the liquidation threshold for Gearbox is set such that it compensates for bad debt in the LUSD system. For example, if the expected value at risk in the LUSD system is 15% of the LUSD supply, then Gearbox would set a liquidation threshold of 85%.</p><p>We note that in normal times, the value at risk of LUSD is expected to be 0%.</p><h3>Price fluctuations</h3><p>Most decentralised stable coins do not have physical mechanisms that force them to be traded at exactly $1. Instead, they fluctuate around $1, with volatility that is correlated to their corresponding dex liquidity (typically Curve Finance liquidity).</p><p>Most of these stable coins are not subject to risk-free arbitrages even when traded above or below peg. However one might hope that being traded above (resp., below) would discourage buyers (sellers) and thus bounce the price back to one.</p><p>Unfortunately, our analysis shows that by examining short time periods of 1 hour, we observe that the trading volume on these assets is fairly one sided.</p><p>The graph below shows that when breaking down the Curve Finance volume for FRAX trades to 1 hour windows, then on (volume weighted) average over 90% of the volume is one sided (of course as the price remains around $1, it shows that every time it is unbalanced towards a different size).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*ai3HMKUyESmLof_6" /></figure><p>That said, FRAX maintains a perfect peg thanks to a huge amount of Curve liquidity (over $0.5B) which is owned almost exclusively by the FRAX protocol itself.</p><p>This is not the case for LUSD, who has less one sided hourly volume, but suffers from almost permanent upwards deppeg.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*aHr6pGBWBXFFk_pB" /></figure><p>Finally, sUSD is the most balanced in terms of sided trading, but still pretty much one sided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*YHnBvXh7TGTC-CQY" /></figure><p>Hence, we also take the stable vs USDC dex liquidity into account, and assume that liquidation cascades will not be mitigated by organic trading volume for the counter direction. That said, as long as the stable coin is solvent, the asset volatility will remain low, and hence, relatively few liquidations are expected.</p><h4>Formal framework</h4><p>To be on the safe side, we simulate a situation where all of Gearbox’s stable collateral is liquidated in a single day, without any price recovery after every liquidation.</p><h3>Taxonomy</h3><h4>Raw assets</h4><p>For raw assets such as sUSD and LUSD we run simulations according to the Double Parachute Model, and according to the price fluctuations model, and set the liquidation threshold to be the minimum among those two recommendations.</p><h4>Curve LP token</h4><p>Curve LP tokens, e.g., LUSD/3crv LP token, are special because their price is bounded above by USDC price (of $1). This is due to technical limitations in their price oracle.</p><p>As a result we get special cases in LP tokens such as LUSD/3crv, where, as long as solvent, LUSD is redeemable to $0.99 of ETH, and as its imperfect oracle bound the price by $1, we get that the asset is not subject to price fluctuations, and thus its dex liquidity can be ignored.</p><p>On the down side, depositing the asset into the Curve system carries additional smart contract risk. This risk can be mitigated by charging higher user fees. And in any case Curve smart contracts are buttle tested and considered to be with low risk.</p><h4>Algorithmic stable coins</h4><p>The FRAX stable coin is also partially backed by its FXS governance token, which is minted whenever some of the backing is lost.</p><p>In this case we can apply the DPM with FXS as collateral asset. However, as FRAX has huge protocol owned liquidity vs USDC, this liquidity would also be taken into account as FXS liquidity.</p><h3>About Risk DAO</h3><p>Risk DAO is a service DAO focused on providing a new, open-source risk assessment framework, associated audits, and dashboards to stress test, monitor, and manage risk in DeFi lending and borrowing protocols as well as L1 and L2 networks.</p><p>You can follow us on Twitter <a href="https://twitter.com/Risk_DAO">here</a>. You can join our Discord <a href="https://discord.com/invite/NYyeDQDDvM">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f99fb08ae18" width="1" height="1" alt=""><hr><p><a href="https://medium.com/risk-dao/the-double-parachute-model-a-mathematical-model-for-using-debt-backed-stable-coins-as-collaterals-5f99fb08ae18">The Double Parachute Model: a mathematical model for using debt-backed stable coins as collaterals</a> was originally published in <a href="https://medium.com/risk-dao">Risk DAO</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>