Attacking the DeFi Ecosystem with Flash Loans for Fun and Profit

03/08/2020 ∙ by Kaihua Qin, et al. ∙ 0

Credit allows a lender to loan out surplus capital to a borrower. In the traditional economy, credit bears the risk that the borrower may default on its debt, the lender hence requires an upfront collateral from the borrower, plus interest fee payments. Due to the atomicity of blockchain transactions, lenders can offer flash loans, i.e. loans that are only valid within one transaction and must be repaid by the end of that transaction. This concept has lead to a number of interesting attack possibilities, some of which have been exploited recently (February 2020). This paper is the first to explore the implication of flash loans for the nascent decentralized finance (DeFi) ecosystem. We analyze two existing attacks vectors with significant ROIs (beyond 500k finding flash loan-based attack parameters as an optimization problem over the state of the underlying Ethereum blockchain as well as the state of the DeFi ecosystem. Specifically, we show how two previously executed attacks can be “boosted” to result in a profit of 829.5k USD and 1.1M USD, respectively, which is a boost of 2.37x and 1.73x, respectively.



There are no comments yet.


page 1

page 2

page 3

page 4

This week in AI

Get the week's most popular data science and artificial intelligence research sent straight to your inbox every Saturday.

I Introduction

A central component of our economy is credit: to spur healthy growth, the market allows borrowers to take on debt from lenders in the form of credit. Credit is generally considered to be a positive force, assuming the borrowed money is used productively, and the lender avoid granting excessive credit [dalio2018principles]. While credit can be used for good purposes, the market may also abuse such capital injection. One of the mechanisms that is used to adjust the attractiveness of borrowing used by central banks and policy makers is interest rate. A higher interest rate renders borrowing more expensive, while a lower interest rate encourages lenders to extend credit. An abuse of excessive credit typically leads to debt defaults — i.e. borrowers no longer being able to repay their debt. This leads us to the following intriguing question: What if it were possible to offer credit, without bearing the risk that the borrower does not pay back the debt? Such a concept appears impractical in the traditional financial world. No matter how small the borrowed amount, and how short the loan term, the risk of the borrower defaulting remains. If one were absolutely certain that a debt would be repaid, one could offer loans of nearly infinitive volume — or lend to individuals independently of demographics and geographic location, effectively giving access to capital to rich and poor alike.

Fig. 1: Overview of our parametrized optimizer. Given a blockchain state, DeFi models, and attack vector, it solves for the parameters yielding the best revenue.

Given the peculiarities of blockchain-based smart contracts, so-called flash loans emerged. A flash loan is a loan that is only valid within one blockchain transaction. Flash loans fail, if the borrower does not repay its debt before the end of the transaction borrowing the loan. That is, because a blockchain transaction can be reverted during its execution, if the condition of a repayment is not satisfied. Such instant loan yields three novel properties, absent in centralized financial economies:

  • No debt default risk: A lender offering a flash loan bears no risk that the borrower defaults on its debt111Besides the risk of smart contract vulnerabilities.. Because a transaction and its instructions must be executed atomically, a flash loan is not granted if the transaction fails due to a debt default.

  • No need for collateral: Because the lender is guaranteed to be paid back, the lender can issue credit without upfront collateral from the borrower: a flash loan is non-collateralized.

  • Loan size: Flash loans are taken from a public smart contract-governed liquidity pool. Any borrower can borrow the entire pool at any point in time. As of March 2020, the two largest flash loan pools [aave, dydx] each offer in excess of M USD.

To the best of our knowledge, this is the first paper which investigates flash loans. We categorize their use cases and explore their dangers. We meticulously dissect two events where talented traders realized a profit of each about k USD and k USD with two independent flash loans. We show how these traders however, have forgone the opportunity to realize a profit exceeding 829.5k USD and 1.1M USD, respectively. We realize this by finding the optimal adversarial parameters the trader should have employed, using a parametrized optimizer (cf. Figure 1).

This paper makes the following contributions:

  • Flash loan usage analysis. We provide a comprehensive overview of how and where the technique of flash loans can and is utilized.

  • Post mortem of existing attacks. We provide a detailed analysis of two existing attacks that used flash loans and generated an ROI beyond 500k%: a pump and arbitrage from the 15th of February 2020 and an oracle manipulation from the 18th of February 2020.

  • Attack parameter optimization framework. Given several DeFi systems covering exchanges, credit/lending and margin trading systems, we provide a framework to determine the parameters that yield the maximum revenue a trader can achieve when utilizing a particular flash loan strategy.

  • Opportunity loss. We analyze previously proposed and executed attacks to quantify the opportunity loss for the attacker given their optimal behavior, as determined by the framework above. We experimentally validate the opportunity loss of both aforementioned attacks on their respective blockchain state.

Paper organization: The remainder of the paper is organized as follows. Section II elaborates on the DeFi background. Section III outlines flash loan use cases. Section IV, dissects two known flash loan attacks and Section V shows how to optimize their revenue. Section VI provides a discussion. We outline related work in Section VII. We conclude the paper in Section VIII.

Ii Background

Decentralized ledgers, such as Bitcoin [bitcoin], enable the performance of transactions among peers without trusting third parties. At its core, a blockchain is a chain of blocks [bonneau2015sok, bitcoin], extended by miners by crafting new blocks that contain transactions. Smart contracts [wood2014ethereum] allow the execution of complicated transaction types enabling DeFi.

Ii-a Decentralized Finance (DeFi)

Decentralized Finance is a conglomerate of financial cryptocurrency-related protocols defined by open-source smart contracts. These protocols for instance allow to lend and borrow assets 

[makerdao, compoundfinance], exchange [dydx, uniswap2018], margin trade [dydx, bzxnetwork], short and long [bzxnetwork], and allow to create derivative assets [compoundfinance]. At the time of writing, the DeFi space accounts for over 1bn USD in smart contract locked capital among different providers. The majority of the DeFi platforms operate on the Ethereum blockchain, governed by the Ethereum Virtual Machine (EVM).

Ii-B Reverting EVM State Transitions

The Ethereum blockchain is in essence a replicated state machine. To achieve a state transition, one applies as input transactions which modify the EVM state following rules encoded within deployed smart contracts. The EVM state is only altered if the transaction execute successfully. Otherwise, the EVM state is reverted to the previous, non-modified state. Transactions can fail due to three reasons: (i) insufficient transaction fees (i.e. due to an out-of-gas exception), (ii) due to a conflicting transaction (e.g. using the same nonce) or (iii) due to a particular condition within the to be executed transaction that cannot be met. State reversion hence appears to be a necessary feature.

Ii-C Flash Loans

Reversing EVM state changes, allows for an intriguing new financial concept: flash loans. A flash loan is only valid within a single transaction (cf. Figure 2).

1. Take a flash loan
2. Use the lent assets
3. Pay back the loan plus interests
Fig. 2: Flash loan approach, summarized.

Flash loans rely on the atomicity of blockchain (and, specifically, Ethereum) transactions within a single block. Atomicity has two important implications on flash loans. First, non-collateralized lending: A lender does not need to provide upfront collateral to request a loan of any size, up to the flash loan liquidity pool amount. Any lender, willing to pay the required transactions fees (which typically amount to a few USD) is an eligible lender. Second, risk-free lending: If a lender is not able to pay back the loan, the flash loan transaction fails. Besides smart contract, and more generally blockchain vulnerabilities, the lender is hence not exposed to the risks of a debt default.

Ii-D DeFi Actors

In the following, we define the on-chain actors that we consider within this work and focus on a single blockchain.


a trader possesses a private/public key pair and is eligible to sign and send transactions towards other accounts and smart contracts.

Liquidity Provider

a trader with surplus capital may chose to offer this capital to other traders, e.g. as collateral within a DEX or lending platform.

Liquidity Taker

a trader which is servicing liquidity provider with fees in exchange to accessing the available capital.

Ii-E DeFi Platforms

We briefly summarize relevant DeFi platforms, such as exchanges [uniswap2018, kyber], margin trading [dydx, bzxnetwork], credit/lending [makerdao, compoundfinance] DeFi platforms. Within this paper, we are not covering alternative DeFi platforms such as stablecoins [makerdao], prediction markets and insurance systems.

Exchanges: We observe the following DeFi exchanges.

Limit order book (LOB) DEX: An order book is a collection of bid and ask orders. Traders post buy/bid or sell/ask orders for an asset of the market to a LOB. A bid order positions the trader as a buyer, while an ask positions the trader as a seller. Buyers aim to purchase an asset at the lowest price possible, while sellers aim for the highest possible selling price. When a trader specifies an order with a fixed or better price, the trader issues a so-called limit order [limit-order]. Once buyers and sellers post orders with compatible prices, their orders can be matched. A liquidity provider contributes bid and asks, to facilitate a match (i.e. market making). Several blockchain exchanges operate a LOB within a smart contract [oasis2019, idex2019, kyber].

Automated market maker (AMM) DEX: An alternative exchange design is to collect funds within a liquidity pool, e.g. two pools for an AMM asset pair /. The state (or depth) of an AMM market / is defined as , where represents the amount of asset and the amount of asset in the liquidity pool. Liquidity providers can deposit/withdraw in both pools and to in/decrease liquidity. AMM DEX support endpoint such as Swapfor to trade an asset for . The simplest AMM mechanism is a constant product market maker, which for an arbitrary asset pair /, keeps the product constant during trades. A number of DEX operate under the AMM model [uniswap2018, kyber].

When trading on an exchange, price slippage may occur, i.e. the change in the price of an asset during a trade. The greater the quantity to be traded, the greater the slippage.

Margin trading: Trading on margin offers the opportunity for traders to borrow assets from the trading platform (or broker) and trade with these borrowed assets. The trader typically must provide collateral and the trading platform then enables the trader to borrow several multipliers of the collateral for margin trading. Multiple DeFi platforms offer margin trading [bzxnetwork, dydx].

Credit and lending: With over 900M USD locked capital, credit represents one of the most significant recent use-cases for blockchain based DeFi systems. Because borrowers are only represented with weak identities (e.g. public keys), they must provide between 125% [dydx] to 150% [makerdao] collateral of an asset to borrow 100% of another asset . Different DeFi lending platforms exist, ranging from user-to-user lending, to pooled lending [compoundfinance] and lending that enable decentralized stable coins.

Iii Use Cases for Flash Loan

In this section, we are analyze the possible use cases for flash loans. It is in general difficult to qualify these activities as fully benign or malicious—it depends on the intent of the people orchestrating these transactions.

Iii-a Arbitrage

The value of an asset is typically determined by demand and supply of the market, across different exchanges. Due to a lack of instantaneous synchronization among exchanges, the same asset can be traded at slightly different prices on each exchange. Related work compared Bitcoin, Ethereum and Ripple price variation across 14 exchanges in Europe, Korea, Japan and the US (excluding China) from 1st January 2017 to 28th February 2018 [makarov2020trading]. The study found twice, price deviations beyond  during several hours. Arbitrage is the process of exploiting price differences among exchanges for a financial gain [arbitrage]. In fact, arbitrage helps synchronizing exchanges by incentivizing traders to equate the price of the same asset across exchanges. To perform arbitrage, a trader needs a reserve of an asset at different exchanges — i.e. arbitrage requires an extensive portfolio and volatility risk management.

How flash loans change arbitrage risks: Given flash loans, a trader can perform arbitrage on different DEX, without the need to hold a monetary position or being exposed to volatility risks. The trader can simply open a loan, perform an arbitrage trade and pay back the loan plus interests. One may argue that flash loans render arbitrage risk-free, the risks of smart contract vulnerabilities and blockchain consensus however remain.

Arbitrage example: On Jan , a flash loan borrowed  DAI from Aave [aave] to make an arbitrage trade on the AMM DEX Uniswap222transaction id: 0x4555a69b40fa465b60406c4d23e2eb98d8aee51def21faa28bb7d2b4a73ab1a9. To prepare the arbitrage, DAI is converted to SAI using MakerDAO’s migration contract333address: 0xc73e0383F3Aff3215E6f04B0331D58CeCf0Ab849. The arbitrage converts SAI for ETH using SAI/ETH Uniswap, and then immediately converts ETH back to  DAI using DAI/ETH Uniswap. After the arbitrage,  DAI is transferred back to Aave to pay the loan plus fee. This transaction costs ETH of gas (about USD at the time of writing). Note that even though the transaction sender gains DAI from the arbitrage, this particular transaction is not profitable.

Iii-B Wash Trading

The trading volume of an asset, is a metric indicating the trading popularity of an asset. The most popular assets therefore, are supposed to be traded the most — e.g. Bitcoin to date enjoys the highest trading volume (reported up to T USD per day) of all cryptocurrencies.

Malicious exchanges or traders can mislead other traders by artificially inflating the trading volume of an asset to attract interests. In September 2019,  out of the top  exchanges on Coinmarketcap [coinmarketcap] were wash trading over % of their volumes [BTIMarke7:online]. In centralized exchanges operators can easily and freely create fake trades in the backend, while decentralized exchanges settle trades on-chain. Wash trading on DEX thus requires wash traders to hold and use real assets. Flash loans can remove this “obstacle” and wash trading comes at a cost of the loan interest, trading fees, and (blockchain) transaction fees, e.g. gas. A wash trading endeavour to increase the 24-hour volume by 50% on the ETH/DAI market of Uniswap would for instance cost about  USD (cf. Figure 3). We visualize in Figure 3 the required cost to create fake volumes in Uniswap markets. At the time of writing, the transaction fee amounts to  USD, the flash loan interests range from a constant  Wei (on dYdX) to % (on Aave), and exchange fees are about % (on Uniswap).

Wash trading example: On March 2nd, 2020, a flash loan of  ETH borrowed from dYdX performed two back-and-forth trades (first converted  ETH to  LOOM and then converted  LOOM back to  ETH) on Uniswap ETH/LOOM market444transaction id: 0xf65b384ebe2b7bf1e7bd06adf0daac0413defeed42fd2cc72a75385a200e1544. The 24-hour trading volume of the ETH/LOOM market increased by % (from  USD to  USD) as a result of the two trades.

Fig. 3: Wash trading cost on two Uniswap markets with flash loans costing 0.09% (Aave) and a constant of 1 Wei (dYdX) respectively. The 24-hour volumes of ETH/DAI and ETH/WBTC market were USD and USD respectively (1st of March, 2020).

Iii-C Collateral Swapping

We classify DeFi platforms that rely on users providing cryptocurrencies 

[dydx, aave, makerdao] as follows: (i) a DeFi system where a new asset is minted and backed-up with user-provided collateral (e.g. MakerDAO’s DAI or SAI [makerdao]) and (ii) a DeFi system where long-term loans are offered and assets are aggregated within liquidity pools (e.g. margin trading [bzxnetwork] or long term loans [aave]). Once a collateral position is opened, DeFi platforms store the collateral assets in a vault until the new/borrowed asset are destroyed/returned. Because cryptocurrency prices fluctuate, this asset lock-in bears a currency risk. With flash loans, it is possible to replace the collateral asset with another asset, even if a user does not possess sufficient funds to destroy/return the new/borrowed asset. A user can close an existing collateral position with borrowed funds, and then immediately open a new collateral position using a different asset.

Collateral swapping example: On February , a flash loan borrowed  DAI (from Aave) to perform a collateral swap (on MakerDAO)555transaction id: 0x5d5bbfe0b666631916adb8a56821b204d97e75e2a852945ac7396a82e207e0ca. Before this transaction, the transaction sender used  WETH as collateral for instantiating  DAI (on MakerDAO). The transaction sender first withdraws all WETH using the  DAI flash loan, then converts  WETH for  BAT (using Uniswap). Finally the user creates  DAI using BAT as collateral, and pays back  DAI (with fee to Aave). This transaction converts the collateral from WETH to BAT and the user gained 

DAI, with an estimated gas fee of 


Iii-D Flash Minting

Cryptocurrency assets are commonly known as either inflationary (further units of an asset can be mined) or deflationary (the total number of units of an asset are finite). Flash minting is an idea to allow an instantaneous minting of an arbitrary amount of an asset — the newly-mined units exist only during one transaction. It is yet unclear where this idea might be applicable to, the minted assets could momentarily increase liquidity.

contract FlashMintableCoin is ERC20 { […]
    function flashMint(uint256 amount) {
        // mint coins and transfer them
        mint(msg.sender, amount);
        // borrower uses the loan
        // reverts if not have enough to burn
        burn(msg.sender, amount);
Fig. 4: Flash mint example.

Flash minting example: A flash mint function (cf. Figure 4) can be integrated into an ERC20 token, to mint an arbitrary number of coins within a transaction only. Before the transaction terminates, the minted coins will be burned. If the available amount of coins to be burned by the end of the transaction is less than those that were minted, the transaction is reverted (i.e. not executed). An example ERC20 flash minting code could take the following form666cf.

Actions within DeFi Flash loan txs Total amount(DAI) Mean gas used [t]
0x, Aave, Dai, Oasis, USDC, WETH9 2 5227.47 [t]
0x, Aave, Dai, Oasis, WETH9 1 1051.00
0x, Aave, Dai, WETH9 2 49.96
Aave, BAT, CollateralSwap, DSProxy, Dai, MakerDAO, Uniswap, WETH9 13 371.31
Aave, BAT, CollateralSwap, Dai, MakerDAO, Uniswap, Unkown, WETH9 2 40.03
Aave, Bancor, Dai, MakerDAO, OneLeverage, cDai, cEther 5 78.13
Aave, Compound, Dai, Kyber, MakerDAO, OneLeverage, cDai, cEther 6 151.27
Aave, Compound, Dai, MakerDAO, Oasis, OneLeverage, WETH9, cDai, cEther 9 2778.95
Aave, Compound, Dai, MakerDAO, Oasis, USDC, Unkown, cDai 1 0.00
Aave, Compound, Dai, MakerDAO, Oasis, Unkown, WETH9, cDai, cEther 1 9.13
Aave, Compound, Dai, MakerDAO, OneLeverage, Uniswap, cDai, cEther 8 425.66
Aave, Compound, Dai, MakerDAO, Uniswap, Unkown, cDai 1 0.00
Aave, Dai 9 5679.00
Aave, Dai, Kyber, MakerDAO, OneLeverage, cDai, cEther 12 2554.08
Aave, Dai, MakerDAO, Oasis, OneLeverage, WETH9, cDai, cEther 6 1220.93
Aave, Dai, MakerDAO, OneLeverage, Uniswap, cDai, cEther 11 117.50
Aave, Dai, MakerDAO, SAI, Uniswap 1 3137.41
Aave, Dai, MakerDAO, Uniswap, cDai, cEther 8 1368.71
Aave, Dai, Unkown 1 0.10
Aave, Unkown 6 0.00
Fig. 5: Classifying the usage of flash loans in the wild, based on an analysis of transactions between 8th of January, 2020 and the 26th of February, 2020 on Aave [aave]. Unknown indicates a private contract we could not attach an owner to.

Iv Flash Loan Post-Mortem

In this section we investigate how flash loans are used and outline in depth two malicious flash loan transactions which yielded an ROI beyond 500k%. To our knowledge, flash loans only appeared in the beginning of 2020.

Iv-a Flash Loan Uses in the Wild

We first consider flash loans offered by the Aave [aave] on the Ethereum blockchain, which started operating on the 8th of January 2020. To our knowledge this is one of the first DeFi platforms to widely advertise flash loan capabilities (although others, such as dYdX also allow the non-documented possibility to borrow flash loans). At the time of writing, Aave charges a constant 0.09% interest fee for flash loans and amassed a total liquidity of M USD.

We collect flash loan data between the 8th of January 2020 and the 26th of February 2020 with a full archive Ethereum node gathering all event logs of the Aave smart contract777address: 0x398eC7346DcD622eDc5ae82352F02bE94C62d119. We then map the transaction data to a known list of projects (cf. Appendix A). In Figure 5 we show our analysis of Aave flash loans, and manually label with which platforms the flash loans interacts with. We observe that most flash loans interact with lending/exchange DeFi systems and that the flash loan’s transaction costs (i.e. gas) appears significant (at times beyond 4M gas, compared to 21k gas for regular Ether transfer).

Iv-B Pump and Arbitrage

A flash loan transaction888executed on the 15th of February, 2020, transaction id: 0xb5c8bd9430b6cc87a0e2fe110ece6bf527fa4f170a4bc8cd032f768fc5219838, USD/ETH, followed by transactions, yielded a profit of ETH (k USD) given a transaction fee of  USD (cumulative  gas, ETH). We show in Section V-E that the parameters chosen by the adversary are not optimal, the adversary could have earned a profit exceeding 829.5k USD.

Fig. 6: Procedure diagram of the pump and arbitrage attack. Solid box represents a single state change operation, and dashed box represents aggregated state change operation. The attack consists of two parts a single flash loan transaction and several loan redemption transactions. The numbers within rectangles represent the optimal parameters found by our parametrized optimizer (cf. Section V).

Attack intuition: The core of this trade utilises a margin trade on a DEX (bZx) to increase the price of WBTC/ETH on another DEX (Uniswap) and thus creates an arbitrage opportunity. The trader then borrows WBTC using ETH as collateral (on Compound), and then purchases ETH at a “cheaper” price on the distorted (Uniswap) DEX market. To maximise the profit, the adversary then converts the “cheap” ETH to purchase WBTC at a non-manipulated market price over a period of two days after the flash loan. The adversary then returns WBTC (to Compound) to redeem the ETH collateral. As demonstrated in Figure 6, this trade mainly consists of two parts. For simplicity, we omit the conversion between WETH (the ERC20-tradable version of ETH) and ETH.

Flash Loan (one block): The first part of the attack (cf. Figure 6) consists of 7 steps within a single transaction. In step

, the adversarial trader borrows a flash loan of ETH from a flash loan provider (dYdX). In step


, the adversarial trader uses out of the ETH as collateral, to borrow WBTC on a lending platform (Compound). More specifically, the adversary first deposits ETH to Compound, in exchange of cETH (cTokens) as a proof of owning this liquidity. The adversary then borrows WBTC (on Compound) using the cETH tokens as collateral. Note that the adversarial trader does not return the WBTC within the flash loan. This means the adversarial trader takes the risk of forced liquidation against the cETH collateral if the price fluctuates. In steps 

, the trader opens a short position for ETH against WBTC (on bZx), with a  leverage. Upon receiving this request, bZx transacts ETH on an exchange (Uniswap) for only  WBTC (at  ETH/WBTC). Note that at the start of block 9484688, Uniswap has a total supply of  ETH and  WBTC (at  ETH/WBTC). The slippage of this transaction is significant with  (cf. Equation 1).


Both DEXes, Uniswap and bZx, allowed for such high slippage to occur. In step 

, the trader converts WBTC borrowed from lending platform (Compound) to ETH on DEX (Uniswap) (at ETH/WBTC). Similarly, the slippage can be calculated per Equation 2.


In step 

, the trader pays back the loan, paying a Wei fee. Note that dYdX only requires a fee of Wei. After the flash loan transaction (i.e. the first part of this pump and arbitrage trade), the trader gained  ETH, and has an over-collateralized loan of  ETH for  WBTC ( ETH/WBTC). If the ETH/WBTC market price is above this loan exchange rate, the adversary can redeem the loan’s collateral as follows.

Loan redemption: The second part of the trade consists of three recurring steps, (step 


), between Ethereum block 9484917 and 9496602. Those transactions aim to redeem ETH by paying back the WBTC borrowed earlier (on Compound). To avoid slippage when purchasing WBTC, the trader executes the second part in small amounts over a period of two days on the DEX (Kyber, Uniswap). In total, the adversarial trader exchanged  ETH for  WBTC (at  ETH/WBTC) to redeem  ETH.

Finding the victim: We investigate who of the participating entities is losing money. Note that in step

of Figure 6, the short position (on bZx) borrows ETH from the lending provider (bZx), with  ETH collateral. Step

requires to purchase WBTC at a price of ETH/WBTC, with both, the adversary’s collateral and the pool funds of the liquidity provider. ETH/WBTC does not correspond to the market price of  ETH/WBTC prior to the attack, hence the liquidity provider overpay by nearly a magnitude of the WBTC price.

How much are the victims losing: We now quantify the losses by the liquidity providers. The loan provider lose (ETH from loan providers) - (WBTC left in short position) (market exchange rate ETH/WBTC) = ETH. The adversary gains  (ETH loan collateral in Compound) - (ETH spent to purchase WBTC) + (part 1) = ETH in total.

Arbitrage: is more money left on the table: Due to the attack, Uniswap’s price reduced from  to  ETH/WBTC. This creates an arbitrage opportunity, where a trader can sell ETH against WBTC on Uniswap to synchronize the price. ETH would yield  WBTC, instead of  WBTC, realizing an arbitrage profit of WBTC ( USD).

Fig. 7: Procedure diagram of the oracle manipulation attack. Solid box represents a single state change operation, and dashed box represents aggregated state change operation. The numbers within rectangles represent the optimal parameters found by our parametrized optimizer (cf. Section V).

Iv-C Oracle Manipulation

In the following, we discuss the details of a second flash loan trade, which yields a profit of ETH (c. k USD) within a single transaction999executed on the February , transaction id: 0x762881b07feb63c436dee38edd4ff1f7a74c33091e534af56c9f7d49b5ecac15, 282.91 USD/ETH given a transaction fee of  USD. Before diving into the details, we cover additional required background knowledge. We again show how the chosen attack parameters were sub-optimal and present in Section V-E attack parameters that would yield a profit of 1.1M USD instead. For this attack, the adversary involves three different exchanges for the same sUSD/ETH market pair (the Kyber-Uniswap reserve, Kyber, and Synthetix). Two of these exchanges (Kyber, Kyber-Uniswap) act as price oracle for the lending platform (bZx) from which the adversary borrows assets.

Price oracle: One of the goals of the DeFi ecosystem is to not rely on trusted third parties. This premise holds both for asset custody as well as additional information, such as asset pricing. One common method to determine an asset price is hence to rely on the pricing information of an on-chain DEX (e.g. Uniswap). One drawback of this approach, is the danger of a DEX price manipulation.

Attack intuitionn: The core of this trade is an oracle manipulation using a flash loan on the asset pair sUSD/ETH. The manipulation lowers the price of sUSD/ETH (from  sUSD/ETH to  sUSD/ETH on Uniswap and  sUSD/ETH on Kyber Reserve). In a second step, the adversary benefits from this sUSD/ETH price decrease by borrowing ETH with sUSD as collateral.

Adversarial oracle manipulation: We identify a total of 6 steps steps within this transaction (cf. Figure 7). In step 

, the trader borrows a flash loan of  ETH (on bZx). In the next three steps (



), the adversary converts a total of  ETH to  sUSD (at an average of  sUSD/ETH). Step

purchases sUSD with ETH at  sUSD/ETH (on the Kyber-Uniswap reserve) and step

purchases sUSD with ETH at  sUSD/ETH (on Kyber). The third involved party is the lending platform bZx, which uses the DEX Kyber as a price oracle. Step 


allow the adversary to borrow more sUSD with ETH, because the price of sUSD/ETH perceived by the lending platform decreased by over % since the beginning of the attack. Step 

converts ETH to sUSD on a third exchange market (Synthetix), which is yet unaffected by the previous trades. This exchange is not serving as price oracle for the lending platform (bZx).

The adversarial trader then uses the sum of the purchased sUSD () as collateral to borrows  ETH (at  sUSD/ETH on bZx). Now the adversary possesses  ETH and in the last step pays back the flash loan amounting to  ETH. The adversary therefore generates a revenue of  ETH while only paying  ETH ( USD) transaction fees.

Finding the victim: The adversary distorted the price oracle (i.e. Uniswap and Kyber) from  sUSD/ETH to  sUSD/ETH, while other DeFi platforms remain unaffected with  sUSD/ETH. Similar to the Pump and Arbitrage attack, the lenders on bZx are the victims losing cryptocurrency as a result of the distorted price oracle. The lender lost  ETH -  sUSD, which is estimated to be  ETH (at sUSD/ETH). The adversary gains (ETH from borrowing) - (ETH to purchase sUSD) - (ETH to purchase sUSD) - (ETH to purchase sUSD) = ETH.

V Optimal DeFi Attack Parameter Generation

In light of the complexity of the aforementioned DeFi attacks (cf. Section IV), in this section we propose a constrained optimization framework that allows to efficiently discover the optimal trade parameters to maximize the resulting expected revenue.

V-a System Model and Assumptions

The system considered is limited to one decentralized ledger which supports pseudo-Turing complete smart contracts (e.g. similar to the Ethereum Virtual Machine; state transitions can be reversed given certain conditions, such as out-of-gas, or insufficient funds returned). Our system comprises of regular users, or traders, which do hold at least one private/public key pair to denote their blockchain address. The private key enables users to transfer cryptocurrency assets and interact/invoke smart contracts.

We assume that the underlying blockchain is not compromised by a malicious adversary. We therefore assume that the share of consensus participants corrupted by the adversary is bounded by the threshold required to maintain safety and liveness of the underlying blockchain. In the Nakamoto consensus-based blockchains, for example, we assume that the fraction of the computational power of the adversary does not exceed   [gervais2016security, garay2015bitcoin]. Similarly, in Byzantine fault-tolerant systems, (e.g. Proof-of-Stake based), we assume that the number of faulty processes does not exceed  of the number of consensus participants. The previous assumptions guarantee the chain quality and common-prefix properties [garay2015bitcoin]. We consider a transaction to be securely included within the blockchain after confirmations, where depends on the transaction value [gervais2016security] and the chain-growth property [garay2015bitcoin].

Importantly, flash loans only apply to a single transaction and hence we limit our analysis to what may happen within a single blockchain block.

V-B Threat and Network Model

Foremost, we assume that the cryptographic primitives of the considered blockchain are secure. We also assume the presence of at least one computationally-bounded and economically rational adversary . attempts to exploit the availability of flash loans for financial gain. may perform any action that maximizes its economic revenue, such as censor or delay transactions, observe unconfirmed transactions on the network layer or the memory pool, and mount Sybil attacks [douceur2002sybil]. For the network layer we follow related work [eyal2016bitcoin, david2018ouroboros] in assuming that honest nodes are well-connected, and that communication channels are semi-synchronous. Importantly, we assume that transactions broadcast by users are received by honest users within an upper bound time. The adversary may collude with other adversaries. While is not required to provide its own collateral to perform the presented attacks, the adversary must be financially capable to pay transaction fees. The adversary may amass more capital which possibly could increase its impact and ROI.

V-C Modelling the State of DeFi

We start by modeling different components that may engage in a DeFi attack. To facilitate optimal parameter solving, we quantitatively formalize every endpoint provided by DeFi platforms as a state transition function with the constraints , where is the given state, are the parameters chosen by the adversary and is the output state. The state can represent, for example, the adversarial balance or any internal status of the DeFi platform, while the constraints are set by the execution requirements of the Ethereum Virtual Machine (e.g. the Ether balance of an entity should never be a negative number) or the rules defined by the respective DeFi platform (e.g. a flash loan must be repaid before the transaction termination plus loan fees). Note that when quantifying profits, we ignore the loan interest/fee payments and Ethereum transaction fees, which are negligible in the present DeFi attacks. The constraints are enforced on the input parameters and output states to ensure that the optimizer yields valid parameters.

We define the balance state function to denote the balance of currency held by entity at a given state . The constraint of Equation 3 must always be satisfied.


In the following, we detail the quantitative DeFi models applied in this work. Note that we do not include all the states involved in the DeFi attacks but only those relevant to the constrained optimization.

Flash loan: We assume a flash loan platform with amount of asset , which the adversary can borrow. The required interest to borrow of is represented by .

State: In a flash loan, the state is represented by the balance of , i.e. .

Transitions: We define the transition functions of Loan in Equation 4 and Repay in Equation 5, where the parameter denotes the loaned amount.


Fixed price trading: We define the endpoint Sellfor that allows the adversary to trade amount of for at a fixed price . is the maximum amount of available for trading.

State: We consider the following state variables:

  • Balance of asset held by :

  • Balance of asset held by :

Transitions: Transition functions of Sellfor are defined in Equation 6.


Constant product automated market maker: The constant product AMM is with a market share of 77% among the AMM DEX, the most common AMM model in current DeFi ecosystem [uniswap2018]. We denote by an AMM instance with trading pair and exchange fee rate .

State: We consider the following states variables that can be modified in an AMM state transition.

  • Amount of in AMM liquidity pool: , which equals to

  • Amount of in AMM liquidity pool: , which equals to

  • Balance of held by :

  • Balance of held by :

Transitions: Among the endpoints of , we focus on Swapfor and Swapfor, which are the relevant endpoints for the DeFi attacks discussed within this work.  is a parameter that represents the amount of the adversary intends to trade. inputs amount of in AMM liquidity pool and receives amount of as output. The constant product rule [uniswap2018] requires that Equation 7 holds.


We define the transition functions and constraints of Swapfor in Equation 8 (analogously for Swapfor ).


Because an AMM DEX transparently exposes all price transitions on-chain, it can be used as a price oracle by the other DeFi platforms. The price of with respect to given by at state is defined in Equation 9.


Automated price reserve: The automated price reserve is another type of AMM that automatically calculates the exchange price depending on the assets hold in inventory. We denote a reserve holding the asset pair with . A minimum price and a maximum price is set when initiating . relies on a liquidity ratio parameter to calculate the asset price. We assume that holds amount of at state . We define the price of in Equation 10.


The endpoint Convertto provided by allows the adversary to exchange for .

State: We consider the following state variables:

  • The inventory of in the reserve: , which equals to

  • Balance of held by :

  • Balance of held by :

Transitions: We denote as the amount of that inputs in the exchange to trade against . The exchange output amount of is calculated by the following formulation.

We define the transition functions within Equation 11.


Collateralized lending & borrowing: We consider a collateralized lending platform , which provides the CollateralizedBorrow endpoint that requires the user to collateralize an asset with a collateral factor (s.t. ) and borrows another asset at an exchange rate . The collateral factor determines the upper limit that a user can borrow. For example, if the collateral factor is , a user is allowed to borrow up to 75% of the value of the collateral. The exchange rate is for example determined by an outsourced price oracle. denotes the maximum amount of available for borrowing.

State: We hence consider the following state variables and ignore the balance changes of for simplicity.

  • Balance of asset held by :

  • Balance of asset held by :

Transitions: The parameter represents the amount of asset that aims to collateralize. Although is allowed to borrow less than his collateral would allow for, we assume that makes use the entirety of his collateral. Equation 12 shows the transition functions of CollateralizedBorrow.


can retrieve its collateral by repaying the borrowed asset through the endpoint CollateralizedRepay. We show the transition functions in Equation 13 and for simplicity ignore the loan interest fee.


Margin trading: A margin trading platform allows the adversary to short/long an asset by collateralizing asset at a leverage , where .

We focus on the MarginShort endpoint which is relevant to the discussed DeFi attack in this work. We assume shorts with respect to on . The parameter denotes the amount of that collateralizes upfront to open the margin. represents the amount of held by that is available for the short margin. is required to over-collateralize at a rate of in a margin trading. In our model, when a short margin (short with respect to ) is opened, performs a trade on external markets (e.g. Uniswap) to convert the leveraged to . The traded is locked until the margin is closed or liquidated.

State: In a short margin trading, we consider the following state variables:

  • Balance of held by :

  • The locked amount of :

Transitions: We assume transacts from an external market at a price of . The transition functions and constraints are specified in Equation 14.


V-D Parametrized Optimization

Our parametrized optimizer (cf. Figure 1) is designed to solve the optimal parameters that maximizes the revenue given an on-chain state, Defi models (cf. Section V-C) and attack vector. An attack vector specifies the execution order of different endpoints across various DeFi platforms, depending on which we formalize a unidirectional chain of transition functions (cf. Equation 15).


By nesting transition functions, it is trivial to obtain the cumulative state transition functions that satisfy Equation 16, where .


Therefore the constraints generated in each step can be expressed as Equation 17.


We assume an attack vector composed of transition functions. The objective function can be calculated from the initial state and the final state (e.g. the increase of the adversarial balance).


Given the initial state , we formulate an attack vector into a constrained optimization problem with respect to all the parameters (cf. Equation 19).


V-E Optimizing the Pump and Arbitrage

Description Variable Value
Maximum Amount of ETH to flash loan
Collateral Factor [t]
Collateralized Borrowing Exchange Rate
Maximum Amount of WBTC to Borrow
Uniswap Reserved ETH
Uniswap Reserved WBTC
Over Collateral Ratio
Maximum Amount of ETH to leverage
Market Price of WBTC
Fig. 8: Initial on-chain states of the pump and arbitrage attack.

In the following, we evaluate our parametrized optimization framework on the existing attacks described in Section IV. Figure 8 summarizes the on-chain state when the attack was executed (i.e. ). We use these blockchain records as the initial state in our evaluation. and denote ETH and WBTC respectively. For simplicity, we ignore the trading fees in the constant product AMM (i.e.  for ). The endpoints executed in the pump and arbitrage attack are listed in the execution order as follows.

  1. Loan (dYdX)

  2. CollateralizedBorrow (Compound)

  3. MarginShort(bZx) & Swapfor (Uniswap)

  4. Swapfor (Uniswap)

  5. Repay (dYdX)

  6. Sellfor & CollateralizedRepay(Compound)

In in the pump and arbitrage attack vector, we intend to tune the following two parameters, (i) : the amount of collateralised to borrow in the endpoint 2) and (ii) : the amount of collateralised to short in the endpoint 3). Following the procedure of Section V-D, we proceed with detailing the construction of the constraint system.

0): We assume the initial balance of owned by is (cf. Equation 20), and we refer the reader to Figure 8 for the remaining initial state values.


1) Loan: gets a flash loan of amounts in total

with the constraints

2) CollateralizedBorrow: collateralizes amount of to borrow from the lending platform

3) MarginShort & Swapfor: opens a short margin with amount of at a leverage of on the margin trading platform ; swaps the leveraged for at the constant product AMM

4) Swapfor: dumps all the borrowed at

5) Repay: repays the flash loan

6) Sellfor & CollateralizedRepay: buys from the market with the market price and retrieves the collateral from

The objective function is the adversarial ETH revenue (cf. Equation 21).


Constraints: We summarize the constraint in Figure 9, five linear constraints and one nonlinear constraint, which implies that the optimization can be solved efficiently.

Constraints ,
Fig. 9: Constraints generated for the pump and arbitrage attack. We remark that is a nonlinear component with respect to  and .

V-F Optimizing the Pump and Arbitrage Attack

We apply the Sequential Least Squares Programming (SLSQP) algorithm from SciPy101010 We use the minimize function in the optimize package. to solve the optimization problem. Our program is evaluated on a Ubuntu 18.04.2 machine, CPU cores and GB RAM. We repeated our experiment for times, the optimizer spent ms on average converging to the optimum.

Optimal pump and arbitrage parameters: The optimizer provides a maximum revenue of  ETH when setting the parameters to , while in the original attack the parameters only yield  ETH. Note, due to the ignorance of trading fees and precision differences, there is a minor discrepancy between the original attack revenue calculated with our model and the real revenue which is  ETH (cf. Section IV). This is a 829.5k USD gain over the attack that took place, using the price of ETH at that time.

Optimal parameter validation: We experimentally validate the optimal pump and arbitrage attack by forking the Ethereum blockchain with Ganache111111 at block 9484687 (one block prior to the original attack transaction). We then implement the pump and arbitrage attack in solidity v0.6.3. In the Pump and Arbitrage attack, revenues are divided into two parts: part one from the flash loan transaction, and part two which is a follow-up operation in later blocks (cf. Section IV) to repay the loan. For simplicity, we chose to only validate the first part, abiding by the following methodology: (i) We apply the parameter output of the parametrized optimizer, i.e.  to the adversarial validation smart contract. (ii) Note that our model is an approximation of the real blockchain transition functions. Hence, due to the inaccuracy of our model we cannot directly use the precise model output, but instead use the model output as a guide for a manual, trial and error search. We find  is the maximum value of that allows the successful adversarial trade. (iii) Given the new constraint, our optimizer outputs the new optimal parameters . (iv) Our optimal adversarial trade yields a profit of  ETH part one revenue (as opposed to  ETH for the original attack). Executing our attack consumes a total of M gas. We note that these cumbersome manual parameter adjustments would be unnecessary with a more precise DeFi model.

V-G Optimizing the Oracle Manipulation Attack

In the oracle manipulation attack, denotes ETH and denotes sUSD. Again, we ignore the trading fees in the constant product AMM (i.e.  for ). The initial state variables are presented in Figure 10. We assume that owns zero balance of  or . We list the endpoints involved in the oracle manipulation attack vector as follows.

  1. Loan(bZx)

  2. Swapfor(Uniswap)

  3. Convertto(Kyber reserve)

  4. Sellfor(Synthetix)

  5. CollateralizedBorrow(bZx)

  6. Repay(bZx)

Description Variable Value
Maximum Amount of ETH to flash loan
Uniswap Reserved ETH
Uniswap Reserved sUSD
Liquidity Rate
Minimum sUSD Price of Kyber Reserve
Maximum sUSD Price of Kyber Reserve
Inventory of ETH in Kyber Reserve
Market Price of sUSD
Maximum Amount of sUSD to Buy
Collateral Factor
Maximum Amount of ETH to Borrow
Fig. 10: Initial on-chain states of the oracle manipulation attack.

There are three parameters to optimize in this attack, (i) : the amount of used to swap for in step 2); ii the amount of used to swap for in step 3); (iii) the amount of used to exchange for in step 4). We construct the constrained optimization problem as follows.

1) Loan: gets a flash loan of amounts

with the constraints

2) Swapfor: swaps amount of for from the constant product AMM

3) Convertto: converts amount of to from the automated price reserve

4) Sellfor: sells amount of for at the price of

5) CollateralizedBorrow: collateralizes all owned to borrow according to the price given by the constant product AMM (i.e. the exchange rate )

with the constraint

6) Repay: repays the flash loan

The objective function is the remaining balance of after repaying the flash loan (cf. Equation 22).

Constraints , ,
Fig. 11: Constraints generated for the oracle manipulation attack. We remark that and are nonlinear components with respect to , and .

Constraints: We summarize the produced constraints of the oracle manipulation attack vector in Figure 11. Five constraints are linear and the other two are nonlinear.

V-H Finding Optimal Oracle Manipulation Parameters

We execute our optimizer  times on the same Ubuntu 18.04.2 machine with  CPU cores and  GB RAM. The average convergence time is ms.

Optimal oracle manipulation parameters: The optimizer discovers that setting to results in about  ETH in profit for the adversary. This results in a gain of 1.1M USD instead of about k USD.

Optimal parameter validation: We fork the Ethereum blockchain with Ganache at block 9504626 (one block prior to the original adversarial transaction). We then implement the oracle manipulation attack solidity v0.6.3. We validate that executing the adversarial smart contract with parameters renders a profit of ETH, while the original attack parameters yield ETH. The attack consumes M gas (which exceeds the block gas limit (M) on the Ethereum main network). By analyzing the adversarial validation contract, we find  is the maximum value of that makes the gas consumption under the block limit. Following the similar methodology in Section V-F, we add the new constraint to the optimizer, which then gives the optimal parameters . The augmented validation contract makes a profit of  ETH and consumes M gas.

Vi Discussion

The current generation of DeFi had developed organically, without much scrutiny when it comes to financial security; it, therefore, presents an interesting security challenge to confront. DeFi, on the one hand welcomes innovation and the advent of new protocols, such as MakerDAO, Compound, and Uniswap. On the other hand, despite a great deal of effort spent on trying to secure smart contacts [luu2016making, jiang2018contractfuzzer, echidna2020, wustholz2019harvey, tsankov2018securify], and to avoid various forms of market manipulation, etc. [mavroudis2019market, mavroudis2019libra, bentov2017tesseract], there has been little-to-no effort to secure entire protocols.

As such, DeFi protocols join the ecosystem, which leads to both exploits against protocols themselves as well as multi-step attacks that utilize several protocols such as the two attack in Section