Vyper, Reentrancy, Curve Finance and the Danger to DeFi

Curve DAO Token (CRV) on a smart phone

Oh, the irony: Vyper was created to offer a more secure programming option for smart contracts on Ethereum than the more commonly used Solidity. Sadly, the reverse has turned out to be true. A reentrancy attack enabled by a flaw in older versions of Vyper allowed attackers to steal $110 million in late July ‘23.

The massive hack targeted the prominent Curve Finance DEX, which operates factory pools that enable its low-fee stablecoin trading. Several projects that used Curve saw losses as well.

The Curve Finance exploit is one of the biggest thefts in crypto so far this year, but that isn’t the only reason this attack is notable. What happened has broad implications for DeFi platforms and the industry-wide goal of creating secure, blockchain-based finance options in web3.

Over $655 million in crypto was stolen in the first half of ‘23 alone, with the vast majority–$471 million–lost in attacks. A closer look at the Curve Finance exploit reveals why this particular incident is so troubling, and what it means to the future of DeFi.

We’ll start with a few basic concepts you’ll need to understand in order to examine this attack in detail and understand its implications.

What is a DEX?

A decentralized exchange (DEX) offers an alternative to the structure of traditional financial institutions. In the legacy finance industry, banks and similar corporations are centralized institutions. In contrast, a decentralized exchange is a non-custodial vehicle that enables peer-to-peer cryptocurrency trades facilitated by smart contracts. Using a DEX removes the need for an intermediary institution which holds your money. Any DEX profits are shared by all participants. Data and coins aren’t centralized but instead are stored in users’ wallets. Because trades take place on the blockchain, there’s greater transparency.

Not all crypto exchanges are structured as a DEX. Many are set up as traditional corporations–the collapse of FTX last year highlighted that the exchange was not a DEX, for instance.

Curve Finance is a type of DEX that employs an automated market maker (AMM). AMMs create liquidity for crypto transactions by holding pools of tokens to enable swaps. Liquidity providers stake their coins to such pools in exchange for compensation. The pools help turn what could otherwise be an illiquid asset into one that’s immediately available to be traded.

What is a factory pool?

When a DEX aims to operate many liquidity pools, it may create a framework it can use for pool setup, rather than manually creating each pool. This is what’s known as a factory pool system–and it’s the approach Curve uses. Factory pools enable projects to easily create their own pools. This more permissionless approach aligns with the goals of web3.

This factory-pool setup is important to bear in mind because if the pool structure is replicated, all the pools may have a similar security flaw.

What is a reentrancy attack?

Smart contracts that enable a user to buy, sell, or swap crypto can have a security flaw relating to reentrancy. Here’s how it works:

While a smart contract is in the process of calling an outside contract to complete a trade, there’s a point where funds are in transit and have left the user’s account, but the user’s account balance has not yet been updated.

At this point, the outside contract may be able to reenter the initial contract and ask for a withdrawal again, before that transaction completes and the user’s balance is updated to a lower figure. It’s known as an interrupted contract call.

In this way, the attacker can keep amassing funds. A skilled attacker can exploit the reentry flaw over and over, pocketing many additional withdrawals.

Smart contracts generally have a security feature that prevents reentry, known as a reentrancy lock or guard. But if this measure fails, reentrancy attacks can occur.

This is what happened in the Curve exploit. The troubling feature of this particular attack is that the flaw the hacker exploited lies in the underlying Vyper code, which is widely used in Web3.

The Curve exploit step-by-step

How did the Curve Finance exploit unfold? Let’s walk through it.

A warning ignored

Three months before the attack, back in April ‘23, cybersecurity firm ChainSecurity notified Curve and projects using Curve’s factory pools of a ‘read only’ reentrancy vulnerability. The flaw affects the algorithm that prices coins from the pools as they’re sold or traded. Read-only functions are often less well-secured in a contract since they are not state-altering.

But in this case, ChainSecurity found that while a transaction was in progress and a liquidity imbalance existed, an attacker could use reentrancy to alter the value of the read-only ‘get_virtual_price’ function.

If an attacker became aware of the flaw, they could exploit it through a flash-loan attack. A bad actor can deposit coins into one of the pools, then quickly start a withdrawal. During the transaction, the attacker can exploit the transitional moment where the pool is imbalanced–the coins are out but the balance hasn’t been updated yet–to manipulate pricing and inflate the value of the pool.

This value inflation makes the coins momentarily worth more, enabling costlier trades. ChainSecurity estimated that even if the value of the coins was only inflated to twice their actual value, it put $100 million at risk. In some scenarios, ChainSecurity found the price could be manipulated to be worth much more than 2X.

Some projects appear to have implemented suggested fixes for this security flaw, the simplest of which is to call a pool’s ‘withdraw_admin_fees’ function, which triggers a functioning reentrancy lock.

But for some crypto projects and for Curve, the warning seems to have gone unheeded.

The attack begins

On July 21, Curve Finance’s omnipool platform Conic Finance was exploited by a single attacker, who drained $3.26 million in ETH. Initially, fingers pointed at a Curve oracle, the means by which smart contracts access data located outside the blockchain.

As DeFi had been the target of several attacks in the months prior and the amount stolen isn’t huge, this hack didn’t garner much attention–it seemed to be just another glitch in the matrix. But the problem will turn out to be much bigger than one Curve contract.

The damage spreads

Nine days later, on July 30, Curve Finance reported that several of its pools holding various types of wrapped ETH “have been exploited as a result of a malfunctioning reentrancy lock.”

Vyper shared that three older versions of its code have the vulnerability. Initial losses were reported at $47 million.

Later that morning, the security firm Ancilia found hundreds of contracts appear to be using the vulnerable versions of Vyper code:

The damage spread as the day went on. Another DEX, Ellipsis, reported some of its stable pools of BNB were exploited.

Other ETH pools saw attacks as well:

  • Alchemix: $13.6M
  • JPEGd: $1.6M
  • Metronome: $1.6M

Later in the day, Curve’s CEO, Michael Egorov, told Cointelegraph that $22 million worth of Curve’s native CRV token was drained from a swap pool via Telegram.

At this point, the whole DeFi ecosystem began to be affected: Mass withdrawals occurred as users sought to safeguard their coins and white hats swung into action, trying to identify problems and fixes.

The value of CRV sunk due to Curve’s losses–and soon, that would trigger another problem.

Does social media help–or hurt?

By the next day, it’s reported that other platforms were taking action to limit their exposure to the problems at Curve. The yield-farm DEX Auxo DAO pulled liquidity from pools it held with Curve and another DEX, Convex Finance, which offered yield-optimization strategy on CRV.

Convex’s liquidity plummeted more than 52% after the Curve exploit. Industry data showed Convex held nearly 300 million CRV tokens, which represented one-third of the entire circulating supply of CRV at the time. On Curve, users need to stake their tokens for 4 years to earn pool interest, but Convex’s solution circumvents that requirement.

The total amount estimated stolen in the Curve exploit has risen at this point to $52 million–and analysis of why this hack was so successful and widespread has begun. One theory was that posts about the exploit on X and other social channels before all affected platforms had a chance to secure their Vyper code may have given more hackers information that allowed them to join in the grift.

“There are concerns in the ETH security community that communication of bugs needs to be more discreet,” Michael Lewellan, the head of solutions architecture for OpenZeppelin, told Decrypt.

Meanwhile, ethical hackers swung into action. Two white hats managed to find and return nearly 3,000 ETH to Curve on July 31.

A bounty is posted

Curve teamed up with other affected parties Alchemix and Metronome on Aug. 3 to offer the attacker a 10% bounty if the other 90% of the coins stolen are returned. They gave the attacker an Aug. 6 deadline, after which the bounty offer would end, prosecution would be pursued, and the 10% bounty was offered to any white-hat hacker who could identify the attacker.

Curve’s troubles spark a loan-liquidity crisis

Remember how the value of CRV began to sink due to the exploit? By early August, CRV’s value had declined 23 percent, triggering a possible liquidity crisis at Curve.

It came to light that Curve founder Michael Egorov had taken out over $65 million in loans using CRV as collateral. The loans appeared to help finance lavish spending including the purchase by Egorov and his fiance of two mansions in Australia worth $41 million. Now, those loans could be called if the value of CRV sank to $.35, an event that would leave major crypto lenders with large bad debts, force the liquidation of massive amounts of CRV, and likely spell the end of Curve.

To shore up Curve’s finances, Egorov quickly sold more than 106 million CRV to prominent figures in the crypto space. Among the big-name ‘over the counter’ buyers of CRV in this timeframe were Tron founder Justin Sun, Huobi co-founder Jun Du, crypto trader DCFGod, and NFT investor Machi Big Brother (Jeffrey Huang). Egorov also reduced his debt by repaying nearly 14 million in loaned stablecoins.

This helped stabilize CRV’s price, at least temporarily, though Curve’s native stablecoin, crvUSD, briefly de-pegged on Aug. 3.

Some observers–including notably, Binance CEO Changpen Zhao–found it ironic that eventually, Curve’s value was rescued by the central exchange (CEX). While the price of CRV plummeted on the DEX, the CEX pegged it higher, helping to keep CRV afloat.

73% of funds return

With no peep from the attacker by the bounty deadline, in early August, Curve offered a bounty of 10% of the remaining outstanding funds, or $1.85 million. Curve also extended the offer that if the attacker returned funds in full, they won’t prosecute.

Ethical hackers swung directly into action. By Aug. 7, some 73% of the stolen funds were returned, amounting to $22 million worth of ETH. Some funds were returned by the attacker, though the bounty deadline was missed.

With the money flowing back in, Curve announced it would reimburse affected users.

CRV’s value continues to sink

In the weeks since the exploit, the CRV continued to decline. From a high around $1.25 in Feb. ‘23, CRV was trading at $.73 right before the exploit. Egorov’s selloff seemed to stabilize the token around $.50-$.60 for a couple of weeks, but then it declined further.

As of the end of August, it was trading in the $.40 range, once again dangerously near the trigger point for default on Egorov’s loans when the exploit occurred.

Is it over?

The lingering question in the aftermath of the Curve Finance exploit is whether this reentrancy hack on Vyper-based projects is over. The short answer is…we don’t know. Remember, hundreds of projects were using these vulnerable versions of Vyper when Curve was hacked.

If there’s a crypto project left somewhere that’s still using those Vyper versions, and they haven’t updated or executed a fix, that project is ripe for theft.

Some may have heaved a sigh of relief since most of the funds were returned in the end, but it would be foolish to grow complacent about the threat posed by flaws in code widely used in DeFi.

The big takeaways

There’s been much analysis since this exploit occurred. What are the key takeaways?

  • Vulnerabilities in underlying code continue to be an ongoing concern. The Curve exploit revealed how flaws in programming languages have the potential to ripple broadly through DeFi, causing massive losses. More needs to be done to stress-test these foundations on which DeFi is being built.
  • Beware of concentration of wealth. Observers have noted that it’s troubling that Egorov was able to build such a large stake in CRV.
  • Overextended crypto lenders could be another weakness in DeFi. After seeing how much had been loaned to Egorov, it appears the crypto lending space may need to review its policies: “This makes those lending protocols look pretty careless for allowing the Curve founder to build such a large position,” Decrypt’s Liam Kelly wrote.
  • Next time, DeFi might not be so lucky. When attackers return funds or white hats are able to locate and return stolen coins, web3 tends to heave a sigh of relief and go back about its business. But the return of Curve’s funds was lucky and may not happen next time there’s a similar hack.

The biggest takeaway for users: Pay attention to the structure and operations of any DEX you trade on. Know what language the platform is built in, how updated it is, and whether it’s racking up debts or has come to be dominated by a few whales.

Subscribe to updates from the Dragonscale Newsletter

Don't miss out on the latest posts. Sign up now to get new posts sent directly to your inbox.