Tuesday, June 6, 2023

Flash Loans

I have been generally skeptical of claims that blockchain technology and cryptocurrencies are major innovations. Back in 2017 Arvind Narayanan and Jeremy Clark published Bitcoin's Academic Pedigree, showing that Satoshi Nakamoto assembled a set of previously published components in a novel way to create Bitcoin. Essentially the only innovation among the components was the Longest Chain Rule.

But, for good or ill, there is at least one genuinely innovative feature of the cryptocurrency ecosystem and in Flash loans, flash attacks, and the future of DeFi Aidan Saggers, Lukas Alemu and Irina Mnohoghitnei of the Bank of England provide an excellent overview of it. They:
analysed the Ethereum blockchain (using Alchemy’s archive node) and gathered every transaction which has utilised the ‘FlashLoan’ smart contract provided by DeFi protocol Aave V1 and V2. The Aave protocol, one of the largest DeFi liquidity providers, popularised flash loans and is often credited with their design. Using this data we were able to gather 60,000 unique transactions from Aave’s flash loan inception through to 2023
Below the fold I discuss their overview and some of the many innovative ways in which flash loans have been used.

The key enabler of flash loans was Ethereum's ability to wrap a Turing-complete program in an atomic transaction. The Turing-complete part allowed the transaction to perform an arbitrary sequence of actions, and the atomic part ensured that either all the actions would be performed, or none of the actions would be performed. Back in 2021 Kaihua Qin, Liyi Zhou, Benjamin Livshits, and Arthur Gervais from Imperial College posted Attacking the defi ecosystem with flash loans for fun and profit, analyzing and optimizing two early flash loan attacks:
We show quantitatively how transaction atomicity increases the arbitrage revenue. We moreover analyze two existing attacks with ROIs beyond 500k%. We formulate finding the attack parameters as an optimization problem over the state of the underlying Ethereum blockchain and the state of the DeFi ecosystem. We show how malicious adversaries can efficiently maximize an attack profit and hence damage the DeFi ecosys- tem further. Specifically, we present 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.37× and 1.73×, respectively.
Qin et al predicted an upsurge in attacks:
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 attacks in Section 3. In a certain poignant way, this highlights the fact the DeFi, lacking a central authority that would enforce a strong security posture, is ultimately vulnerable to a multitude of attacks by design. Flash loans are merely a mechanism that accelerates these attacks. It does so by requiring no collateral (except for the minor gas costs), which is impossible in the traditional fiance due to regulations. In a certain way, flash loans democratize the attack, opening this strategy to the masses
Saggers et al explain from the financial perspective:
Flash loans are unlimited uncollateralised loans, in which a user both receives and returns borrowed funds in the same blockchain transaction. Currently they exist exclusively within the DeFi ecosystem. DeFi aims to be an alternative to traditional financial (TradFi), with centralised intermediaries replaced by so-called decentralised code-based protocols. These protocols, based on distributed ledger technology, eliminate, in theory, the need for trust in counterparties and for financial institutions as we know them.
...
It is important to understand that the lender is exposed to almost no credit risk when participating in a flash loan, hence collateral is not required. Flash loans leverage smart contracts (code which ensures that funds do not change hands until a specific set of rules are met) and the atomicity of blockchains (either all or none of the transaction occurs) to enable a form of lending that has no traditional equivalents.

Flash loans are therefore only available to the borrower for the short duration of the transaction. Within this brief period, the borrower must request the funds, call on other smart contracts to perform near-instantaneous trades with the loaned capital, and return the funds before the transaction ends. If the funds are returned and all the sub-tasks execute smoothly, the transaction is validated.
Cointelegraph provides an example:
On a platform such as Aave, this is how flash loans typically work:
  1. The borrower applies for a flash loan on Aave.
  2. The borrower creates a logic of exchanges to try making a profit, such as sales, DEX purchases, trades, etc.
  3. The borrower repays the loan, makes a profit, and pays a 0.09% fee.
  4. If any of the following conditions occur, the transaction is reversed, and the funds are returned to the lender:
    • The borrower does not repay the capital
    • The trade does not lead to a profit
"reversed" is not quite the right word. If transaction does not repay the loan, or if the trade does not make a profit, the transaction is not validated and thus does not become part of the history on the blockchain. It is as if it never happened, except that the failed transaction incurred gas fees. Saggers et al explain the fees:
A non-refundable fee that covers the operational costs of running the smart contracts must be paid up-front, known as the ‘gas fee’ for the transaction – this is true for any Distributed Ledger Technology transaction and not specific to flash loans. Further commission fees are charged only once the transaction executes successfully, making the whole endeavour nearly ‘risk free’ to both the borrower and lender.
Saggers et al Fig. 2
Based on their 60,000 flash loan dataset, Saggers et al's Figure 2 displayed a histogram of "the ratio between the gas fee paid by a flash loan transaction and the average gas fee paid on the same day, for all transactions on the Ethereum blockchain" and determined that:
on average, flash loans cost roughly 15 times as much as a standard DeFi transaction.
Of course, if they succeed the flash loan transactions are likely to be much more profitable than other DeFi transactions, outweighing the additional cost.

There are two reasons why flash loans are so expensive; they are typically urgent and complex. Saggers et al explain:
The more events included in a transaction, the more space it takes on the Ethereum Virtual Machine. Given the uncertain execution of these loans, some users are also willing to pay additional prioritisation fees for their transaction to be included in the most immediate block added.
Saggers et al Fig. 3
They compiled a histogram of the number of logs in flash loan transactions and concluded:
cost is proportional to the complexity of a transaction, and on this count, flash loans also stand out from typical transactions. Flash loans typically contain between 35–70 logs (Figure 3) per transaction compared to roughly 5–10 logs for the average Aave transaction.
Because of these high fees, flash loans require sufficiently large profit opportunities. Saggers et al list them:
Flash loans are most commonly used for arbitrage opportunities, for example if traders look to quickly profit from a mismatch in cryptoassets’ pricing across markets. Flash loans can also be used for collateral swaps – a technique where a user closes their loan with borrowed funds to immediately open a new loan with a different asset as collateral – or debt-refinancing through ‘interest rate swaps’ from different protocols.
But the really profitable use of flash loans is for theft. Molly White maintains a timeline of successful flash loan attacks; as I write the entries for the trailing 12 months are:
  1. Jimbos Protocol exploited for $7.5 million on May 28th.
  2. Brand new $CS token exploited for almost $700,000 on May 23rd.
  3. 0VIX Protocol exploited for $2 million on April 29th.
  4. Euler Finance exploited for almost $200 million on March 13th.
  5. Platypus Finance stablecoin exploited for $8.5 million ten days after launch on Febraury 16th.
  6. dForce Network exploited for $3.65 million, funds returned on February 13th.
  7. DFX Finance suffers $5 million loss on November 10th.
  8. Earning.Farm exploited for $971,000, exploiter gets frontrun by MEV bot on October 14th.
  9. More than $1.1 million stolen from Sovryn defi protocol on October 4th.
  10. New Free DAO loses $1.25 million in flash loan attack on September 8th.
  11. Flash loan attack nets attacker $370,000 from several sources on September 6th.
  12. Nirvana Finance drained of $3.5 million on July 28th.
  13. Hackers steal $1.43 million from Omni NFT lending platform on July 10th.
  14. Hacker steals over $1.2 million from Inverse Finance, their second such exploit in under three months on June 16th.
Saggers et al Fig. 4
White is thus recording more than one such successful heist per month. As shown in their Figure 4, Saggers et al's 60,000 transaction database demonstrates that:
To this date over US$6.5 billion dollars’ worth of cryptocurrency has been stolen in attacks directly attributable to flash loans.
Since their data covers only one of the many DeFi protocols, albeit the most liquid, this is surely an underestimate. White's Web3 is Going Just Great timeline currently records over $12B in losses, but not all of these exploited flash loans. Further, it is important to note, as Jemima Kelly and Molly White both point out, all these dollar numbers are "notional value". The actual dollars that can be realized from these heists are typically much less than these headline figures, as Ilya Lichtenstein and Heather Morgan found out.

Saggers et al note that:
Table A shows that out of the top five largest amounts borrowed via flash loans, four of these were used to attack protocols.
DateAmount borrowed
(US$ millions)
Protocol attackedAmount stolen
(US$ millions)
27/10/20212,100Cream Finance130
16/06/2022609Inverse Finance5.8
17/04/2022500Beanstalk (loan 1)181 (total)
22/05/2021396N/AN/A
17/04/2022350Beanstalk (loan 2)181 (total)
This seems reasonable, in that even using a flash loan, borrowing hundreds of millions of dollars "worth" of cryptocurrency is expensive, and the fees for executing the flash loan attack are expensive, so only the lure of ill-gotten gain if the attack succeeds can motivate the expense.

Lets look at the two most profitable attacks in Table A, Cream Finance ($130M on October 27th, 2021) and Beanstalk ($181M on April 17th, 2022).

C.R.E.A.M. Finance

First, C.R.E.A.M. Finance, which is not to be confused with Crema Finance (exploited for $8.8M in July 2022). Molly White summarized the heist in DeFi platform C.R.E.A.M. is hacked for a third time, this time for $130 million:
Crypto lending service C.R.E.A.M. Finance lost $130 million in a flash loan attack. It was the third hack of the platform this year, following a $37.5 million hack in February and an $18.8 million attack in August.
Kevin Reynolds described the first flash loan heist in DeFi Protocols Cream Finance, Alpha Exploited in Flash Loan Attack; $37.5M Lost:
Decentralized finance protocols (DeFi) Cream Finance and Alpha Finance were victims of one of the largest flash loan attacks ever Saturday morning, resulting in a loss of funds totaling $37.5 million,
...
This is the second attack on a DeFi protocol in the last two weeks. Cronje's Yearn Finance suffered an an exploit in one of its DAI lending pools, according to the decentralized finance protocol’s official Twitter account. That exploit drained $11 million.
Cronje is Andre Cronje. The second heist exploited a reentrancy bug, not a flash loan. Eliza Gkritsi reported on it:
  • The attack was first reported by PeckShield in a tweet early on Monday. The blockchain security firm pointed to Ethereum records showing at least $6 million were drained at 5:44 UTC.
  • Cream Finance later confirmed the hack in a tweet, adding that 418,311,571 AMP tokens and 1,308.09 ether had been stolen, bringing the total value of the hack to just over $25 million. PeckShield updated its estimate, saying the hacker siphoned off about $18.8 million.
  • The root cause of the incident was lending of AMP tokens, Cream Finance Product Manager Eason Wu said on Discord. Other assets on Cream are secure, he said.
  • AMP token contracts allowed for a reentrancy attack, the same type of exploit used in the infamous DAO hack.
$CREAM
Tim Copeland reported the third heist in Ethereum DeFi protocol Cream Finance hacked for more than $130 million:
According to blockchain records, $92 million was stolen into one address and $23 million into another, alongside other funds taken. The funds are now being moved around to different wallets.

The funds stolen were mostly in Cream LP tokens and other ERC-20 tokens. Cream LP tokens are tokens you receive when you deposit funds into the Cream pools.

The price of cream (CREAM) has plummeted following the news, down from $152 to $111 in minutes — a 27% drop — according to CoinGecko.
It is now around $25. It is amazing that, with this history of incompetence, anyone would pay anything for it.

Beanstalk

Beanstalk was an algorithmic metastablecoin that, as David Gerard pointed out, was obviously a scam:
Beanstalk was offering interest on locked-in BEAN tokens on the order of 2,000% to 4,000% annual percentage rate. Those numbers are enough to tell you straight away that this is not a sustainable scheme.
It used a slightly different algorithm to the infamous Terra/Luna pair that "transitioned to state B" on May 13th, 2022. Twenty-six days earlier, Beanstalk suffered a flash loan attack. Molly White summarized the attack:
All my magic beans gone. An attacker successfully used a flash loan attack to exploit a flaw in Beanstalk Farms' stablecoin protocol, which allowed them to make off with 24,830 ETH (almost $76 million). The attacker then donated $250,000 to Ukraine before moving the remaining funds to Tornado Cash to tumble.

Estimated damages to the project were higher than the amount the hacker was able to take for themselves — around $182 million. The $BEAN token, once pegged to $1, dropped to nearly 0.
In Beanstalk DAO Exploited For $75 Million BowTied Effer provided more detail:
The exploiter used flash loans to borrow enough of the required voting power to push a proposal through. The proposal was pushed through an emergency execution option in Beanstalk. This emergency execution option allowed for a BIP to be executed if a ‘super majority’ voted in favor of it.

The BIP had a ‘hidden’ exit call that would withdraw all the funds once the BIP was executed.

Flash loans complete in a single block, so the $BEAN that was loaned was actually non-existent. But the loan allowed the exploiter to inflate his holdings and get a supermajority of $STALK, to push through the BIP, before the loan closed.

When all was said and done ~$75 million was removed from the liquidity pool (roughly evenly split between $BEAN and $ETH).
This is an example of the problems of governance via tokens that I discussed in Be Careful What You Vote For. In Code Is LOL Ed Zitron riffs on the same idea:
Much of what has been written about this has (as I have) used the term “attacker,” as if an attack was made in anything other than complete accordance with how the project worked. The project was set up to allow the largest amount of votes to pass whatever proposal was made, which, in this case, was “I think that I should have all of the money.” To describe this as an attack, a hack, or “malevolent” is to misunderstand the vacuous idea of “code is law” and Decentralized Autonomous Organizations.

“Code is law” refers to the idea that code can govern without human intervention, and DAOs are the Code Is Law monster - an autonomous organization that operates entirely based on what the highest amount of votes suggest. The problem is obvious if you’ve met more than one person in your life - human beings are fallible and biased, and prone to making mistakes.
...
The irony here is that cryptocurrency grew out of anti-government propaganda - the idea that our current laws allow the rich to take advantage of specific systems to benefit them. Except, if anything, cryptocurrency has created an even more exploitable system, naturally built for the rich to extract from the poor that they’ve tricked into buying into.

No comments: