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 qinputq_{input} BUSD for WBNB tokens, you are going to do the swap using a BUSD-WBNB pool that contains xBUSDx^{\mathrm{BUSD}} and xWBNBx^{\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:

xpostBUSD×xpostWBNB=xpreBUSD×xpreWBNB.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 0r10\leq r \leq 1: Among your qinputq_{input} BUSD tokens, you are charged r×qinputr\times q_{input} tokens that are mainly used to pay the liquidity providers and are locked into the pool. Your remaining (1r)×qinput(1-r)\times q_{input} BUSD tokens are put into the pool to do the swap. So we have

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

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

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

So the constant product rule rewrites

(xpreBUSD+(1r)×qinput)×(xpreWBNBqoutput)=xpreBUSD×xpreWBNB,(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 qoutputq_{output} of WBNB tokens yields the swap formula:

qoutput=(1r)×qinput×xpreWBNBxpreBUSD+(1r)×qinput.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 qoutputqinput=(1r)×xpreWBNBxpreBUSD+(1r)×qinput\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 qinputq_{input} increases. This phenomenon is known as slippage.