Resources

People often ask me "How did you learn how to hack?" The answer: by reading. This page is a collection of the blog posts and other articles that I have accumulated over the years of my journey. Enjoy!

Saving $100M at risk in KyberSwap Elastic- 1292

100ProofPosted 2 Years Ago
  • KyberSwap is a CLMM that was implemented from scratch. Concentrated Liquidity Market Makers (CLMM) are market makers where the liquidity is provided only within narrow bands. This allows for higher capital efficiency and less impermanent loss for LPs.
  • CLMM price ranges are divided into ticks. Although they have a given number, they translate to the price of 1.0001t, where t is the tick. For a tick spacing of 10 in the price range $1.00-$1.22, you would deposit into the tick range (0,2000) because 1.00010 = 1.00 and 1.00012000 = 1.22. Each pool on KyberSwap consists of two tokens.
  • When using a CLMM, a swap by a trader causes the price to shift. When this happens, the liquidity tick for the price goes to a different location, resulting in a sub-swap to occur. The degree of price impact is determined by the amount of liquidity inside a given tick range.
  • There are three important invariants with CLMMs that should always be kept:
    1. Liquidity should never go below zero.
    2. When going between ticket range boundaries, the liquidity must either be increased or decreased.
    3. Should look like a normal distribution.
  • The vulnerability literally lies on an edge case. When handling the edge between two ticks, the boundary edge cases had a major issue. When performing a one-for-zero (WHAT IS THIS) swap, the nextTick() function will be calculated as the currentTick, even though it crossed a boundary. Practically, this allows us to double add liquidity.
  • How do we make money from this though? By getting our liquidity added *twice*, we can effectively steal funds from the protocol. Under the hood, the actual bug was in the backwards portion of the code. The first sub-swap cross the tick boundary, which is fine. On the second sub swap, the price difference is so small that is does not change. Hence, the sqrtP and nextSqrtP end up being the same, leading to a double add.
  • The author wrote a proof of concept using a flash loan from Aave to drain the entire protocol of all its funds. The hacker got a large payout and no one lost money. Except, later on, a variant of this bug was found that stole all of the funds. Overall, an amazingly complicated bug with a good write up from the perspective of the author.