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 qinput BUSD for WBNB tokens, you are going to do the swap using a BUSD-WBNB pool that contains xBUSD and xWBNB tokens BUSD and WBNB.
In general there may be several pools joining two tokens, or there may not be any in which case you would need to find a route: a sequence of several pools joining your input token to the desired output token. Choosing the right pools and finding routes is the role of decentralised exchanges and AMMs like PancakeSwap.
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.
Another key ingredient is the fee of the pool. This fee is determined by a fee rate 0≤r≤1: Among your qinput BUSD tokens, you are charged r×qinput tokens that are mainly used to pay the liquidity providers and are locked into the pool. Your remaining (1−r)×qinput BUSD tokens are put into the pool to do the swap. So we have
xpostBUSD=xpreBUSD+(1−r)×qinput.
But what is the quantity qoutput of WBNB tokens that you get after the swap? Well, this is the quantity that is withdrawn from the pool:
Note that the ratio qinputqoutput=xpreBUSD+(1−r)×qinput(1−r)×xpreWBNB gets smaller as the input quantity qinput increases. This phenomenon is known as slippage.