All About DeFi Flash Loans
Table of Contents
Flash loans are uncollateralized decentralized finance loans that are issued and repaid within the same blockchain transaction. They can be used to make money with arbitrage, liquidate or refinance debt, or even exploit other DeFi protocols. Find out how flash loans really work, why they are controversial, and if Pontem Network plans to add flash loan support to its products.
- A flash loan is a crypto loan that doesn’t require collateral and is taken out and repaid over the course of a single blockchain transaction.
- You can flash-borrow any amount, even millions of dollars, as long as there is enough liquidity in the pool.
- Flash loans are used to make money with arbitrage trading, as well as for DeFi liquidations and self-liquidations, debt refinancing, and collateral swapping.
- The main flash loan providers are Aave, Uniswap (where they are called flash swaps), Solend on Solana, and C.R.E.A.M. Finance.
- Flash loans exist only in DeFi. There is nothing similar in traditional finance. As a rule, you typically need coding skills to write a flash loan smart contract (for example, for arbitrage), though there are no-code tools, too, like DeFi Saver and Furucombo.
- Flash loans are often used by hackers to exploit DeFi protocols: recent examples include the attacks on Beanstalk, Nirvana, Crema, Deus, and Fei.
- The Move programming language allows for much safer implementations of flash loans than Solidity.
- Pontem’s Liquidswap AMM for Aptos has flash swaps built into its code, but they will only be activated when it becomes safe to do so.
What are flash loans in DeFi?
A flash loan is a crypto loan that is both taken out and repaid in a single transaction. Unlike regular DeFi loans, a flash loan doesn’t require collateral.
How regular crypto loans work:
1. Supply some cryptocurrency as collateral (lending protocols support major cryptos like ETH, USDT, USDC, etc.).
2. Pick the cryptocurrency you want to borrow. Interest rates fluctuate based on the supply and demand for each token, so you cannot calculate in advance how much you’ll pay in interest. Some platforms offer stable-rate loans, though the interest rate is higher (you pay extra for extra peace of mind).
3. The protocol will calculate how much you can borrow based on how much collateral you’ve deposited. Most protocols require overcollateralization: the loan amount is usually only around 70-75% of the collateral amount.
4. Overcollateralization helps protect the lender’s interests, as decentralized lending is anonymous and there is no way to check the borrower’s credit history.
5. Once you confirm the loan, the tokens will be automatically sent to your wallet. Everything is done via smart contracts.
6. There is no set loan duration; you can repay whenever you want, together with the accumulated interest.
7. If the value of the collateral drops below a certain threshold, you’ll need to add some more to arrive at the required collateralization ratio – or repay the loan. Otherwise the collateral will be liquidated (sold), so that the lenders can get their money back. As a borrower, you don’t borrow from a specific lender but rather from a pool, and the interest is divided between the liquidity providers depending on how much each has supplied.
8. The main drawback of this system for the borrower is, of course, the high collateral requirements. For example, to borrow 1,000 USDT you may need to lock up $1,500 in ETH. An alternative for certain categories of expert users is a flash loan. Let’s look at how it works next.
How flash loans work
With a flash loan, there is no collateral.he loan size is limited only by the amount of liquidity in the pool. You can even borrow $100 million if the pool is large enough. The flip side is that you have to repay the loan within the same transaction, before the block containing it is added to the blockchain.
How can you borrow and return the money in a single transaction? This requires a special smart contract – and this is why flash loans were originally designed for developers. As explained by Aave:
1. The user’s contract needs to call the smart contract of a liquidity pool using the flash loan function.
2. The pool performs checks on the user’s contract and transfers the requested amount into it.
3. The user’s contract executes whatever operation the flash loan is needed for, such as an arbitrage trade. All this has to be coded into the contract from the beginning.
4. Once this part of the code has finished running, the contract approves the pool to pull the borrowed amount plus the fees. Note the difference: the borrower doesn’t send the money back – the pool takes it back but is pre-authorized to do so.
5. Instead of an annualized interest rate, you’ll usually pay a fixed fee. For example, on Aave it’s 0.09%, so for a 10,000 USDT flash loan, the fee works out to $9. Also, as everything happens in a single transaction, you only need to pay the blockchain gas fee once. However, the required amount of gas can be quite high, because of the amount of computational effort that goes into executing a flash loan contract.
6. There is no easy way for the borrower to default on a flash loan. If at the end of the transaction there aren’t enough funds in your account to repay, all the operations you’ve performed with the borrowed tokens will be rolled back – and the money will be automatically returned to the lending pool just the same. The loan is effectively reversed.
7. This is possible as the transaction hasn’t been confirmed on-chain yet. It’s an important distinction, since, once validated and confirmed, a blockchain transaction can’t be reversed.
Flash loans without coding
There are a few flash loan tools for non-coders, such as DeFi Saver and Furucombo. However, remember that you’ll need to find arbitrage opportunities yourself. You can also easily get front-run by more advanced arbitrage bots.
Flash loan design flaw: re-entrancy
Flash loan logic in Solidity relies on re-entrancy – a feature that smart contract engineers generally try to avoid as unsafe.
You may have heard of “re-entrancy attacks” in DeFi. Re-entrancy occurs when smart contract X calls contract Y, Y can call X back while X is still running.
It sounds complex, but that’s the process we’ve just described: a user’s custom contract calls the flash loan contract and passes control over to it. The flash loan contract transfers the funds, then calls back the user’s contract. We’ll come back to this when we talk about the implementation of flash loans in Move.
If you’d like to dive deeper into the subject, we recommend the wonderfully named paper ‘Attacking the DeFi Ecosystem with Flash Loans for Fun and Profit’.
Use cases for flash loans
Arbitrage means taking advantage of a difference in the price of an asset across multiple markets. For example, if you find that the price of a token on Uniswap is lower than on SushiSwap, you can buy it on Uniswap, then sell it higher on Sushi and extract a small profit. In practice, this can be difficult for two reasons:
1) Arbitrage windows can close quickly. There is an army of arbitrage bots out there looking for such DEX opportunities, and they are far faster than you. In the time that you need to get the first swap transaction to be confirmed and switch to the second AMM, the price difference will disappear. You’ll be stuck with an asset you don’t need.
2) You need to operate with a large amount of capital to earn enough to cover the gas and DEX fees and still make a profit that’s worth your time.
Flash loans take care of these issues:
1) The loan and both swaps happen in a single transaction, so you can move much faster to capture an arbitrage opportunity (unless another flash loan contract beats you to it).
2) You can arbitrage trade without risking your own capital. If your contract doesn’t complete the arbitrage swap because the opportunity isn’t there anymore, you won’t be left holding a bag of tokens.
Arbitrage flash loan contracts usually include a function that checks if a set of swaps will yield a profit. If no profit can be gained, the contract simply won’t execute the arbitrage transaction.
Example: how to make money arbitraging with flash loans
Let’s say that Token A trades for 10 USDT on Uniswap and for 10.1 USDT on SushiSwap. The swap fee is 0.3%, and the average gas fee for a swap is $10.
You flash borrow 100,000 USDT on Aave and buy 10,000 Tokens A on Uniswap with it, paying $10 in gas and a 0.3% fee (100,000*0.003=$30), so the transaction cost $40 in total.
Next (but within the same transaction, remember?), you sell Tokens A at 10.1 USDT each on Sushi for 110,000 USDT. Once again, you pay an equivalent of $40 in fees.
As the final step, the pool on Aave collects the lent 100,000 USDT plus Aave’s standard flash loan fee of 0.09% ($90), and the gas fee of roughly $30.
You made $10,000 through arbitrage ($110,000-100,000), minus $200 in fees (40+40+90+30), leaving you with $9800. USDT. Not bad for a trade where you didn’t risk your own capital! It should be noted, however, that a 10 cent price discrepancy on the same token would be extremely large; most arbitrage trades occur with much, much smaller amounts.
If some other flash loan bot beat you to the arbitrage opportunity, you would only lose $120 inAave fees and gas. In other words, the risk-reward ratio is very good.
Users who take out regular loans on DEXs like Aave, Compound, etc. can use flash loans to protect themselves from liquidation. A reminder: liquidation happens when the value of your collateral falls below the minimum allowed threshold. You’ll also have to pay a penalty (5% on Aave), which is a good reason to avoid getting liquidated.
Here’s how you can avoid liquidation with a flash loan:
- Imagine you’ve borrowed 75,000 USDC on Aave, depositing an equivalent of $100,000 in ETH as collateral.
- The price of ETH suddenly drops by 15%, so that the collateral is now worth just $85,000. You decide to self-liquidate (repay) before it’s too late. Let’s also presume that you owe 100 USDC in interest.
- You borrow 75,100 USDC via a flash loan on Aave and pay back the loan with interest. In return, you get access to your collateral of $85,000 in ETH.
- As part of the same flash loan contract script, you swap most of the ETH on Uniswap to get 75,100 USDC…
- ...and repay the flash loan. You’ll be left with around $10k worth of ETH.
Flash loans are also popular among liquidators: users who specialize in performing liquidations on Aave and other lending protocols to make money on penalties. For them, it’s also easier to get a flash loan to repay a loan on behalf of a borrower quickly, then sell the collateral to repay the flash loan and keep the rest.
Collateral swapping means replacing one collateral asset with another. This can come in very handy if you suspect that the price of your collateral asset is about to drop. Collateral swaps are supported by both Aave and Compound.
Imagine that you’ve taken out a loan in USDC and collateralized it with CRV, but you’re worried that CRV’s price will fall soon due to upcoming development news. You’d rather take out the CRV and replace it with ETH, which you believe to be safer.
With a flash loan, it’s not difficult: borrow ETH, take out the CRV collateral, put the ETH in , then swap CRV for ETH on a DEX and repay the flash loan. Once again, this whole sequence of operations need to be coded into the flash loan smart contract.
Refinancing a debt means paying off a loan using another loan opened on better terms (usually at a lower interest rate). Imagine that you’ve borrowed USDT on Compound at 2.05% APY, but you notice that on Aave the borrowing APY for ETH is just 1.39%.
How can you take advantage of that lower rate?
- Get a USDT flash loan on Aave;
- Repay the loan on Compound to get your collateral back;
- Deposit the collateral on Aave and take out a new loan in USDT;
- Repay the flash loan.
Admittedly, creating a new contract can be too much work for a one-off refinancing operation. Plus, DeFi borrowing rates are really volatile, so there’s no guarantee that the rate on Aave will remain lower than on Compound. But still, it’s a use case worth knowing about.
Which blockchains and protocols support flash loans?
Aave: Ethereum, Avalanche & Polygon
Even though it was Marble Protocol that originally introduced flash lending back in 2018, Aave was the first major DeFi protocol to offer them on Ethereum. This happened back in January 2020 – around the same time it rebranded from Ethlend to Aave. By August 2020, the volume of flash loans issued by the protocol reached $300 million. The single largest flash loan of that early period amounted to $14 million.
By January 2021, the total flash loan volume on Aave exceeded $2 billion, and the largest single transaction was a whopping $200 million.
Aave also supports flash loans on Polygon and Avalanche. Between these three blockchains, Aave issued over $5 billion in flash loans in 2021, according to this analysis.
Uniswap’s implementation is called Flash Swaps, but they are essentially flash loans. The only difference is that you borrow from trading pools, not lending pools – and you need to choose one of the two tokens in a pool. For example, if you pick the WBTC-ETH pool, you can borrow up to 100% of WBTC or ETH in the pool (but not both).
There are three main differences between Uniswap’s Flash Swaps and Aave’s flash loans:
1. On Uniswap, you can choose to either repay the loan with the same tokens that you borrowed or swap them for the pool’s second token at the current price. This can save you some effort when coding the contract.
2. Uniswap allows you to borrow any ERC20 token from any pool, so you have hundreds of assets to choose from. Aave supports only 37 assets as of September 2022.
3. The fee is 0.3% on Uniswap versus 0.09% on Aave, more than three times the cost.
Equalizer Finance (Ethereum, BNB Chain, Polygon, Optimism)
Equalizer Finance is a marketplace for flash loans that currently doesn’t charge any fees. According to the website, the protocol uses less than half the gas per loan compared to Aave.
Equalizer is still in alpha, and there aren’t many pools available. The biggest pool is USDC on Optimism, with $1.5 million worth of flash loans issued. Number two is the WETH pool on Ethereum ($1 million), and number three is WBNB on BNB Chain (formerly BSC), with $660k in flash loans.
C.R.E.A.M. Finance (Ethereum, BNB Chain, Fantom)
Independent developers can access flash loans through the main app interface, but the feature is intended primarily for DeFi protocols. They can access flash loans through the Iron Bank, C.R.E.A.M.’s protocol-to-protocol lending project.
Somewhat ironically, C.R.E.A.M. Finance itself suffered a flash loan attack in October 2021, losing $130 million.
Solend is the largest lending protocol on Solana. It charges a 0.3% fee on flash loans, which are available for SOL, USDC, TULIP, SLND, ATLAS, APT, STEP, and many other tokens. In July 2022, a hacker flash-borrowed from Solend to attack Crema Finance, stealing almost $9 million (though they ended up returning $8M).
Just a few weeks later, the stablecoin protocol Nirvana Finance fell victim to a similar attack. The hacker took out a $10M flash loan in USDC from Solend and used it to mint ANA tokens, with the ANA price rising 3x in the process. The attacker then swapped all that ANA for USDT via Nirvana’s treasury, draining it. Finally they repaid the flash loan, making away with $3.5 million in profit. Nirvana’s NIRV stablecoin itself dropped 99%.
By the way, the technical implementation of flash loans on Solana is different than on Ethereum, because Solana smart contracts don’t allow re-entrancy. Instead, a custom flash loan contract will include stacked instructions, and the instruction to borrow will immediately check if there is an instruction to repay further down the line. If there isn’t, the transaction will fail. It’s technically complex, but you can find some more details here.
What are the risks of flash loans?
Flash loans are a groundbreaking innovation: not a DeFi version of an existing TradFi product, like a regular loan, but something that does not exist in the world of legacy banking. For the first time in the history of finance, people borrow hundreds of millions of dollars instantly, with no checks, no documents, no KYC or AML, and no collateral. But while flash loans open up a new world of possibilities, they also introduce new risks.
Any hacker can stage capital-intensive exploits
Imagine that you are a hacker and found a way to exploit a DeFi protocol – but you need $1 million for an attack to succeed.
In the past, that was it – if you didn’t have the money, you’d have to abandon the plan. But with the arrival of flash loans, you can simply write a contract that includes all the steps for the attack,borrow 1 million USDT, and instantly repay it– without risking anything.
If it doesn’t work, you will have lost a couple of hundred bucks in fees – but if it does, you can make away with millions of dollars. The opportunity cost is basically zero.
It is harder for DeFi protocols to protect themselves
dApp teams now must prepare for all situations where a malicious actor wielding millions of dollars in liquidity could overtake their governance, liquidity pools, and so on.
According to a report by CertiK, flash loan attacks have cost the space over $300 million in the second quarter of 2022 alone. Let’s look at several recent examples:
Beanstalk Finance ($182M lost)
We’ve already covered the attack on Beanstalk Finance in our article on blockchain audits, but it’s worth covering it here, becausethis was the biggest flash loan attack of 2022 with $182 million stolen. It’s also really clever, as it exploited a fundamental principle of DAO governance: users with a larger stake in a protocol have more votes.
The attacker took out a set of flash loans worth around $1 billion and used that money to provide liquidity for trading pools with Beanstalk on Curve, becoming the largest liquidity provider. This also gave them the majority of votes in the DAO.
The attacker proceeded to submit a very creative proposal: transfer all the funds from the protocol to their own address! And thanks to their majority voting power, the perpetrator made the proposal pass. It was automatically implemented, so the attacker got away with all of Beanstalk’s money.
This is a good example of how every module of a DeFi dApp should be made resistant to flash loan attacks. Developers need to consider all the ways in which a malicious agent with vast amounts of (virtually free) capital can exploit a dApp’s business logic, including governance.
Fei Protocol ($80M lost)
Fei is a lending protocol that was exploited because it had a re-entrancy vulnerability in a contract forked from Compound. The hacker managed to repeatedly borrow money and withdraw the collateral without repaying the loan. In turn, the capital they used as collateral (150 million USDC) came from a flash loan.
The reason why Fei was hacked was a bug in its own code. Any good blockchain audit team would have discovered the vulnerability. So it’s not a case of ‘It got hacked because flash loans are bad,’ but rather ‘It got hacked because it wasn’t properly audited.’.
Deus Finance ($18M lost)
Deus is a DeFi service marketplace on Fantom with its own DEI stablecoin. On April 28, the attacker exploited Deus’ oracle – a service that tracked the price of DEI in the USDC-DEI trading pool and supplied that price to the lending module where you could mint new DEI by depositing collateral.
The hacker took out a $143 million flash loan in USDC and used it to buy DEI from the liquidity pool. This huge purchase pushed the price of DEI from$1 to more than $15. Next, the attacker deposited a small part of the expensive DEI as collateral to mint over 17 million DEI. Finally, they used the DEI to repay the flash loan and still ended up with over $13 million in profit.
The saddest part is that Deus had been attacked in a very similar way just a couple of months earlier – also using a flash loan and price manipulation.
Flash loans in Move and on Liquidswap, the First Aptos DEX by Pontem
Move is a very safe new smart contract language, used by the Aptos and Sui blockchains. Its safety comes largely from its simplicity: it’s easier to avoid errors in Move, debug contracts, and spot malicious code. It also deals with many common vulnerabilities, such as re-entrancy.
Move relies on a system of modules (smart contracts) and resources (assets), which developers can easily create and move around within the module. A resource cannot be copied (so double spending is impossible, for example) or implicitly deleted – only moved around. Developers can also use linear logic to define custom resource types to build the structures they need – once again, easily and safely.
How does this apply to flash loans? Here’s how. In Move, you can create a structure (a digital thing) that has to be destroyed at the end of a transaction, once you’ve done what you needed to do with it. So with a flash loan, the user will receive two resources: the coins they requested to borrow and a receipt, which must be destroyed at the end. The only way to destroy the receipt is to repay the loan.
In between, you can insert whatever logic you need, such as arbitrage. But the loan is guaranteed to be repaid in full – without any need for callbacks and re-entrancy. It’s also easy to implement on the level of code. You can find out more about Move security from our recent AMA with Robert Chen from OtterSec, one of the industry’s leading Move code auditors.
Flash loans on Liquidswap
The first DEX for Aptos, Liquidswap by Pontem Network, already has flash loans implemented at the level of its main branch. However, they haven’t been activated yet, and we don’t have a specific release date scheduled yet.
The reason is that Pontem Network always prioritizes security – even ahead of scaling and feature roll-out. For example, Pontem Wallet is now undergoing a third smart contract audit, and Liquidswap has a detailed security roadmap, too. We are extremely careful about which projects to integrate with and prioritize those who also conduct security audits (read this AMA recap to learn more).
Our security-first approach applies to flash loans, too. They are a powerful feature, and we believe that they can be beneficial for the Aptos DeFi ecosystem. But we need to minimize the risk that someone might use Liquidswap flash loans to target other DeFi protocols on Aptos.
Ideally, every Aptos-based DeFi protocol should consider potential ways that they could be exploited using a flash loan, and close those loopholes. By the way, the bug bounty program for Aptos, as published on ImmuneFi, covers flash loans.
To summarize: Pontem’s Liquidswap AMM for Aptos theoretically supports flash loans, but we will only implement them in practice once we feel that it’s safe to do so – for us and for our ecosystem..
Before that happens, Pontem has a detailed roadmap to implement, including dozens of new features for Pontem Wallet and Liquidswap, releasing Byte Babel, first Solidity-to-Move translator, and even NFTs. Follow us on Twitter, Telegram, and Discord and don’t miss these technical updates and weekly AMAs!