​​What Are DeFi Flash Loans & How To Prevent Flash Loan Attacks?

Decentralized Finance is changing the way we borrow and invest. Flash loans, a type of uncollateralized lending, have gained in popularity, as well as bad press. Flash loan attacks are a common threat that enable hackers to steal massive amounts of cryptocurrency reaching up into the hundreds of millions.

What is a flash loan?

A flash loan is an ultra-fast, unsecured loan, where the whole lending and returning process occurs within a single transaction on the blockchain.

Source: Finematics

The loan is able to by-pass the numerous prerequisites of a traditional loan, used to guarantee their repayment. No credit checks, collateral and guarantors are needed, provided that the liquidity is returned to the pool within a single transaction block. If this fails to occur, the whole transaction is reversed, effectively undoing the actions executed up until that point. This guarantees the safety of the funds in the reserve pool.

Watch this 1 min video to see how a flash loan works. Source: Coindesk.

The primary intended reason for these flash loans is for users to capitalize on arbitrage opportunities. Arbitrage is the simultaneous purchase and sale of the same asset in different markets in order to profit from marginal differences in the asset’s listed price. Arbitrage traders are vital for their role in increasing market efficiency as they narrow the gap in these price discrepancies. Other use-cases include collateral swapping, self-liquidation, and more.

Typically, the concept works well, but some misuse this form of lending, intending to drain vulnerable DeFi protocols of millions of dollars.

Flash loan attacks — why they are easily executed

Flash loan attacks are relatively common because they are easy for a hacker to perform and low-risk due to the probability of exposure being so low. The resources required to execute a flash loan attack are nothing more than a computer, internet connection and ingenuity as stated by Coinmarketcap.

One of the most common types of economic exploit in DeFi involves a flash loan attack. Source: Elliptic

DeFi hackers can easily exploit flash loans as they can be used to create artificial arbitrage opportunities. It involves manipulating asset prices in order to take advantage of arbitrage opportunities on DeFi services that would not otherwise have existed. In short, due to the theoretically infinite size of the loan, the attacker is able to ‘increase demand’ and raise the price. They can make a trade just like any other arbitrage opportunity [buy low, sell high], then pay off the loan and keep the profits. The maximum size of the loan could be as great as the liquidity pool could handle; theoretically reaching into the billions of dollars, draining the liquidity of the effect pools.

Their unlimited and instantaneous nature mean that a well-planned attack can be executed in one go, with no risk if it fails [since the loan transaction will automatically reverse if the loan isn’t repaid.

Examples of flash loan attacks in 2021

C.R.E.A.M. Attack October 2021 loss of ~$130m

The hacker borrowed $500m DAI and $2bn ETH with two separate addresses. Through a series of trades, and using the loans as collateral for more loans, the attacker was able to artificially double the price of the yUSD and repay the loans. With the remaining $1bn of collateralized crYUSD, the attacker borrowed all the liquidity from the C.R.E.A.M. Ethereum v1 markets.

In the post-mortem by C.R.E.A.M., it is stated that the key vulnerability lies within the price calculation of the wrappable token.

xToken Attack August 2021 loss of ~$4.5m

This hack was the result of a flash loan being used to deflate an xSNX token price and the hacker’s ability to call a function which shouldn’t have been within their power to do so. The source of value extraction was the artificial arbitrage by the price manipulation of xSNX. Interestingly, xToken has since retired the xSNX product due to its complexity.

Pancake Bunny Attack May 2021 loss of ~$200m

The hacker used pancakeswap to borrow BNB. They used this to manipulate the price of USD/BNB and BUNNY/BNB, gaining a huge amount of BUNNY. They then dumped the BUNNY and remaining BNB which was at the time worth around $200m.

**The figures quoted are the amount of value extracted at the time of the hack. The protocols may have recovered some of the tokens or compensated the users after.

Consequences of flash loan attacks

Depending on the scale of the attack, consequences can vary. But one thing is certain, the reputational damage is great, and the other protocol users pay the adverse effects. Seemingly never out of the spotlight, C.R.E.A.M. has been attacked three times in 2021, two of which were flash loan attacks. In the case of flash loans, lightning can and does strike the same place twice.

The primary and most important consequence is the impact that flash loan attacks can have on other users. DeFi would be nothing without the loyalty and money of the users who are all key players in an intricate autonomous ecosystem. It is presumptuous to assume that victims have available cash to put back into a system that has failed to protect their assets adequately.

Questions about whose responsibility it is to ensure that flash loan attacks don’t occur will continue to rise and protocols will rightfully be expected to defend themselves. Is taking preventative measures enough to adequately prove that the platform isn’t responsible if an exploit occurs? A prudent protocol or exchange should also consider a post-exploit action plan, if the worst is to occur.

5 Steps for protocols to take to minimize the likelihood and impact of flash loan exploits

The recommendations here align with the three pillars of cyber security: security, vigilance and resilience.

1Design of the protocol matters

Complexity comes with risk. While developing a large smart contract or building a dApp it is difficult to pinpoint loopholes. Therefore all external calls should be located, to explore if these could serve as a path for the malicious actors in the contracts. In older versions of Solidity, even reading a public field could lead to unsafe external calls that can be easily manipulated.Therefore, developers should always use the stable and updated versions of Solidity.

2. Use a decentralized oracle

Oracle manipulations are the biggest cause of flash loan attacks. Smart contracts heavily rely on oracles which provide an effective interface between the contracts and the external source to push the required data. Decentralized Oracles like Chainlink, gather data about prices from multiple sources, which reduces the likelihood of a single data point influencing the oracle. If a platform relies solely on the data of one particular DEX, then its data is at risk of being flawed. Malintended users could directly manipulate the price of the singular DEX where the loan price is based off, resulting in loans issued with an inaccurate average price. On the other hand, limited data could form an inaccurate representation of the average market price and thus promote excessive slippage exploitation.

3. Get audited

Getting a smart contract audit is one of the most vital steps before launching your product. These audits identify and remediate vulnerabilities in the smart contracts before they can be exploited by someone with malicious intent. Source Consensys Source Certik

Due to the interwoven nature of these protocols, just focusing the attention of the audit on the critical components isn’t enough to guarantee their security. A chain is only as strong as its weakest link, perfectly showcased by the recently detected Log4Shell vulnerability. If an audited protocol integrates with, for example, an un-audited bridge, well this might be the gap that a hacker is looking for.

If a hole in the code of the platform is found, then it is crucial for the developers to remedy it as soon as possible. It may sound obvious, but apparently it isn’t to everyone. As described in the examples above, in May of 2021, Pancake Bunny was hit resulting in an enormous loss. Just days after, AutoShark was hit in a copy-cat attack, which fortunately resulted in significantly smaller losses. The kicker, however, is that AutoShark officially published its acknowledgement that it was vulnerable to a similar style hack.

4. Participate in a Bug Bounty program

Continual vigilance over the smart contracts while they are in operation is critical, especially if updates and integrations are occurring. Offering a bug bounty incentivizes those with ‘hacking skills’ to act ethically. They are prizes for ethical hackers who report holes in code, which they could have exploited. It encourages these white hat hackers to work with the protocols rather than against them. ImmuneFi is a platform that advocates for the rights of white hat hackers. Protocols list their bounty on the database and offer a portal for hackers to submit their findings.

It isn’t enough to just offer a few thousand dollars as a bounty. ImmuneFi suggests 10% of TVL. It has to be enough to incentivize a hacker to act ethically when they know they have ‘illegal’ access to a much larger pool of funds. The incentives provided are attractive with a record amount of $10m being offered by BXH after a hack where over $139m was taken.

5. Offer in-App coverage

Despite all efforts to prevent a flash loan exploit, there is always a possibility for the event to occur. Proactively educating users about the risks of investing should be the responsibility of the protocols. Do your own research (DYOR) is one of the most thrown-around phrases. However, in the context of deciding which protocols to use, the protocols themselves should do the research about their risks and present these to users in a clear way.

The impact of an exploit can cause a serious business crisis if the protocol doesn’t act transparently. By offering in-app coverage, crypto’s alternative to insurance, protocols are acknowledging the risks and presenting their users with a discretionary option to mitigate the risks based on their risk appetite.

How does it work in practice? There are multiple risk platforms offering coverage against smart contract failures for hundreds of protocols, exchanges and wallets. Nexus Mutual is currently the best known, with TVL around $1B. New players are slowly building up traction in the market like Bright Union and Bridge Mutual.

Bright Union, DeFi coverage aggregator, has developed a way for protocols to offer their users coverage from their own app with an SDK. The cost of coverage can even be deducted from the APY so no out of pocket costs for users creating a seamless customer journey.

A protocol proactively offering users coverage is Alpaca Finance. The app connects the users directly to these risk coverage platforms, where they are then able to buy coverage. Similarly Don-key finance, a social platform for yield farming, is soon offering a fully covered strategy for users to invest in, with coverage just a click away.

About Bright Union

Bright Union is the world-leading multi-chain decentralized finance cover marketplace. Our mission is to safeguard your digital assets from hacks, smart contract failures, and rug pulls by empowering the crypto community to cover one another in a decentralized and permissionless manner.

Bright Union provides the most comprehensive range of crypto insurance on the market at competitive prices. Furthermore, Bright Union will soon release its unique suite of cutting-edge risk solutions, providing investors with outstanding investment and coverage opportunities. Be bright and take advantage of DeFi’s exponential growth.

Join the Union

Be Bright and #JointheUnion. Receive announcements by joining the community.

🌍 Check out the website.

🤝 Discuss Bright by joining Telegram or Discord

🗞️ Get the latest news on Twitter @BrightUnion.

📺 Watch tutorials on Youtube

📸 Follow us on Instagram




Web3 Insurance marketplace that allows DeFi users to to buy and provide coverage against hacks and protocol failures.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

SPACE-02 and the beginning of Multi-space (UPDATE)

The total computing power of the entire network has skyrocketed.

Merchants to benefit from cryptocurrency payments?

NFT NEWS briefly about the main thing.

BlockBank chooses Bright Union as their partner for DeFi insurance

The curious case of Tethers (not sure this title hasn’t been coined before!)

The trading volume of DEX in February is close to US$73 billion, and NGKEX will promote DEX after…

What is the token of the Muso blockchain?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bright Union

Bright Union

Web3 Insurance marketplace that allows DeFi users to to buy and provide coverage against hacks and protocol failures.

More from Medium

Flash Loans: How to cosplay as a whale in 2022

Flash loans: magic money ?

I talked to 100 scammers and put together the Universal Crypto Scammer’s playbook

The Ultimate Savings Protocol: mStable