LP-Swap

# How swap output is calculated

When swapping on a decentralised exchange like PancakeSwap, have you ever wondered how the quantity of tokens you get after the swap is determined? Let us walk you through an example and explain you the maths behind it.

So let us say that you want to swap $q_{input}$ BUSD for WBNB tokens, you are going to do the swap using a BUSD-WBNB pool that contains $x^{\mathrm{BUSD}}$ and $x^{\mathrm{WBNB}}$ tokens BUSD and WBNB.

Recall the constant product rule that relates the quantities of BUSD and WBNB in the pool before and after the swap:

$x_{post}^{\mathrm{BUSD}}\times x_{post}^{\mathrm{WBNB}} = x_{pre}^{\mathrm{BUSD}} \times x_{pre}^{\mathrm{WBNB}}.$

Another key ingredient is the fee of the pool. This fee is determined by a fee rate $0\leq r \leq 1$: Among your $q_{input}$ BUSD tokens, you are charged $r\times q_{input}$ tokens that are mainly used to pay the liquidity providers and are locked into the pool. Your remaining $(1-r)\times q_{input}$ BUSD tokens are put into the pool to do the swap. So we have

$x_{post}^{\mathrm{BUSD}}=x_{pre}^{\mathrm{BUSD}}+ (1-r)\times q_{input}.$

But what is the quantity $q_{output}$ of WBNB tokens that you get after the swap? Well, this is the quantity that is withdrawn from the pool:

$x_{post}^{\mathrm{WBNB}}=x_{pre}^{\mathrm{WBNB}} - q_{output}.$

So the constant product rule rewrites

$(x_{pre}^{\mathrm{BUSD}}+(1-r)\times q_{input})\times (x_{pre}^{\mathrm{WBNB}}-q_{output})= x_{pre}^{\mathrm{BUSD}} \times x_{pre}^{\mathrm{WBNB}},$

and so isolating your output $q_{output}$ of WBNB tokens yields the swap formula:

$q_{output}=\frac{(1-r)\times q_{input} \times x_{pre}^{\mathrm{WBNB}} }{x_{pre}^{\mathrm{BUSD}}+(1-r)\times q_{input}}.$

Note that the ratio $\frac{q_{output}}{q_{input}}=\frac{(1-r)\times x_{pre}^{\mathrm{WBNB}} }{x_{pre}^{\mathrm{BUSD}}+(1-r)\times q_{input}}$ gets smaller as the input quantity $q_{input}$ increases. This phenomenon is known as slippage.

Docs