Back to Blog

#3: KyberSwap Incident: Masterful Exploitation of Rounding Errors with Exceedingly Subtle Calculations

Code Auditing
February 10, 2024

On November 23, 2023, there were a series of attacks targeting KyberSwap. These attacks resulted in a total loss of over $48 million. The fundamental issue originated from incorrect rounding direction during KyberSwap's reinvestment process. This subsequently led to improper tick calculations and, ultimately, to double counting of liquidity.

We've released an extensive report, "Yet Another Tragedy of Precision Loss: An In-Depth Analysis of the KyberSwap Incident", which delves into the particulars of the event. For a deeper understanding, you are encouraged to consult the full analysis. Below, we provide a succinct introduction to this incident, highlighting it as one of the top ten security incidents of 2023.

Background

KyberSwap is a decentralized automated market maker (CLAMM) platform. To meet the market demand of the concentrated liquidity, KyberSwap Elastic is launched based on Uniswap V3, with several improvements including the reinvestment curve to enable the auto-compounding of the liquidity provision yields.

1. Tick and Square Root Price

Tick in Uniswap V3-like CLAMMs is used to mark the price in a discrete manner so that the LPs can provide liquidity within a fixed range instead of the entire range (hence the term "concentrated").

Liquidity can be put in a range between any two ticks (which need not be adjacent), i.e., a pair of tick indices (a lower tick and an upper tick). Specifically, the price of each tick (at an integer index i) is defined as follows:

In practice, the square root price (denoted as sqrtP or sqrtPrice) is used:

It is also possible to compute the current tick based on the current square root price:

Obviously, while only a single square root price is calculated for a given tick, multiple square root prices may point to the same tick. For a more detailed explanation, please refer to the documents of Uniswap V3 and KyberSwap.

2. Reinvestment Curve

Uniswap V3-based CLAMM suffers from the pool utilization of LP fees and significant gas fees required to reinvest. Hence, KyberSwap adopted reinvestment curve to address the problem.

The key to the reinvestment curve is that the fees collected in each swap is accumulated as additional liquidity in the pool as the reinvestment liquidity within an infinite range. The reinvestment tokens are minted to the LPs and the reinvestment liquidity accumulated is allocated to the LPs accordingly. Besides, the reinvestment liquidity also participates in the swap and price calculation process.

The corresponding code for the calculations introduced above is shown in the computeSwapStep function in following code snippet of the corresponding pool.

It should be noticed that due to the reinvestment liquidity, the liquidity in this function is a sum of two components: baseL for the base liquidity, and reinvestL for the accumulated liquidity for the reinvestment.

3. Swap in KyberSwap

The implementation of the swap function of the KyberSwap's pool discussed earlier can be abstracted as the below diagram:

The crucial logic pertaining to the tick calculation resides within the swapping while loop, as highlighted by the blue rectangle. Specifically, the principal logic involves the computeSwapStep function and the _updateLiquidityAndCrossTick function. The former calculates key states, such as input and output amounts for the given swap and nextSqrtP, while the latter handles cases when a cross-tick occurs.

Traditionally, when the price increases, we refer to this as shifting the tick right/upward; otherwise, we say the tick moves left/downward.

To better understand the vulnerability that will be discussed later, it's essential that we explore the relevant code logic of the computeSwapStep function, as illustrated in the following figure:

Specifically, the calcReachAmount function calculates the input tokens needed for the target price targetSqrtP (lines 50-57). If the usedAmount is greater than specifiedAmount, the tick isn't crossed, and nextSqrtP is calculated from deltaL (i.e., the delta liquidity, lines 59-62). deltaL is determined using the estimateIncrementalLiquidity function, and the final price nextSqrtP is calculated with the calcFinalPrice function (lines 70-79). If less input is needed, nextSqrtP is set to the next tick's price, but this case isn't used in the attack.

The steps outlined above make clear that if the tick is not crossed, the nextSqrtP returned by computeSwapStep should not be larger than the sqrtP of the next tick. However, due to the dependency of the price on the liquidty (base liquidity and delta liquidity) and precision loss, the attackers is able to manipulate the nextSqrtP to be larger while the tick is not crossed.

Vulnerability Analysis

The root cause lies in the flawed tick calculation caused by the incorrect rounding direction within the delta liquidity calculation (i.e., the estimateIncrementalLiquidity function) of the SwapMath contract (which is invoked by the computeSwapStep function). This, in turn, improperly affects the tick calculation later.

Interestingly, upon examining the comment at line 188 (highlighted by the blue rectangle), we find that deltaL is intended to be rounded up in order to round down the nextSqrtP. However, deltaL is mistakenly rounded down due to the use of the mulDivFloor function at line 189. Consequently, nextSqrtP is inaccurately rounded up.

Attack Analysis

The attackers initiated multiple attack transactions, with each transaction draining multiple pools. For the sake of simplicity, the following discussion is based on the first attack within the attack transaction.

The core attack logic consists of the following six steps:

  1. Borrowing 2,000 WETH via flash loan from AAVE.

  2. Swapping 6.850 WETH for 6.371 frxETH in the victim pool 0xfd7b. This step is used to push current tick and currentSqrtP into a location where currently no liquidity is present.

  • currentSqrtP seems to be randomly chosen by the attacker, and the swap stops at this price precisely.
  • Base liquidity (baseL) is zero after this step, but the reinvestment liquidity (reinvestL) is non-zero.
  1. Adding liquidity into the pool and then removing part of the liquidity. This step is used to control the range and total liquidity to a desired amount.
  • The tick range is chosen based on the currentSqrtP.
  • The desired liquidity for the attack could be derived from the tick range, although the corresponding calculation logic requires further exploration.
  1. Swapping 387.170 WETH for 0.06 frxETH in the pool. This step is used to manipulate the current tick so that nextTick == currentTick. Specifically, the swap in step 4 cunningly deceives the pool into believing that the tick 111,310 is not crossed. However, in reality, the currentSqrtP is indeed greater than the sqrtP of tick 111,310.
  1. Swapping 0.06 frxETH for 396.244 WETH in the pool. Note that the swapping direction is opposite compared to the previous step. In this step, liquidity is double counted to make the swap profitable and consequently drain the pool.
  1. Repaying the flash loan, and harvesting 6.364WETH and 1.117 frxETH.

For an in-depth examination, please refer to our comprehensive analysis, which includes more details with calculations and figures.

Summary

The fundamental issue in this incident stems from incorrect rounding during KyberSwap's reinvestment process, leading to inaccurate tick calculations and ultimately to double liquidity counting. This incident highlights the intricate and elusive nature of precision loss problems within DeFi protocols, posing a serious challenge to the entire community.

This 2023 attack stands out for its complexity, featuring exceptionally nuanced calculations and serving as a prime example of the many precision-related security incidents that have significantly tested the community. Moreover, after extensive negotiations with authorities, the attacker issued a provocatively toned message to the public, asserting a demand for total control over the protocol.

Sign up for the latest updates
~$10.26M Lost: Term Finance, MAYAChain | BlockSec Weekly
Security Insights

~$10.26M Lost: Term Finance, MAYAChain | BlockSec Weekly

During the week of August 17-23, 2026, two notable security incidents resulted in approximately $10.26M in total losses across Ethereum and MAYAChain. The highlighted Term Finance incident (~$8.5M) was a flawed governance design rather than a coding bug: each vault ships its own on-chain DAO whose support-threshold and participation checks are purely relative, with no absolute floor; with almost no one taking part in governance, there was no electorate to vote a proposal down and no guardian to cancel one, so an attacker acquired a supermajority of a vault's voting power for roughly 0.5 ETH and, after the execution delay elapsed, drained six of Term's vaults for approximately $8.5M in total. MAYAChain (~$1.76M) lost funds to a chain of accounting and state-validation defects, where a single crafted deposit made valid withdrawals appear to have failed, triggered a recovery path that inflated a low-liquidity pool's recorded native-token balance with no real backing, and let the attacker drain the inflated value by adding and withdrawing liquidity.

Harmony Cross-Shard ONE Mint + ~$47M Key Losses | BlockSec Weekly
Security Insights

Harmony Cross-Shard ONE Mint + ~$47M Key Losses | BlockSec Weekly

During the week of August 10-16, 2026, 5 notable security incidents are featured, involving approximately $47M in quantified losses, with the detailed analysis focused on a chain-implementation flaw in the Harmony Layer-1. Harmony suffered unauthorized minting of native ONE through a cross-shard receipt replay: destination shards derived the receipt spent-marker from unauthenticated MerkleProof.ShardID and BlockNum fields instead of the signed source header, so an already-credited receipt could be replayed with no matching source-shard debit. Approximately 3.01T ONE was forged, but its nominal value far exceeds the token's market capitalization and is neither realizable nor confirmed realized loss, so Harmony is excluded from the total; the ~$47M came from private-key compromises (Unknown Whale Wallet ~$25M, Kite ~$14M, and Coinsbuy ~$7.9M) plus a Fox business-logic flaw (~$117K).

~$1.6M Lost: Moke Token, LpdFi Exploits | BlockSec Weekly
Security Insights

~$1.6M Lost: Moke Token, LpdFi Exploits | BlockSec Weekly

During the week of August 3-9, 2026, 2 notable security incidents on BNB Chain resulted in approximately $1.6M in total losses, both from price manipulation. The highlighted LpdFi incident (~$697K) reused the same manipulable PancakeSwap pair reserves for both order valuation and interest redemption, letting the attacker inflate a position's principal and reshape the pool to redeem an oversized interest claim. Moke Token (~$906K) combined a manipulable spot price with duplicated LP dividend accounting to claim inflated MOKE and collect the resulting BNB dividends multiple times.

Best Security Auditor for Web3

Validate design, code, and business logic before launch. Aligned with the highest industry security standards.

BlockSec Audit