# Flash Loans: Finance on Steroids

Subscribe to the mailing list!

All the views expressed below are the personal views of the author, and are not financial or investment advice.

Traders and other finance professionals have always had to contend with the risk that the information they are acting on is stale. In the world of DeFi, so-called flash loans have given participants the ability to not only make multi-leg trades atomic, but also access to near infinite leverage. In this article we will cover how these special loans work, and also some legitimate (and some less legitimate) uses of them.

## A Refresher on Regular Loans

Before we get into flash loans, it is worth covering the basics of how regular loans work. If you are already familiar with this, then feel free to skip ahead to the next section.

A loan is probably one of the simplest financial constructs that exists. It is a transaction involving (in its simplest form) two parties: the borrower and the lender.

1. A borrower borrows a fixed sum of money (the principal) from a lender.
2. After some time (or on a schedule), the borrower must pay back the principal amount, plus any interest that accrued on the loan.

As such, borrowing money gives the borrower access to funds now, at the cost of having to pay back the same amount and more in the future. This is why taking out a loan is sometimes phrased as “borrowing money from your future self”, since it is your future self who will have to earn that money to pay it back. The whole idea however, is that if getting the money now is more valuable than getting the same money in the future (factoring in the interest), then it is something worth doing (see also time value of money).

### Interest

When a borrower takes out a loan, they will need to pay interest. Interest is a percentage rate e.g. 1% which will need to be paid at some scheduled time. These rates are typically annualised, meaning that they are scaled so that they represent how much interest you would need to pay if you held the loan for a year. Interest is also typically calculated and charged at certain times. For mortgage loans (loans for buying a house) this will typically be daily. How frequently this happens is sometimes referred to as how often a loan compounds (from compound interest). This is done pro rata (proportional) from the rate. So if the annual rate is 10%, then the daily rate charged would be $\frac{10\%}{365} \approx 0.027\%$ daily.

There are two ways that these concepts are typically represented:

Annual Percentage Rate (APR)
The interest rate not taking into account compounding. If the monthly interest rate is 1%, then the APR is $12 \times 1\% = 12\%$. Typically however, the APR is just stated as is.

Annual Percentage Yield (APY)
The interest rate that takes into account compounding, and represents the actual amount that would be paid if the interest was compounded over one year. For instance, if our APR was 10%, then our APY would be (taking into account daily compounding) $100 \times ((1 + \frac{0.1}{365})^{365} - 1) \approx 10.52\%$

### Collateral

With any loan, there is always some risk for the lender. Most lenders are rarely willing to hand out loans willy-nilly. After all, it is their own money at risk, and they want some sort of security that the loan will be able to be paid back. This can take many forms:

• A credit check. This is an assessment (usually done by a third party) that assesses your earnings, current debts, and various other factors and gives you a score as to how “credit worthy” you are. If you have a load of bad loans, and barely any income it is unlikely a bank will be willing to offer you credit.

• A guarantor. Someone who is willing to put their name on the line so that if you are unable to pay back the loan, they will be on the hook. This is often seen in arrangements such as children buying their first house, and the parents helping them get the loan in the first place by acting as guarantors.

• So-called income-driven repayment which is a legal setup where the lender is entitiled to some fraction of your salary while the loan is still outstanding. This is commonly used for student loans.

• Most frequently, collateral for the loan. This is some cash or asset that is given up to the lender to secure the loan. The most common version of this that people are familiar with is a mortgage where the house itself is the collateral, but this can also be anything valuable such as e.g. a Rolex watch given to a pawn shop. If you default on the loan, the lender has the right to take your collateral and liquidate (sell) it to recoup their losses.

The concept of collateral was also covered in some detail in the article on leverage & liquidations if you want to see a different take on it.

What happens if the borrower cannot (or will not) pay the loan back? If this occurs, the loan is said to be in default. What happens afterwards however, depends on what the terms of the loan were. Depending on the loan, the lender (at least in traditional finance) can claim the collateral, but also has the option of taking the borrower to court to e.g. seize their other assets if they are unable to pay the loan.

If the market value of the collateral is less than the principal of the loan, the loan is said to be under collateralised. If your credit score is good enough, then a lender may be willing to extend you such a loan. Credit cards are a good example of this, since you typically do not have to put up any collateral to get access to one. The lender however, can still try and take you to court if you fail to pay. Normally such loans do not have a very large principal.

If a loan is over collateralised that means that the collateral that has been put up for the loan is worth more than the principal of the loan itself. Such loans are popular in what we might call low trust environments which would include such things as pawn shops and (heh) crypto. In the case of the latter, there is always a risk that if the loan was under collateralised, then the borrower could take whatever they borrowed and simply disappear, leaving the lender with an asset that is worth less than the loan that they gave out.

At first, it may seem strange that someone would take out a loan that is worth less than what they put up, however this is typically done because the borrower requires cash immediately, or does not wish to sell the asset, but instead borrow against it. It can also supposedly be used to reduce taxes by living off of money borrowed against assets, instead of taking a salary.

## The Basics of How Smart Contracts Work

I won’t go into the whole blockchain explanation too deeply as by this point it’s been done to death, though if you are looking for an introduction this series is not bad. Instead, I will go over how smart contract execution works in terms of blocks and transactions. Again, if you know all this stuff already feel free to skip ahead.

I will also be basing this mainly on how the Ethereum Virtual Machine or EVM works, though other chains will usually work in a vaguely similar way. The following document outlines some of these concepts quite well, and the next few paragraphs summarise and simplify it.

Smart contracts are special programs that run on a blockchain. Just like any computer program, they are essentially a series of instructions that cause the state of the computer to change. State (and more broadly state of the world) here refers to various stateful properties in the chain. The main one would be balances of coins in different accounts, but with smart contracts this can be anything e.g. the balances in an AMM. To change from one state to the next a transaction is required. In diagram form, it can be represented as a state machine.

For instance, consider if we have two clients A and B, and A has 10 ETH that they want to transfer to B who only has 5 ETH. In order to do this, we would need to put a transfer transaction into the blockchain. This transfer can be modeled like so:

Smart contracts essentially work the same way, but are more complicated. Smart contract will usually have an API which is a set of functions that can be called with certain parameters. For instance, if we consider an Automated Market Maker (AMM), then we might have the following functions that can be called (this is highly simplified):

• deposit: Deposit funds into the AMM. The user would need to provide parameters for which AMM they want to deposit to, and the amount of each token to deposit.
• withdraw: Same as deposit, but this time withdraw your deposited tokens. The user would need to provide the amount of liquidity provider tokens as one of the parameters.
• swap: Swap some tokens for another in the AMM. The user would need to provide the amount of tokens they want to swap, slippage tolerance, and various other parameters.

Each of these functions (and other functions on other programs) can be called in sequence, and packed into one transaction. The diagram below illustrates how several instructions such as deposits and swaps can be arranged (in sequence) in a transaction to do several things at once.

Similarly, transactions themselves are organised into blocks. Each block contains a number of transactions, and this is the block that is “mined” on the chain. These blocks connected in order form the “blockchain” that gives the concept of ordering and time in the chain. As we move from left to right, and up to down the transactions are applied to the Ethereum state in order.

There are some important concepts here that also need to be understood (these will be important later):

1. All transactions are sequenced (they happen one after the other) globally. In other words, only one transaction can happen at a time for the whole chain.
2. Each transaction is atomic, meaning that the transaction must be carried out as one, and it cannot be e.g. partially carried out.
3. If a transaction fails, then all the instructions it tried to carry out are rolled back, i.e. they never happened.

## What is a Flash Loan?

Loans in the DeFi ecosystem are a commodity product. There are numerous lenders available, with a variety of rates and collateral requirements. Flash loans however are in a category of their own, and a much more advanced product. So what exactly is a flash loan, and what’s so special about it?

Probably the most succinct definition can be found in the documentation for Aave, a platform that offers flash loans:

Flash loans are a feature designed for developers, due to the technical knowledge required to execute one. Flash Loans allow you to borrow any available amount of assets without putting up any collateral, as long as the liquidity is returned to the protocol within one block transaction.

In the first sentence, they lay out an important caveat: Flash loans are not a product that is readily available to retail customers. While of course in theory anyone can make use of one (it is DeFi after all), to do so requires a fairly high level of technical skill and familiarity with programming and deploying smart contracts. It is definitely not a one click affair.

The second sentence covers the functionality that the flash loan provides. A flash loan is a loan which is fully uncollateralised. That means that you can take out a flash loan, and not put up any capital at all, zero. In addition, you are allowed to borrow as much money as you want… well, as much money as the platform has. Sounds great, but there is a catch: You must return the principal plus interest, all within one transaction. The last part is the reason that they are called “flash” loans. You have to take out the loan and return it almost instantly.

From the perspective of someone working in traditional finance this might seem completely insane. Someone is giving out as much money as you want, at low interest rates (as we will see later), and with no down payment required. Such a thing would basically never occur in the real world, barring sketchy deals with various unsavoury characters. Nevertheless, it is very much real, and it makes a lot more sense if you recall what we covered in the prior section about atomic transactions.

As mentioned previously, within each transaction there are multiple instructions. These instructions can be simple such as transferring some money, or as complex as trading tokens, or adding liquidity, etc. Remember that our constraint is that within one transaction, we must return both the principal as well as some fixed interest rate. In the below cases we will cover two possible outcomes when taking out a flash loan.

### Profitable Case

Consider therefore, that there is some (clever) function that we have come up with called makeMoney(amount). When called, this function will make us some money. How it works is super secret, but let’s say it does something clever like e.g. exchange arbitrage (more on this later). The function takes a parameter amount that tells it how much money to use to make a profit, in this case we will go with \$1,000. The amount of money the function makes will be profit which is 10% of amount. So if we call it, we end up with amount + profit in our wallet. We want to use makeMoney() to well… make some money, but we don’t have much money ourselves, and want to take full advantage of the opportunity. Fortunately, a flash loan offers us access to near unlimited capital. But how do we set this up, so we can use the flash loan? In order to do it, we have to make sure that we take out the loan, use that money to make a profit, and then pay back the principal plus the interest. Let’s say that the flash loan charges 1% of the principal as interest. The following transaction structure would be required: Once we have made our money, and repaid our flash loan, we are left with a small profit (\$90) in our wallet. Instantly.

### Unprofitable Case

With the flash loan above, we were able to pay back the loan + the interest and even got to keep the profit that we made using the money from the flash loan. Imagine that we are not a very good trader, and we have a function that actually loses us money (say 10% of the amount given to it). To do this we will use a function loseMoney(amount). What would happen if we put together a transaction using this function to lose money?

Notice what happened. We lost money on running the function, and were therefore unable to pay back the loan. In this case, the flash loan program would invalidate the transaction. Recall that we said earlier that transactions are atomic, and that either the whole transaction happens, or none of it happens. What the blockchain has done is essentially first “simulate” what would happen if we took out the loan, ran the function, and repaid the loan.

Because it sees that we would be unable to pay the loan back, it simply rejects that transaction, and does not allow it to “really” happen. Since one step of the transaction was invalid, the whole transaction is invalid, and it’s like we never took the loan. The only money we would lose, would be gas fees used trying to carry out the transaction.

## Arbitrage Opportunities

We’ve covered how these loans work in a theoretical case with fake functions. One of the biggest use cases of these loans in real life is carrying out “risk-free” price arbitrage. We have covered arbitrage briefly in the article on AMMs, but here we will cover some of the operational details that are important when implementing such a strategy in the real world. Arbitrage is when a market participant finds the same asset being sold at one venue at a lower price than it is being bought at another venue, and takes advantage of it.

If ETH is being sold for \$4,000 on exchange A, and being bought for \$4,100 on exchange B then there is an arbitrage opportunity. A participant could buy 1 ETH on exchange A, sell it on exchange B, and make $\$4,100 - \$4,000 = \$100$in profit with essentially no risk (assuming they can do this instantly, more on this later). Arbitrage is the mechanism that keeps different exchanges trading the same products in line price wise, since any price differences will quickly be taken advantage of to make risk-free money. ### Traditional Market Arbitrage The concept of arbitrage has been around since at least several hundred years BC and probably even longer. In ancient times, most arbitrage could be called “geographic arbitrage” since due to the lack of fast communication, various commodities might be priced differently in different cities / countries. Today, despite electronic communication being ubiquitous, things are not actually that different. What would once have been the trade routes between countries are now the fiber optic cables that make up the backbone of the internet. The routes are faster, but they still have a speed limit:$c$, the speed of light. For example, for an electronic message to travel from New York to Hong Kong ($\approx 13,000$km), it would take around 44 milliseconds (less than$\frac{1}{20}$th of a second) in the best case, and likely more with network switching and other things in between. That might not seem like a long time, but in financial markets milliseconds can make all the difference. In the case of arbitrage, one of the key problems is timing risk. Namely, the arbitrage only works if the prices are what you expect them to be when your order reaches the exchange. We will demonstrate this risk using a sequence diagram that shows the order of events and messages sent when doing an arbitrage. Here we consider two venues A and B which both trade the ETH/USD pair. Arrows represent messages, and the direction of time is downwards. In the above diagram the client sees that the prices between A and B give them an arbitrage opportunity. They send one order to buy 1 ETH at A, and then subsequently send another order to sell 1 ETH on exchange B. However, between the client and the exchange there is a time delay for the message to be received. Just after they sent the sell order, they got a (delayed) message from exchange B saying the price had changed in the meantime. This means that this client ended up executing the sell at \$3,900 instead of \$4,100 as they expected (assuming market orders for simplicity). Because of this, they lost$\$3,900 - \$4,000 = -\$100$.

Of course, you could optimise this by sending both orders at once, or by using limit orders etc. However, you are still exposed to this risk, since you might e.g. buy one side, but not be able to sell the other. Then you are long ETH and are exposed to any price fluctuations. The whole idea is for the profit to be risk-free, and to do that requires holding on to the assets for as little time as possible (ideally 0).

### Arbitrage with Flash Loans

As we saw, the difficulty with arbitraging between exchanges is that there is always a risk that the price will change before you are able to execute your instructions. You can try and speed it up as much as you want, but you will never be able to beat the speed of light (well, not yet anyway). The beauty of using flash loans for arbitrage, is that you CAN deterministically say what the price at each exchange is!

This is possible because within one transaction, the world does not change. Each transaction is atomic, and that means that while that transaction is happening, nothing else can change. If you look at the price on a DEX while executing a transaction, that’s the price you will get 100% guaranteed. It is the equivalent of stopping time, and being able to do anything you want while time is stopped.

This makes arbitrage on DeFi almost completely deterministic. An arbitrageur can monitor the chain to identify profitable arbitrage opportunities. If they see one, all they need to do is put together a flash loan transaction to borrow some money (as much as the opportunity will allow), buy/sell the assets to make a profit, and then repay the loan and pocket the difference. Assuming your arbitrage calculation makes sense, there are only two outcomes:

1. The arbitrage is profitable. You pay back the loan plus interest, and keep the profits.
2. The prices on the exchanges have changed as you were putting together the transaction, and now the arbitrage is not profitable. In this case, the flash loan contract identifies that you do not have the money to pay back the loan, and the transaction is invalidated. You lose a small amount of gas fees.

Notice that there is still some timing risk, but it is very minimal. The only money at risk is the gas fees for the transaction, there is no risk (as in the traditional case) of doing only one side of the trade and holding a position you do not want. This atomicity allows the arbitrage to be effectively risk-free, other than minor gas fees. Other than that, there is no risk to your actual capital. It also gives you access to essentially infinite leverage, because as long as your trade is profitable within one transaction, you can take as much money as you want!

## Other Uses of Flash Loans

Arbitrage is one of the primary uses of flash loans. There are however other use cases where the availability of uncollateralised capital can be useful. The Equalizer whitepaper covers some of these other use cases.

### Liquidations & Self-Liquidations

With the availability of loans and even derivatives in the DeFi space, it is inevitable that the topic of liquidations would come up. We covered liquidations in detail in a previous article, however in the DeFi world liquidations are handled a bit differently.

In short, if someone has a loan of e.g. USDC with ETH collateral, then someone will need to liquidate (sell) the ETH collateral into USDC in order to be able to cover the loan if the collateral loses value. Often, this is outsourced to what in some places is called a backstop liquidity provider or liquidator. This entity will typically keep a basket of different currencies (USDC included). If the above client with ETH collateral gets liquidated, their collateral will become “available” to any entity that can offer the USDC outright.

Keeping a large bucket of different currencies around in order to cover any potential liquidations is expensive, and carries inventory risk i.e. the risk of losing money while holding the asset. With a flash loan, this can be deftly avoided. The liquidator takes out a flash loan of USDC, and immediately pays off the bad loan, and thereby taking custody of the ETH collateral. In the same transaction, they can then flip the ETH on another DEX for USDC. As long as the USDC they got back from the collateral covers the loan and interest, this will be executed netting the liquidator a small profit in one transaction.

If you are the holder of the bad debt, you can even self liquidate whereby you act as a liquidator on yourself using a flash loan. Assuming you are able to flog the collateral at a sufficient price, you can save yourself the $\approx 10-15\%$ liquidation fees, and pocket them yourself.

### Collateral Swapping

Consider a client that has USDC loan that is collateralised in ETH. The client has a bearish outlook on ETH, and believes that it may lose value, thereby endangering their loan. Instead, they feel that WBTC (wrapped Bitcoin) will be a better choice for collateral. Using a flash loan, they can essentially “hot swap” one collateral for another.

They can take out a flash loan for the same amount as their USDC loan, and pay it back unlocking their ETH collateral. They can then swap their ETH for WBTC (using an exchange), and take out the same sized USDC loan again but this time using WBTC. With the USDC they received, they can then pay back the flash loan. Within one transaction they have now swapped out the ETH for WBTC, with little cost involved.

## Unethical Oracle Price Manipulation

With the flexibility and leverage the flash loans offer, it was only a matter of time before someone figured out how to use it for nefarious means.

One of my favourite crypto newsletters is rekt.news. It covers various hacks and exploits that occur within the DeFi ecosystem. Some of the best write-ups involve the usage of flash loans to exploit protocols, since usually the exploit is incredibly intricately designed and the approach to the hack very cleverly executed.

Many DeFi protocols rely on “Oracles” to provide reference prices for various tasks e.g. the valuation of collateral. An oracle is simply the on-chain equivalent of a price index on centralised exchanges, and represents a price of a certain asset at a certain time. For safety, optimal design of indices/oracles requires having multiple sources of prices in order to make manipulation harder. A determined attacker might be able to crash the price on a single exchange, but crashing it on e.g. five is much harder/capital intensive and therefore makes the index/oracle safer.

Due to the relative novelty of most DeFi exchanges, it became apparent that certain exchanges used single price oracles for asset/collateral valuation. For instance, in November 2021 a flash loan was used to exploit Cheese Bank (what a name) by using 20k ETH to raise the price of the CHEESE token on Uniswap. It turned out that Cheese Bank was using Uniswap as a single price oracle, and this allowed the attacker to fraudulently inflate the value of their own collateral (the 🧀) on the platform and promptly drain 3.3 million USD from the “bank’s” vaults.

At the time of writing Cheese Bank appears to be trying recover its client’s funds using the industry-standard method of calling out the alleged thief on Twitter. Good times.

Attacks like this on centralised exchanges are much more risky even if a single price index/oracle is used. As seen in the section on arbitrage, there are timing risks, and it is possible that someone else might interrupt your attack while it is going on. With flash loans however, there is pretty much no risk. If the attack should fail for some reason, the worst case is that your transaction will be canceled and possibly someone will notice what you tried to do. In addition, crashing a market normally takes a huge amount of capital. With a flash loan, you have access to pretty much as much capital as the lender can offer - perfect for such a task!

Dozens of protocols have been hit by such attacks, with some of the largest losing hundreds of millions of USD worth of tokens:

• Cream Finance: Hit by flash loan attacks not once but twice for \$130m and \$18m respectively. Attackers snatched the funds by manipulating oracles and exploiting re-entrancy attacks.
• bZx: Hit by flash loan attacks for close to \$950k. • PancakeBunny: The attacker took out 8(!) different flash loans to skew the valuation of certain LP tokens, and claim BUNNY rewards which were then flipped in the market for cold hard cash that was used to pay back the loans. Total losses were around \$45m, and in the resulting fallout PancakeBunny lost 90% of its Total Value Locked (TVL).
• Grim Finance: Another case of a re-entrancy attack amplified by the use of a flash loan. The resulting repeatedly minted tokens were subsequently fenced on a DEX, and used to repay the flash loan. Total losses were \\$30m.

## The Future Of Flash Loans

For better of for worse, flash loans are here to stay. Currently, there are a few providers offering this service including Aave, and dYdX. Due to there being essentially zero risk for lenders, fees for these loans are quite low, with Aave charging just 0.09% at the time of writing. As more developers learn to use these tools, it is likely we will continue to see more use cases for these loans appear.

Flash loans have also undoubtably given hackers the ability to exploit protocols more easily. However, some suggest that those protocols which manage to survive the DeFi wasteland where various (flash loan enabled) predators lurk will be better for it, having battle tested their code and contracts. The final outcome however, remains to be seen.

## Glossary

Annualised
An interest rate calculated as if it was applied over a whole year.
Arbitrage
To make a risk-free profit by buying/selling an asset between two venues at different prices
Atomic
An event that happens all at once, or not at all.
Backstop Liquidity Provider
A market participant that takes over positions/loans whose collateral is insufficient to maintain it.
Borrower
Someone who takes out a loan.
Collateral
Cash or assets that are offered as security for a loan. If the loan defaults then the lender can take the collateral.
Compounding
The charging of interest on interest already accrued.
Credit Check
A check done on borrowers on lenders to assess their ability to repay a given loan.
Default
When a borrower is unable to make the payments on a loan.
Ethereum Virtual Machine (EVM)
The runtime for the Ethereum blockchain. Used by smart contracts.
Flash Loan
A special type of loan available as a smart contract on certain blockchains. Allows the borrower to take out any available funds as a loan as long as the full principal plus a fee is returned within one transaction.
Guarantor
Someone who guarantees a loan for a borrower, by committing to pay it on their behalf if the borrow is unable to pay.
Income-driven Repayment
When a lender takes a portion of a borrower’s income to pay back a long.
Interest
Extra money that is charged to the borrower for taking out a loan.
Inventory Risk
Holding onto assets that might potentially go down in value.
Lender
Someone who gives a borrower a loan.
Liquidator
See Backstop Liquidity Provider.
Low Trust Environment
An environment where the participants cannot trust each other either due to the nature of the business, or other factors such as anonymity.
Mortgage
A loan used to purchase a house, where the house is used as the collateral and the borrower provides a down payment.
Oracle
A type of smart contract that reports the price of some external or internal asset.
Over Collateralised
When the value of the collateral exceeds that of the loan.
Principal
The initial amount that was taken out for a loan.
Self Liquidate
On DeFi protocols, the ability to act as your own liquidator to save on fees.
Single Price Oracles
An oracle that sources its price from only one exchange.
Smart Contract
A program that can be run on a blockchain in a decentralised fashion.
State Of The World
The current state of a system. Includes everything such as token balances, and any other stateful values in smart contracts.
Timing Risk
When carrying out an arbitrage trade, the risk that the current market conditions will change while your orders are in flight.
Total Value Locked (TVL)
The total value of deposits in a DeFi protocol.
Transaction
An atomic set of instructions to a blockchain.
Under Collateralised
When the value of the collateral for a loan is less than the value of the loan itself.

Subscribe to the mailing list: