Flashot: A Snapshot of Flash Loan Attack on DeFi Ecosystem
FFlashot: A Snapshot of Flash Loan Attack on DeFi Ecosystem
Yixin Cao ∗ , Chuanwei Zou, and Xianfeng Cheng Shanghai Wanxiang Blockchain Inc.
Abstract
Flash Loan attack can grab millions of dollars from decen-tralized vaults in one single transaction, drawing increasingattention from the Decentralized Finance (DeFi) players. Ithas also demonstrated an exciting opportunity that a hugewealth could be created by composing DeFi’s building blocksand exploring the arbitrage chance. However, a fundamentalframework to study the field of DeFi has not yet reached aconsensus and there’s a lack of standard tools or languagesto help better describe, design and improve the running pro-cesses of the infant DeFi systems, which naturally makes itharder to understand the basic principles behind the complex-ity of Flash Loan attacks.In this paper, we are the first to propose
Flashot , a proto-type that is able to transparently illustrate the precise assetflows intertwined with smart contracts in a standardized dia-gram for each Flash Loan event. Some use cases are shownand specifically, based on
Flashot , we study a typical
Pumpand Arbitrage case and present in-depth economic explana-tions to the attacker’s behaviors. Finally, we conclude thedevelopment trends of Flash Loan attacks and discuss thegreat impact on DeFi ecosystem brought by Flash Loan. Weenvision a brand new quantitative financial industry poweredby highly efficient automatic risk and profit detection systemsbased on the blockchain.
Flash Loan is an unprecedented outcome of Decentralized Fi-nance (DeFi) ecosystem. The idea was first proposed with thenotion
Flash Lending in July 2018 by a start-up project called
Marble , which tried to let anyone borrow assets withoutcollateral to take advantage of arbitrage opportunities as longas the funds are returned within the scope of the same transac-tion. Although some DeFi protocols may offer such function ∗ [email protected] https://medium.com/marbleorg/introducing-marble-a-smart-contract-bank-c9c438a12890 implicitly since 2019, it was first publicly implemented andmade available to market by one of the popular DeFi protocols Aave [17]. In fact, Flash Loan did not get a lot of attentionbefore DeFi went viral last year. Several large Flash Loanattacks accompanied the rise of the DeFi community, pushingFlash Loan to the forefront.Before delving into how Flash Loan works and why itdeserves our attention, we believe it is helpful to introduce abrief review of DeFi ecosystem first, with the hope to reach awider audience. A more comprehensive review can be foundin [15].
The Bright Future of DeFi
The year 2020 saw a pure community-driven DeFi ecosystemthriving. According to DeFi Pulse , the Total Value Locked(TVL) in a sum of 63 DeFi protocols has reached $26.504Billion on January 29 th Ethereum [2, 16]. Compared with the traditional finance,in DeFi systems transactions can be settled in an atomicand transparent way thanks to the blockchain technology.Moreover, intermediaries and centralized institutions, suchas custodian and central counterparty clearing house, are re-placed by smart contracts that can automatically running onthe blockchain platform. Built upon the innovative technicalfeatures, DeFi shows a promising potential to turn into a moreopen and efficient financial ecosystem with less counterpartyrisk [3, 6, 12, 15].
Assets in DeFi Market
Assets in DeFi markets are often called digital assets or virtualassets. They can be classified into two kinds, native proto-col assets and tokenized assets. Bitcoin (BTC) [8] as the firstsuccessful decentralized cryptocurrency is a typical native pro-tocol asset, which is entirely created by a blockchain protocol https://defipulse.com/ (Accessed January 29 th a r X i v : . [ q -f i n . C P ] F e b nd gains its market value mainly from community adoption.Tokenized asset, or token for short, is on the other hand a map-ping of certain asset or derivative product, to the blockchainthrough a process called Tokenization . There are various waysto create tokens [7, 11, 13]. The most adopted tokens arestable coins. For example, USDT and USDC backed byoff-chain fiat money share the largest market capitalizationin this section . DAI is a decentralized stable coin backedby over-collaterized digital assets . In fact, the vast major-ity of tokens are issued on Ethereum [11] through a smartcontract template referred to as the ERC-20 token standard .The major purpose of tokenization is to reduce transactionfrictions and make assets more accessible and flexible. Thisfeature contributes to make DeFi a more efficient financialecosystem. Smart Contract In Ethereum , a smart contract is intrinsically a piece ofcode created according to a protocol and broadcasted to theblockchain network. The code is first written in a human read-able way to specify the pre-agreed details such as transactionrules and execution restrictions etc . And then it undergoestranslation to a machine readable level in order to be executedin a temper-proof environment named as Ethereum VirtualMachine (EVM) when it is called. The distributed ledger ofblockchain platform also makes sure the uploaded smart con-tract itself is immutable unless some guy changes it using anadmin key, if there’s any .Smart contract is created or called by an electronic-signedtransaction sent by the creator’s or user’s address to theblockchain platform, while in the transaction the user specifiesthe operation instructions and required parameters. It can alsobe called by internal transactions from another running smartcontract and there’s no need for user to re-sign. In short, if welldesigned, a single electronic-signed transaction can triggera series of smart contracts and internal transactions to beexecuted in a deterministic, automatic way.If the transaction is successfully executed, it will change thestates of related contract parameters and asset balances as https://tether.to/wp-content/uploads/2016/06/TetherWhitePaper.pdf according to coinmarketcap.com, last accessed Jan 29 th https://makerdao.com/en/whitepaper/ https://eips.ethereum.org/EIPS/eip-20 Solidity is one of the most used programming languages for writingsmart contracts on
Ethereum . Admin key is not a necessary part of smart contract. It is supposedto allow a set of predefined key holders to upgrade the DeFi protocols orperform urgent shutdowns when some governmental condition is satisfied.Usually the admin key is set with multi-sig and time-locks and controlled byproject’s core team. Even though the team has no intension to do maliciousthings, there’re still potential risks from third parties. analogy to the bank account in the fiat money system, but the entity whoowns it is kept secret. A blockchain address is generated from the public-private key pair created by asymmetric cryptography. The private key is usedto sign the transaction sent by the corresponding address, which authenticatesthat the transaction can only be sent by the private-key holder. secured in blockchain addresses will be updated accordingly.Once any of the predefined restrictions is breached duringthe execution, the transaction will be reverted and the stateswill remain the same as if this transaction hadn’t taken place.Only a transaction fee will be charged from the address thatsends this transaction. DeFi’s Building Blocks
DeFi is actually composed by a bunch of building blocks, or money legos . Some of them can find prototypes in traditionalFinance, while others are original, such as
Uniswap [1].Nevertheless, they are all financial products or services in adecentralized version, being translated to smart contracts andinteracting with users through DApps .The key concept by using the term money legos is to empha-size the composability of the DeFi protocols. Money legos can be composed to form various kinds of systems in DeFiand work together with the common base settlement layer ofthe blockchain. Up to now, a few basic types of money legos have seen promising market, e.g. , stable coin, decentralizedexchange(DEX), lending&borrowing, derivatives, asset man-agement, insurance etc . They are classified to be within the ap-plication layer or protocol layer in a multi-layered frameworkproposed by some researchers [12, 15]. The multi-layeredframework gives a conceptual overview of the different con-structs of DeFi ecosystem on a macroscopic scale. But onemay still feel confused about how the DeFi systems reallywork and how Flash Loan exploiters find a vulnerability inthem. There is a need of more specific descriptions probingon a microscopic scale to help people get started. Flash Loan
Some aggregation DApps have already shown opportunitiesand risks the composability may bring by offering on-chainasset management services or repackaging assets to formmutilayer-structured financial instruments [5]. Flash Loanamplifies it in a dramatic way. In one single transaction, itcan either facilitate a liquidation bot to gain $3.6M as a rev-enue, or be utilized by a smart exploiter to grab millions ofdollars from a complex composite of DeFi protocols. Thereare only a few inspiring early works [4, 9, 14, 15] studying onthe Flash Loan attack. Wang et al. [14] proposed a 3-phasetransaction-based analysis framework to identify Flash Loantransactions by applying observed transaction patterns andtried to reveal the senders’ intentions through a behavior clas-sifier. Gronde [4] presented a more thorough analysis aboutFlash Loan’s market and applications but not up to date. Qin Uniswap is a decentralized exchange that facilitates automatic swappingof tokens, where price is determined according to a pre-defined constantproduct formula and liquidity provided by different investors is homogenizedin a same liquidity pool. DApps are frontend apps that interface with smart contracts throughABI. https://medium.com/pov-crypto/ethereum-the-digital-finance-stack-4ba988c6c14b t al. [9] treated Flash Loan attack as an optimization prob-lem and proposed a model formalized by a state transitionfunction with constraints. Werner et al. [15] presented a sys-tematic introduction of attacks in DeFi ecosystem, includingthose exploiting Flash Loan. In this paper, we hope to shedlight on some more aspects.This paper mainly contributes in the following aspects,• We propose a prototype called Flashot to uncover themicroscopic process of the Flash Loan attack in a clearand precise way. In fact,
Flashot is created to be astandard tool that can be utilized to illustrate asset flowsin any kind of DeFi systems.• An in-depth analysis about a typical Flash Loan attacktargeted at bZx is presented based on
Flashot , with amore accurate model and solution regarding the opti-mization problem plus some economic explanations tothe attacker’s behaviors.• We summarize the development trends of Flash Loanattacks and discuss about some risk control strategies.• Finally, we envision a groundbreaking financial ecosys-tem where Flash Loan plays a significant role.The rest of the paper is arranged as follows. In Section 2,we first give a background about what Flash Loan is andcompare its properties to other products in debt market. Alist of Flash Loan attack events that have occurred is alsocollected in Section 2.2. In Section 3, we propose a novelprototype called
Flashot to draw the running processes ofFlash Loan transaction in a single diagram. A typical case isstudied based on
Flashot and presented in Section 4 with anin-depth analysis in Section 4.2. In Section 5, we show thetrends of Flash Loan attacks with flashots of eight additionalcases attached in appendix A. Finally, we make a conclusionand share some discussions in Section 6.
Currently, Flash Loan services are provided by four represen-tative DeFi protocols namely
Aave , dYdX , Uniswap V2 ,and bZx . To use Flash Loan, one need to send a transactioncalling a smart contract to conduct all of the operations. Thebasic logic includes three steps, i.e. (i) Lend flash loan without collateral or credit certification;(ii) Make use of the flash loan to gain a profit;(iii) Repay flash loan plus interest. https://docs.aave.com/developers/guides/flash-loans https://help.dydx.exchange/en/articles/3724602-flash-loans https://uniswap.org/docs/v2/core-concepts/flash-swaps/ https://github.com/bZxNetwork/flashloan-sample As discussed about smart contract in Section 1, if in step(ii) one fails to make extra money, he will not have enoughmoney to fulfill step (iii), so that the transaction will be re-verted . The most important thing to be noted here is thatthe borrowing of flash loan is not valid unless the flash loancan be fully repaid within the scope of the same transaction,which technically eliminates the default risk.There’s no Flash Loan equivalent in the real world. De-fault risk exists in any loan products in the traditional finan-cial market and it raises the interest rate to different extent.Decentralized lending products provided by DeFi protocolssuch as Maker and
Compound prevent it by requiring over-collaterization of digital assets, nevertheless users still haveto encounter losses when the collaterized assets are not liq-uidated as soon as possible, especially when the market fluc-tuates sharply. Flash Loan, on the contrary, is a business thatnever loses money. Given the technical advantage, Flash Loan offers a rather con-venient borrowing service with very low interest rate . More-over, users can borrow as much as the total amount availablein flash loan pools. There’s no limitation on the borrowingamount as long as you can repay back. Flash Loan is alsoaccessible easily by anyone without complicated censorship.In a word, Flash Loan can provide abundant of assets at avery low interest rate in flash speed to anyone. These proper-ties make Flash Loan an ideal source of funds for attackers,and the trial and error cost of the attack is very low, just sometransaction fee charged by the base settlement layer of theblockchain platform. As listed in Table 1, several influential events exploiting FlashLoans have occurred since February 2020. Qin et al. [9] pro-vided a detailed analysis on two attacks happened in February2020 and categorized them as
Pump and Arbitrage attackand
Oracle Manipulation attack respectively. We follow thenotions in classifying subsequent cases that occurred and findthat most of them correspond to a manipulation of oracles.Two events were associated with a reentrancy attack [10]. Theexact DeFi protocols implicated in these events and the esti-mated value of proceeds grabbed by attackers at the time areshown as well. From the data, a more than tenfold increase inthe profit of a single attack is witnessed. Unless the user pays to fill the difference, for example, in a wash trading. https://compound.finance/ Aave , 0.3% for
Uniswap V2 , 2 Wei for dYdX , and free for bZx . dYdX bZx Pump and Arbitrage $330K
CompoundKyberUniswap V1 bZx bZx
Oracle Manipulation $638K
Uniswap V1KyberSynthetix dYdX Balancer
Pump and Arbitrage $439K
Uniswap V2
Uniswap V2 Harvest
Oracle Manipulation $26.6M
CurveUniswap V2 dYdX Cheese Bank
Oracle Manipulation $3.3M
Uniswap V2 dYdX Akropolis
Reentrancy $2M2020-11-14 Value.DeFi Attack
Value.DeFi
Oracle Manipulation $7.4M
Aave CurveUniswap V2 Uniswap V2SushiSwap dYdX OUSDUniswap V2SushiSwap
Reentrancy $7.9M2020-12-18 Warp Finance Attack
Uniswap V2dYdX Warp FinanceUniswap V2Sushiswap
Oracle Manipulation $941K
Actually, even the senior DeFi players may find it difficultto understand what really happened during the Flash Loanattack events as described in Section 2.2. The DeFi ecosystemis developing too fast to wait for the creation of useful re-search tools. People are still trying to understand and discussthe phenomena emerged in this field in rather native ways.Unlike industries that have developed for centuries, there areno applied tools fit for the nascent DeFi ecosystem, such as acircuit diagram for electronic engineering or an engineeringdrawing for mechanical engineering.Decentralized computing platforms,
Ethereum as a pioneer,provide a promising opportunity to transform the traditionalfinancial systems that heavily relying on manual works into afinancial engineering industry. One of the core components issmart contract. Smart contracts interact with each other andautomatically execute and record the transactions betweenassets. It will be useful and foresightful to form a universallanguage describing the functions and events of smart con-tracts, and to outline where assets are flowing and how theyare transformed in each transaction.To our best knowledge, we are the first to propose a stan- dardized asset flow diagram called
Flashot , which is de-signed to reveal the asset flows among various protocols ina transparent and precise way. For a comparison, similar at-tempts in [14](Fig. 4 and Fig. 5 therein) and [9] (Fig. 6and Fig. 7 therein) are either too simple to uncover importantmessages or hard to understand and standardize.
Flashot is composed of three basic elements and two classesof operations extracted from the DeFi systems.
Elements: (1)
Asset corresponds to the a naitve protocol asset createdon the blockchain such as ETH or a tokenized asset suchas the stable coin USDC. Each kind of asset has a tickerto distinguish with each other.(2)
Smart Contract corresponds to a piece of code that auto-matically executed on the decentralized blockchain plat-form, according to certain protocol. Each smart contracthas a name and a unique Hash as its index in
Ethereum .Here for legibility, we label smart contracts by their namesas an example.4igure 1: (a) Asset. An amount of 10,000 ETH is shown in this example. (b) Asset pool. The protocol dYdX ’s asset pool isshown in this example. (c) Smart contract. In this example, the contract name is dYdX: solo Margin . (d) Transform operationis denoted by a horizontal arrow line connecting an asset/asset pool to another, with smart contract’s name attached. A splitoperation is denoted by vertical arrow lines.(3)
Asset Pool corresponds to a blockchain address thatrecords assets’ balances, functioning as a vault. AssetPools include various types, e.g. , Lending Pools, Liquid-ity Pools, Minting Pools. There may be one or severalkinds of assets in an asset pool.
Operations: (1)
Split/Merge
Assets can be either splited into parts ormerged into a bulk.(2)
Transform
One kind of asset can be transformed intoanother by calling one or more smart contracts. Trans-form operations include swapping, depositing, redeeming,withdrawing, etc .As shown in Fig. 1(a) − (c), we use a rectangle to representa sum of asset and the figures inside it represent the amount.To distinguish different kinds of assets, the rectangles willalso be labeled with the corresponding tickers. An oval shaperepresents an asset pool with the protocol’s name inside it.Smart contract is represented by a rounded rectangle.Spit or merge operations are denoted by vertical arrowlines connecting rectangles representing a same kind of assets.Transform operations are denoted by horizontal arrow linesconnecting either asset pools or assets, with associated smartcontracts’ name attached. Fig. 1(d) shows an example. Next we use
Flashot to illustrate a notable transaction sent by a liquidation bot during the Compound LiquidationEvent on November 26 th . As shown in Fig. 2, the txhash: 0x53e09adb77d1e3ea593c933a85bd4472371e03da12e3fec853b5bc7fac50f3e4 https://beincrypto.com/100m-liquidated-from-compound-following-flash-loan-exploit/ whole process of the liquidation transaction is clearly pre-sented. There are three panels in the flashot , as described inthe following.• Asset Pool Panel
The left panel in the flashot shows the asset pools thateither provide flash loan or interact with asset flows ifthere is any. Some asset pools may be interacted morethan once at different stages of the transaction process.For example, flash loan pools are always associated withan asset flowing out and an asset flowing in. We use adotted line to connect the same asset pool that appearsat different stages.•
Asset Panel
The middle panel is the major panel illustrating assetflows. All associated assets are arranged in each columnin order of appearance. As introduced earlier, asset flowsare triggered by two classes of operations. Asset’s splitor merge operation is denoted by a set of solid arrowlines in the vertical direction. Transform operation isalso denoted by an arrow line in the horizontal direction,and the rounded rectangle denoting smart contract isattached. The arrow directions point to the destinationof the asset flows. Figures in the black solid rectanglerepresent the amount of ultimate proceed.•
Ratio Panel
In the right panel, some critical ratios or parameters willbe listed as a reference.From Fig. 2, we can easily find that this liquidation botborrowed around 46 million DAI from
Uniswap V2 ’s DAIpool, transfered it to
Compound ’s asset pool to liquidate anunderwater account at a favorable liquidation ratio (1 DAIfor 51.945 cDAI). Next, it splitted its asset cDAI into two5igure 2: A flashot of a transaction triggered by a Compound liquidation bot on November 26 th Flashot is able to illustrate even more complicate process.As listed in Table 1, the first well-known Flash Loan attack,bZx Pump Attack, took place on February 15 th , whichis a typical case covered by previous works [4,9,14]. Here wecontinue to show the power of Flashot based on this case,and give a guide on how to use
Flashot for analysis. First txhash: 0xb5c8bd9430b6cc87a0e2fe110ece6bf527fa4f170a4bc8cd032f768fc5219838
The flashot corresponding to the event bZx Pump Attackis shown in Fig. 3. At the very beginning, the attacker bor-rowed a total of 10,000 ETH from dYdX ’s flash loan pooland splitted it into three parts. The first part, 5,500 ETH, wasdeposited to
Compound ’s lending pool as a collateral in or-der to borrow 112 wBTC. At the same time, the attacker gotcDAI to be used to redeem the collateral later. We can also de-scribe this operation literally as (ETH:5,500)
CompoundEther −−−−−−−−−→ (cETH:274,843.68, wBTC:112, debt-wBTC: − equals 0.75.Then the attacker deposited the second part of flash loan,a total of 1,300 ETH, to bZx ’s vault as a margin collateral inorder to short ETH in favor of wBTC at 5x leverage by call-ing bZx ’s smart contract. The internal process of the margintrade was handled automatically by bZx protocol as shown inFig. 4. To execute the order, bZx ’s smart contract borrowed In Compound , a Collateral Factor is set for each token, the reciprocal ofwhich indicates the over-collateral ratio.
Flashot of bZx Pump Attack. There are five panels from top to bottom. The first panel shows the first Flash Loantransaction at block height 9484688 in which the major attack processes occurred. The second and fourth panels correspond to atotal of 57 transactions sent by the attacker to redeem collateral in
Compound during block height 9484917 to 9496529. Thethird panel presents a merge of 18 transactions triggered by liquidation bots. The last panel shows the last swap transaction andthe ultimate proceeds left in the attacker’s address. 7igure 4:
Flashot of internal process of 5x short margin trade in bZx protocol as exploited by the attacker in the event bZx PumpAttack.about 4,698.02 ETH from its iETH Vault and swapped about5,637.62 ETH to 51.346 wBTC at the DEX
Uniswap througha router called Kyber . Since
Uniswap is an automated mar-ket maker (AMM) where price is set according to a constantproduct formula relying on no external information, the pricedeviation from the initial price (36.55 in this case) will in-crease sharply with the trading volume in a swap transaction,giving the attacker a chance to manipulate the market. Bythis margin trade, he pumped the average price of wBTCat
Uniswap by three times up to 109.8 ETH and get somederivative-like token called sETHwBTC5x .To take advantage of the price spread between Uniswap andother market, 112 wBTC borrowed from
Compound was im-mediately swapped back to 6871.413 ETH at a ratio of 61.35,which is about 1.67 times of 36.83. The attacker merged6,871.413 ETH with the remain third part, 3,200 ETH andrepaid 10,000 ETH plus a flash loan fee (10 Wei).As a result of this transaction, the attacker gained 71.413 A router can aggregate different DEXs to find a trading path at a bestprice. contract address: 0xb0200b0677dd825bb32b93d055ebb9dc3521db9d ETH directly. Meanwhile, he owned 274,843.68 cETH, whichcan be used to redeem the collaterized ETH in
Compound after paying back the borrowed 112 wBTC plus interest. Healso had 1,300 ETH deposited in bZx ’s vault as a margin anda position of 51.346 wBTC in the margin trade. He couldclose the position by burning sETHwBTC5x in his address aslong as it were not liquidated.Actually, 75 transactions were executed in several subse-quent blocks to pay back 112 wBTC and redeem ETH. 57 ofthem were actively sent by the attacker, which went througha three-step process, cETH
CompoundEther −−−−−−−−−→
ETH
Kyber : Contract −−−−−−−−→ wBTC
CompoundWrappedBTC −−−−−−−−−−−−−−→ debt-wBTC. It is also interestingto see that there were 18 transactions corresponding to a liq-uidation process executed by third parties. As for the positionand margin collateral in bZx , the attacker just left them alone.Finally, the proceeds in this Flash Loan attack event wasabout 1244.106 ETH (about $ 330K at then market price),neglecting a small amount of cETH and sETHwBTC5x.8 .2 Economics Behind Behaviors
The essential reason why Flash Loan attack can succeed isbecause DeFi’s building blocks are automatically runningbased on predefined algorithms and predictable parameters.It’s capable to fomulate the problem as an optimization equa-tion under a few constraints. Qin et al. [9] had already sharedan instructive analytical framework in this aspect, despite theflaw that they analyzed the optimization problem based onprocedures and parameters over several blocks, which intro-duced future parameters in the calculation process.In this paper, we offer a more accurate version of deriva-tion as well as economic explanations behind the attacker’sbehaviors.According to the flashots in Fig. 3 and Fig. 4, we breakdown the first transaction of bZx Pump Attack into 6 steps, i.e. ,(1) Borrow n ETH from dYdX ;(2) Deposit n ETH as collateral to borrow c f · n p wBTC from Compound , where 0 < c f ≤ Compound , p is the market price of wBTC;(3) Borrow ( locr − )( n − n ) ETH from bZx by depositing ( n − n ) ETH as margin collateral , where ocr > bZx ;(4) Short sell l · ( n − n ) ocr ETH and get ∆ b wBTC through Uniswap ;(5) Swap c f · n p wBTC to ∆ e ETH through
Uniswap ;(6) Repay the Flash Loan.After setp (6), the attacker obtained P f = ∆ e − n ETH as adirect proceed, an amount of cETH and some sETHwBTC5x.He may choose another two steps to close the margin trade in bZx and repay the debt in
Compound ,(7) Close the short position by selling ∆ b wBTC in exchangefor ETH. Repay ( locr − )( n − n ) ETH plus interest. Theremain ETH deducted by ( n − n ) ETH will be net profitof the margin trade, if there is any;(8) Repay c f · n p wBTC to redeem n ETH.The key to success is to finish steps (1) − (6) in one trans-action without revertion. Steps (7) − (8) are actually like op-tions offered to the attacker, who can decide whether to ex-ercise them in a favorable way. While Qin et al. [9] in-cluded steps (1) − (7) to find the overall optimal output, wetreat steps (1) − (6) as an independent optimization problemdiscussed in Section 4.2.1 and Section 4.2.2. Step (7) and step(8) are treated as two additional problems related to contin-gent choices, which will be discussed in Section 4.2.3. https://compound.finance/markets/ETH Here we suppose the flash loan is used up, which is the optimal choice.
Let’s suppose there are b wBTC and e ETH in
Uniswap ’sasset pool before the Flash Loan attack takes place, and thesetwo parameters obey the constant product formula as shownin Eq. 1. b · e = k (1)Neglecting any fee charged, after step (4), the constantproduct formula becomes Eq. 2, where the price of wBTC ispumped from eb ETH to e + l · ( n − n ) ocr b − ∆ b ETH so that a profit can bemade in step (5). ( b − ∆ b ) · (cid:20) e + l · ( n − n ) ocr (cid:21) = k (2)From Eq. 1 and Eq. 2, we get Eq. 3, ∆ b = k · l · ( n − n ) ocr e (cid:104) e + l · ( n − n ) ocr (cid:105) (3)After step (5), the constant product formula becomes Eq. 4. (cid:18) b − ∆ b + c f · n p (cid:19) · (cid:20) e + l · ( n − n ) ocr − ∆ e (cid:21) = k (4)Combining Eq. 2 − Eq. 4, we get Eq. 5. ∆ e = c f · n p (cid:104) e + l · ( n − n ) ocr (cid:105) k + c f · n p (cid:104) e + l · ( n − n ) ocr (cid:105) (5)In step (6), it is required that there must be enough ETHto repay the flash loan plus an interest. Thus we get the firstconstraint as shown in Eq. 6, ∆ e > n (6)which can be transformed to Eq. 7 by substituting ∆ e accord-ing to Eq. 5. c f · l ocr ( n − n ) + c f · locr ( e − n )( n − n ) + c f · e ( e − n ) > p · k · nn (7)Eq. 7 gives a necessary but not sufficient condition to makesure the Flash Loan transaction will not be reverted. Thereare a few more constraints to follow as listed in Eq. 8. Theseconstraints restrict that the amounts of borrowed assets are https://hackmd.io/@HaydenAdams/HJ9jLsfTz c f Compoundocr bZxl bZxb
Uniswape
Uniswapp
Compoundp m n f n c Compound to borrow n b n ≤ n f < n < n c f · n p ≤ n c ( locr − )( n − n ) ≤ n b (8)Parameters c f , ocr , l are known constants set by Compound and bZx . b , e , p , n f , n c and n b are predictable variables whichcan be fetched from the Ethereum ’s event logs. k can becalculated according to Eq. 1. These parameters are collectedfrom [9] and listed in Table 2. One thing to be noted is that p is slightly different from the actual value (as shown in Fig. 3)calculated according to transaction logs. Since the differencewill not cause a qualitative change in the final result, we willexplore it in later works.The constraints in Eq. 8 can be degenerated to be Eq. 9,and then Eq. 10 after substituting the values. n ≤ n f max [ , n − n blocr − ] ≤ n ≤ min [ n c · pc f , n ] n − n blocr − ≤ n c · pc f (9) n − . ≤ n ≤ .
25 7573 . < n ≤ . n − . ≤ n ≤ n . < n ≤ . ≤ n ≤ n < n ≤ .
23 (10)Under these constraints, parameters can be tuned to reachthe optimal output. Here we define the ultimate gross profit P g to be composed by four parts as expressed in Eq. 11, P g = P f + n · ( − c f ) + P c + P c (11)where P f = ∆ e − n is the direct proceed of the Flash Loantransaction as defined before, and n · ( − c f ) is a fixed profitin the form of collateral in Compound under the assumptionthat the redemption ratio is equal to the borrowing exchange rate. P c and P c are unpredictable extra parts associated withthe contingent choices offered in step(7) and step(8) accord-ingly and we discuss about it in Section 4.2.3.Therefore, the main optimization problem is to maximizethe predictable profit P p = P f + n · ( − c f ) resulted fromstep (1) − (6). Next, we show why the parameters chosen by the attacker isnot optimal. In this case, n = , n = , + , = , n = ,
800 is shown in Fig. 5(a). The gray areasurrounded by two non-linear curves and two vertical linesshows that the favorable interval of n is between 5,343.77and 5,522.75, which can be quickly obtained by a numeri-cal calculation. We see that 5 ,
500 lies in this interval. AndFig. 5(b) shows that the maximum predictable profit onecan obtain is 2,043.45 ETH if he assigns 5,343.77 out of6,800 ETH to
Compound in step (2), which is more than71 . + , × ( − . ) = , .
41 ETH in the first at-tack transaction.The proceed can be further maximized by tuning theamount of flash loan, n . The optimization process automati-cally executed by a numerical simulation script yields the op-timized predictable profit in a few seconds. The maximum P p is 2,914.43 ETH with the optimal parameters set as n = , n = , .
77, which is twice the actual P p the attackergot. In previous analysis, we calculate the optimal predictableprofit obtained under the assumption that the redemption ratiois the same as the Borrowing Exchange Rate in
Compound . Bydoing this we actually separate the potential gain or loss apartfrom the gross profit, which is resulted from the contingentchoices according to step (7) and step (8).10igure 5: (a) Condition curves for a successful Flash Loanattack when n = , n according to Eq. 10. The gray area shows the favorableinterval of n where the Flash Loan transaction will not bereverted. We see that the parameter chose by the attacker inthe real event, n = ,
500 lies in this interval. (b) Predictableprofit P p versus n given n = , Uniswap in step (4), he onlygot about ∆ b = .
35 wBTC, equaling 2,002.50 ETH at amarket price around 39. Such a huge loss should have alreadycaused the short position not fully collateralized and triggereda liquidation process, which didn’t occur in the real event.This was caused by a hidden bug in bZx ’s smart contractwhere the sanity check was skipped, which was detected byPeckShield .Next, by tuning n and n we see if the short position’smarket value will increase to yield an extra profit P c denotedby Eq. 12. The maximum value of ∆ b · − l · ( n − n ) ocr + ( n − n ) over the valid parameter space yields − .
84, which means https://peckshield.medium.com/bzx-hack-full-disclosure-with-detailed-profit-analysis-e6b1fa9b18fc unpredictable part of profit P c is always 0 in this case. Inthe real event, the attacker didn’t execute subsequent processregarding it, which is rational. P c = max (cid:20) , ∆ b · − l · ( n − n ) ocr + ( n − n ) (cid:21) (12)As for step (8), a reasonable strategy is to keep cETH untilthe price of wBTC decreases, expecting a positive extra profit P c . If the expected price of wBTC is going to increase, itwill be better to redeem the collateral instantly since it willdepreciate. In the real event, the price of wBTC increasedfrom p = .
48 ETH to p m = .
08 ETH. The attacker mighthave noticed it and started to redeem the collateral in thesubsequent transactions. To minimize the impact it may bringto the market, the attacker finished the redemption processby sending multiple small-amount transactions. The processextended over several
Ethereum blocks and the redemptionratio was not predictable. Part of collateral even had beenliquidated by third parties. In a word, P c is unpredictableand can be negative when the collaterized assets go througha depreciation. That’s why the ultimate gross profit in thisevent, about 1244 .
108 ETH as shown in Fig. 3, is less thanthe predictable profit 1446 .
41 ETH.
From this attack, the composability of DeFi is demonstratedby Flash Loan transaction vividly. Flash Loan attack strategyconnects different money legos such as Flash Loan, decentral-ized lending platform, margin trade platform, exchange routerand AMM, and the margin trade platform itself is composedof lower-level modules. Flash Loan also offered a huge sumof money to help the attacker conduct such a pump-and-dumpattack strategy at a negligible error cost.The strategy will not succeed if two prerequisites are miss-ing.• First, there is an AMM where price can be predicted andmanipulated easily. In this case,
Uniswap is the target,where price is predicted by a constant product formulaand converges to the external market price relying onon-chain arbitrage bot. By making a single large-volumetransaction one can pump the price of the reduced assetin a swap pair to an extremely high level.• Second, the atomic property of Flash Loan transactionworks like a shelter against external arbitrageur whomay detect and reduce the price spread instantly. Thearbitrage spread is manually created and then made useof by the attacker in one go.Similar to the analysis in [9], the victim in this at-tack is protocol bZx , which encountered a loss of about5 , . − , − . × . = , .
02 ETH since11he attacker’s margin trade position was depreciated dramat-ically. The liquid providers in
Uniswap encountered a greatimpermanent loss due to the large price deviation, which couldbe taken advantage of by arbitrageurs to get a profit about1 , .
26 ETH . The attacker finally grabbed 1244 .
11 ETH($330K) into his own address. It is noted that the loss value of bZx roughly equals the sum of the arbitrage gain in
Uniswap and the attacker’s profit. And the proceeds could be doubledif the parameters were set optimally.
We conduct a thorough study on other Flash Loan attacks aslisted in Table 1.
Flashots can be found in Appendix A. Fromthese
Flashots , we can summarize a few development trendsof the Flash Loan attacks.• The proceeds grabbed by the exploiters increased by ascale. This is partially due to the expanding of the capitalscale in DeFi market itself.• While some of the attacks include a series of sophisticatesteps in one strike, some others show a trend to repeatsimple steps to accumulate profits.• While most of the attack targets are AMM, the roleAMM plays is different from each other. In most FlashLoan attack events, AMM acts as an oracle providingprices to other DeFi protocols, so that attackers shifttheir target to the oracles and then they can manipulatethe exchange or borrowing ratios of certain tokens thatrelying on the oracle.• While some events happened due to the technical bugsof smart contracts such as reentrancy attacks and someof the oracle manipulation attacks like Warp FinanceAttack , the rest events show vulnerabilities emergingfrom the DeFi systems themselves.Without doubt, Flash Loan attacks will continue to occurin the future. To control risks, some protocols introducedmaximum slippage checks in an AMM swap, yet attackerswere still capable to perform manipulations within limitationand many a little makes a mickle, such as in Harvest Attack as shown in Fig. A3 and Fig. A4. Another solution is to makesure that the buying and selling operations of an asset must beexecuted in different transactions or even blocks so that the After step (4), there were 138.76 wBTC and 1565.21 ETH in
Uniswap ’swBTC asset pool and the price of wBTC is dumped to be 11.28 ETH. To pullthe price back to the market price, say, 39.08, the arbitrageur swaps 1,348.19ETH for 64.21 wBTC with 29.72wBTC as an arbitrage gain. attacker cannot repay flash loan in one transaction, but this isat the expense of normal users’ experience.From another perspective, Flash Loan attacks have con-tributed a lot to the discovery of DeFi protocols’ vulnerabil-ities. We could see that similar strategies were used by theattackers, such as Cheese Bank Attack and Warp Finance At-tack as shown in Fig. A5 and Fig. A11, which can be com-pletely avoided based on the lessons learned. These eventswarned us that protocols should be designed more seriouslyin against both of the attackers and deal-hunters. Flashot isdesigned to be a helpful tool for this task.
In this paper, we studied an unprecedented lending tool, FlashLoan, which is a double-edged sword to be used either to raisecapital efficiency during normal financial operations such asliquidation, or to conduct a subtly designed Flash Loan attack.Since transactions can only be executed one by one andthe update time of blockchain state is discrete, the FlashLoan transaction makes an exclusive and definite changeof the blockchain’s world state as if DeFi systems are stoppedrunning during its execution. It somewhat realizes a scenedepicted by
Time Dilation theory proposed by Albert Ein-stein. Flash Loan transaction is like a rocket flying acrossthe blockchain world at the speed of light, and in the viewfrom the blockchain world, time is dilated. Thus it’s interest-ing to call Flash Loan attack as
Time Dilation attack, whereFlash Loan transaction sender can apply magic changes to theblockchain’s world state with no one else can interfere.During the magic changes, assets borrowed from the flashloan pools shuttle smartly among different DeFi protocols.
Flashot we proposed in this paper can be used to illustratethe asset flows intertwined with smart contracts in a standardway, which is like taking a snapshot to capture the runningprocess of the Flash Loan transaction. In the future, the mod-ules assembled by DeFi systems may become hundreds andthousands. At that time such a standardized tool will showmore power.The features caught by
Flashot can help form a com-prehensive understanding about the key components to beimproved in order to make a more robust and efficient DeFisystem. In bZx Pump Attack, we see that currently the coretarget of Flash Loan is liquidity pools of AMM, especiallythose swap pairs with low liquidity. To some extend, the sizeof the liquidity pool will become the "moat" for AMM toresist Flash Loan attacks. Driven by such a factor, the FlashLoan attack may facilitate the optimization and consolidationof the AMM liquidity pools. AMMs whose liquidity poolshave not reached the "critical scale" may be absorbed by largerAMMs. Both of the attackers grabbed their proceeds by manipulating the amountof an asset in AMM that is a critical parameter used by the price oracle.
12e also realize a fusion effect of the DeFi ecosystem on
Ethereum . Before frequent Flash Loan attack incidents hap-pened, DeFi’s money legos had just shown a limited com-posability. As the DeFi ecosystem has already developeda scale on
Ethereum , it offers a diverse platform for FlashLoan borrowers to connect imaginative composite of moneylegos . On the other hand, Flash Loan attack shows a greatpotential to speed up the construction and troubleshootingof DeFi systems in a positive way. These all form a virtu-ous cycle helping transform the rudimentary DeFi systems todecentralized financial infrastructures that can realize moresophisticated functions. And the difficulty of migrating DeFi’sbuilding blocks from
Ethereum to other public blockchains isincreasing because the latter does not have such an ecosystemwith comparable scale.Moreover, Flash Loan transaction provides a new solu-tion for reducing frictions in the financial systems. One donot need to hold the principal to participate and the liquidityrisk is greatly reduced. Since the revertion feature cannotbe established without blockchain technology, it also demon-strates that in addition to solving credit problems by providingatomic transactions, blockchain technology can also greatlyimprove the capital efficiency through Flash Loan. In future,competition in the financial industry may just have to focuson how to improve the capabilities on advanced modeling andsystem design in terms of price discovery.To conclude, We look forward to a next-generation of fi-nancial industry powered by highly efficient automatic riskand profit detection systems based on the blockchain.
Acknowledgments
We thank Dr. Xiao Feng for insightful discussions about thedevelopment of Flash Loan and the significant impact it maybring to DeFi ecosystem.
References [1] Hayden Adams, Noah Zinsmeister, and Dan Robinson.Uniswap v2 core. 2020. https://uniswap.org/whitepaper.pdf .[2] Vitalik Buterin. Ethereum: A next-generation smartcontract and decentralized application platform. 2013. https://ethereum.org/en/whitepaper/ .[3] Yan Chen and Cristiano Bellavitis. Blockchain disrup-tion and decentralized finance: The rise of decentralizedbusiness models.
Journal of Business Venturing In-sights , 13:e00151, 2020. https://doi.org/10.1016/j.jbvi.2019.e00151 .[4] Florian Gronde.
Flash Loans and Decentralized Lend-ing Protocols: An In-Depth Analysis . PhD thesis, Uni-versity of Basel, 7 2020. https://wwz.unibas.ch/ fileadmin/user_upload/wwz/00_Professuren/Schaer_DLTFintech/Lehre/MA_Florian_Gronde_Flashloans-ohne_Appendix.pdf .[5] Lewis Gudgeon, Daniel Perez, Dominik Harz, BenjaminLivshits, and Arthur Gervais. The decentralized financialcrisis. , 2020. https://doi.org/10.1109/CVCBT50464.2020.00005 .[6] Darren Lau, Daryl Lau, Sze Jin Teh, Kristian Kho,Erina Azmi, Lee TM, and Bobby Ong.
How toDeFi . Independently published, 1st edition, 2020. .[7] Xuefeng Li, Xiaochuan Wu, Xin Pei, and Zhuojun Yao.Tokenization: Open asset protocol on blockchain. , 2019. https://doi.org/10.1109/INFOCT.2019.8711021 .[8] Satoshi Nakamoto. Bitcoin: A peer-to-peer electroniccash system. 2008. https://bitcoin.org/bitcoin.pdf .[9] Kaihua Qin, Liyi Zhou, Benjamin Livshits, and ArthurGervais. Attacking the defi ecosystem with flash loansfor fun and profit. arXiv preprint arXiv:2003.03810v2 ,2020. https://arxiv.org/abs/2003.03810 .[10] Michael Rodler, Wenting Li, Ghassan O. Karame, andLucas Davi. Sereum: Protecting existing smart con-tracts against re-entrancy attacks. In
Proceedings of26th Annual Network & Distributed System SecuritySymposium (NDSS) , 2019. http://tubiblio.ulb.tu-darmstadt.de/111410/ .[11] Jakob Roth, Fabian Schär, and Aljoscha Schöpfer. Thetokenization of assets: Using blockchains for equitycrowdfunding.
Available at SSRN , 2019. https://ssrn.com/abstract=3443382 .[12] Fabian Schär. Decentralized finance: On blockchain-and smart contract-based financial markets.
Avail-able at SSRN , 2020. https://ssrn.com/abstract=3571335 .[13] Yifeng Tian, Yuanxin Zhang, R. Edward Minchin,Ashish Asutosh, and Congwen Kan. An innovativeinfrastructure financing instrument: Blockchain-basedtokenization.
Construction Research Congress 2020:Infrastructure Systems and Sustainability , 2020. https://doi.org/10.1061/9780784482858.079 .[14] Dabao Wang, Siwei Wu, Ziling Lin, Lei Wu, XingliangYuan, Yajin Zhou, Haoyu Wang, and Kui Ren. Towardsunderstanding flash loan and its applications in defi13cosystem. arXiv preprint arXiv:2010.12252v1 , 2020. https://arxiv.org/abs/2010.12252 .[15] Sam M. Werner, Daniel Perez, Lewis Gudgeon, AriahKlages-Mundt, Dominik Harz, and William J. Knot-tenbelt. Sok: Decentralized finance (defi). arXivpreprint arXiv:2101.08778v1 , 2021. https://arxiv.org/abs/2101.08778 .[16] Gavin Wood. Ethereum: A secure decentralised gener-alised transaction ledger. 2020. https://ethereum. github.io/yellowpaper/paper.pdf .[17] [email protected]. Aave protocol whitepaper. 2020. https://github.com/aave/aave-protocol/blob/master/docs/Aave_Protocol_Whitepaper_v1_0.pdf . A Appendices
Flashot of bZx Oracle Attack. The borrowing rate is based on an oracle depending on the prices provided by
Uniswap and
Kyber , which was manipulated by the attacker in this event. The whole diagram presents the process of a singleFlash Loan transaction, where 18 swap operations interacted with
Kyber ’s smart contract are merged for simplicity. Txhash:0x762881b07feb63c436dee38edd4ff1f7a74c33091e534af56c9f7d49b5ecac15.15igure A2:
Flashot of Balancer Attack. The attacker drained up Balancer’s asset pool by manipulating the price of a defla-tionary token called STA. Since in each swap operation 1% of STA will be burned as a swap fee, the attacker swapped itfrequently with other 4 tokens and then the amount of STA was dramatically reduced and STA’s price soared sharply. Txhash:0x013be97768b702fe8eccef1a40544d5ecb3c1961ad5f87fee4d16fdc08c78106.16igure A3:
Flashot of the first Flash Loan transaction targeting at
Harvest ’s fUSDC pool in HarvestAttack, which was repeated by 16 times to grab a total of 14 million USDC and 340 ETH. Txhash:0x35f8d2f572fceaac9288e5d462117850ef2694786992a8c3f6d02612277b0877.17igure A4: After attacking fUSDC pool as shown in Fig. A3, the attacker repeated a similar strategy by 13 times targeting at
Harvest ’s fUSDT pool and grabbed a total of 11.7 million USDT and 0.76 million USDC. Here we show the flashot of the firstFlash Loan transaction targeting at
Harvest ’s fUSDT pool in this event. Some proceeds out of previous attack transactions wereused in the subsequent attacks. Txhash: 0x0fc6d2ca064fc841bc9b1c1fad1fbb97bcea5c9a1b2b66ef837f1227e06519a6.18 i gu r e A : F l a s ho t o f C h ee s e B a nk A tt ac k . T h e bo rr o w i ng r a t e i s p r ov i d e dby a no r ac l e , w h i c h w a s m a n i pu l a t e dby t h ea tt ac k e r t h r ough i n c r ea s i ng t h ea m oun t o f U n i s w ap ’ s C H EE S E l ’ s ET H . T xh a s h : a aa a a ff ca ea b8961 a c a f cc . Flashot of the first Flash Loan transaction exploited in a reentrancy attack targeted at
Akropo-lis . A large number of dsUSD was minted without being backed by any collateral. The attacker repeated thesame strategy in another 16 transactions and got a total of 2.04 million DAI and 0.31 million dsUSD. Txhash:0xddf8c15880a20efa0f3964207d345ff71fbb9400032b5d33b9346876bd131dc.20 i gu r e A : F l a s ho t o f V a l u e . D e F i A tt ac k . T h e p r i ce o f t e x tit V a l u e . D e F i ’ s poo lt ok e n m v U S D i s f e dby C u r ve a s a no r ac l e . T h ea tt ac k e r m i n t e d m v U S D a t a no r m a l p r i cea nd t h e n m a n i pu l a t e d t h e p r i ce o f C r vby s w a pp i ng a l a r g ea m oun t o f s t a b l e s c o i n s i n C u r ve ’ s DA I / U S D C / U S D T poo l , w h i c hpu m p e d t h e p r i ce o f m v U S D t o r e d ee mm o r e C r v . T xh a s h : a f e c a c c c f a dd c a . Flashot of the Flash Loan transaction exploited in a reentrancy attack targeted at
OUSD . The balances of all user’sOUSD were rebased and the attacker got a total of 9181 ETH, 1 million DAI and 5.223 million OUSD. The attacker sent 11 sub-sequent transactions to redeem OUSD. Txhash: 0xe1c76241dda7c5fcf1988454c621142495640e708e3f8377982f55f8cf2a8401.22igure A9:
Flashot of subsequent transactions in the reentrancy attack targeted at
OUSD . Some transactions with a same patternwere merged for simplicity. 23igure A10:
Flashot of subsequent transactions in the reentrancy attack targeted at
OUSD as a continuation of Fig. A9.24igure A11:
Flashot of Warp Finance Attack in a single Flash Loan transaction. The attacker exploited a calculation bug inWarp Finance’s oracle, where the price of
Uniswap ’s pool token UNI-V2 was calculated by n ETH · p ETH + n DAI · p DAI totalsupply . While prices p ETH and p DAI were normally provided by