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 BUSD for WBNB tokens, you are going to do the swap using a BUSD-WBNB pool that contains and 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:
Another key ingredient is the fee of the pool. This fee is determined by a fee rate : Among your BUSD tokens, you are charged tokens that are mainly used to pay the liquidity providers and are locked into the pool. Your remaining BUSD tokens are put into the pool to do the swap. So we have
But what is the quantity of WBNB tokens that you get after the swap? Well, this is the quantity that is withdrawn from the pool:
So the constant product rule rewrites
and so isolating your output of WBNB tokens yields the swap formula:
Note that the ratio gets smaller as the input quantity increases. This phenomenon is known as slippage.