Skip to content
KALANBLON
Show contents

Chapter 4 of 6 · 20 min

Automated exchanges, MEV and oracles

By the end of this chapter, you'll be able to

  • Compute a swap on a constant-product automated market maker
  • Measure the impact of a purchase on the price
  • Simulate a sandwich attack and the protection by slippage limit
  • Explain why an instantaneous price is a bad oracle and name protections

The automated market maker

A decentralised exchange has no order book: it has a pool of two tokens, and a formula that sets the price. The most common is the constant product: if the pool holds x A tokens and y B tokens, every swap must keep x × y = k (before fees). The more B is bought, the more expensive it becomes: the price reacts to demand, with nobody setting it.

With a slippage limit, Awa's transaction fails instead of being executed at a bad price.

Step 5 of 5
Text description of the animation
  1. The transaction waits to be included; everyone can read it.
  2. By paying more in fees, the bot gets placed just before Awa.
  3. The price went up because of the bot's purchase.
  4. The price is even higher thanks to Awa's purchase: the bot sells at a profit.
  5. With a slippage limit, Awa's transaction fails instead of being executed at a bad price.
class Pool:
    def __init__(self, tokens, stables, fee=0.003):
        self.tokens, self.stables, self.fee = tokens, stables, fee

    def price(self):
        return self.stables / self.tokens                        # STABLE per TOKEN

    def buy_tokens(self, stables_in, minimum=0):
        net = stables_in * (1 - self.fee)
        out = self.tokens - self.tokens * self.stables / (self.stables + net)
        if out < minimum:
            raise ValueError(f"slippage too high: {out:.0f} < {minimum}")
        self.stables += stables_in
        self.tokens -= out
        return out

    def sell_tokens(self, tokens_in):
        net = tokens_in * (1 - self.fee)
        out = self.stables - self.tokens * self.stables / (self.tokens + net)
        self.tokens += tokens_in
        self.stables -= out
        return out

pool = Pool(tokens=100_000, stables=500_000)
print(f"initial price: {pool.price():.3f} STABLE per TOKEN")
for purchase in (5_000, 50_000, 250_000):
    trial = Pool(100_000, 500_000)
    received = trial.buy_tokens(purchase)
    print(f"buying with {purchase:>7} STABLE → {received:>7.0f} TOKENS, average price {purchase / received:.3f}, new price {trial.price():.3f}")
initial price: 5.000 STABLE per TOKEN
buying with    5000 STABLE →     987 TOKENS, average price 5.065, new price 5.100
buying with   50000 STABLE →    9066 TOKENS, average price 5.515, new price 6.048
buying with  250000 STABLE →   33267 TOKENS, average price 7.515, new price 11.239

A small purchase is made almost at the displayed price; a purchase equal to half of the pool pays much more on average and makes the price jump. That is price impact, unavoidable with a constant-product formula.

The sandwich attack

Whoever builds a block chooses the order of transactions and can insert some. The value they can extract this way is called MEV (Maximal Extractable Value). The most common attack is the sandwich: buy just before a large purchase spotted in the waiting queue, then sell just after.

class Pool:
    def __init__(self, tokens, stables, fee=0.003):
        self.tokens, self.stables, self.fee = tokens, stables, fee
    def buy_tokens(self, amount_in, minimum=0):
        out = self.tokens - self.tokens * self.stables / (self.stables + amount_in * (1 - self.fee))
        if out < minimum:
            raise ValueError("slippage too high: transaction cancelled")
        self.stables += amount_in; self.tokens -= out
        return out
    def sell_tokens(self, amount_in):
        out = self.stables - self.tokens * self.stables / (self.tokens + amount_in * (1 - self.fee))
        self.tokens += amount_in; self.stables -= out
        return out

# Without attack: what Awa would receive
alone = Pool(100_000, 500_000).buy_tokens(50_000)

# With a sandwich
pool = Pool(100_000, 500_000)
bot = pool.buy_tokens(30_000)                 # 1. the bot jumps ahead
awa = pool.buy_tokens(50_000)                 # 2. Awa buys at a higher price
gain = pool.sell_tokens(bot) - 30_000         # 3. the bot sells right after
print(f"Awa alone: {alone:.0f} TOKENS | after sandwich: {awa:.0f} TOKENS (loss {alone - awa:.0f})")
print(f"bot's profit: {gain:.0f} STABLE")

# Protection: Awa accepts at most 1% slippage compared with the expected amount
pool = Pool(100_000, 500_000)
pool.buy_tokens(30_000)
try:
    pool.buy_tokens(50_000, minimum=alone * 0.99)
except ValueError as e:
    print("with a slippage limit:", e)
Awa alone: 9066 TOKENS | after sandwich: 8112 TOKENS (loss 954)
bot's profit: 5527 STABLE
with a slippage limit: slippage too high: transaction cancelled

The slippage limit (minimum) makes the attack pointless: if the price has moved too much, Awa's transaction fails, and the bot is left with tokens bought too expensively. It does not remove all the risk (a bot can aim just under the limit): it is combined with private waiting queues or batch auctions, which execute the orders of a block at the same price.

Mini-lab: choosing your slippage limitPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: a moving-average oracle

Write an AverageOracle class that records a pool's price once per block, at the end of the previous block, and returns the average of the last n recorded prices. Replay the attack: during the attack block, the instantaneous price shoots up, but the oracle only sees the prices recorded in previous blocks. Compare the borrowing capacity with both oracles.

Hint 1
Keep a list self.prices_per_block; a method end_of_block(pool) appends pool.price(), and price() returns the average of the last n items.
Hint 2
Simulate 10 normal blocks with small swaps, then the attack block: the manipulation and its unwinding happen in the same block, before end_of_block is called.
Show the solution and common mistakes
class Pool:
    def __init__(self, tokens, stables):
        self.tokens, self.stables = tokens, stables
    def price(self):
        return self.stables / self.tokens
    def buy_tokens(self, amount_in):
        out = self.tokens - self.tokens * self.stables / (self.stables + amount_in)
        self.stables += amount_in; self.tokens -= out
        return out
    def sell_tokens(self, amount_in):
        out = self.stables - self.tokens * self.stables / (self.tokens + amount_in)
        self.tokens += amount_in; self.stables -= out
        return out

class AverageOracle:
    def __init__(self, n):
        self.n, self.prices_per_block = n, []
    def end_of_block(self, pool):
        self.prices_per_block.append(pool.price())
    def price(self):
        last = self.prices_per_block[-self.n:]
        return sum(last) / len(last)

pool, oracle = Pool(100_000, 500_000), AverageOracle(n=8)
for block in range(10):                                  # normal activity
    if block % 2:
        pool.buy_tokens(3_000)
    else:
        pool.sell_tokens(600)
    oracle.end_of_block(pool)

collateral = 10_000
bought = pool.buy_tokens(2_000_000)                      # attack block: manipulation…
instantaneous = collateral * pool.price() * 0.75
averaged = collateral * oracle.price() * 0.75
pool.sell_tokens(bought)                                 # …and unwinding in the same block
print(f"capacity with the instantaneous price: {instantaneous:>10.0f} STABLE")
print(f"capacity with the average oracle     : {averaged:>10.0f} STABLE")
capacity with the instantaneous price:     937566 STABLE
capacity with the average oracle     :      37285 STABLE

The average oracle does not see the manipulation, which starts and ends in the same block: the borrowing capacity stays normal. To skew the average, the attacker would have to hold an artificial price for several blocks, exposed to arbitrageurs who bring it back to the market price, which is very expensive.

Common mistakes:

  • Updating the oracle during swaps instead of once per block: the average then includes the manipulated price.
  • Choosing a window that is too short (n = 1): you are back to almost the instantaneous price; too long, the oracle reacts too slowly to a real drop.
  • Using a single illiquid pool as the source: even an average can be manipulated if the pool is small.

Summary

  1. 1A constant-product exchange sets the price with x × y = k: the larger the purchase, the stronger the price impact.
  2. 2Whoever orders the transactions can extract value (MEV), notably through the sandwich attack.
  3. 3A slippage limit makes a transaction fail if executed at a price that is too unfavourable.
  4. 4An instantaneous price read from a single pool can be manipulated within one transaction, with a flash loan.
  5. 5A robust oracle averages prices over several blocks and aggregates independent sources.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.