Trading tokens in decentralized exchange is quite different from trading coins or tokens in centralized exchanges. In this tutorial I will cover different parts of trading starting from creating the trading pair to adding or removing liquidity, and buying, selling or swapping tokens. Example costs in this tutorial assume gas price is 5 gwei. The gas costs are taken from real-life smart contract calls, but can vary slightly due to small differences in relevant smart contract parameters.
Creating a liquidity pool and trading pair
When creating a trading pair, first step is to enable all relevant tokens, however you don't need to enable BNB as BNB can be sent to the router directly. This will ask the token contracts to allow router contract to transfer tokens from the user's address to the contract address of the liquidity pool. The router contract will first create the contract for the liquidity pool. Creating the liquidity pool will cost for example 3683231 gas (0.018416155 BNB). Adding liquidity to the liquidity pool during creation will cost for example 560,926 gas. Exact amounts will depend on the parameters of the token contract(s).
Adding more liquidity to liquidity pool
If there is already a liquidity pool for a trading pair, but it doesn't contain enough tokens to execute the swap, user needs to add more liquidity to the liquidity pool. PancakeSwap tries to keep the total values of the two token balances in the liquidity pool as close to each other as possible, so usually the ratio of two token balances must stay same before and after adding more liquidity.
It is however possible to add more balance of just one token, but half of the amount is automatically converted to balance of the other token. This is called zapping in PancakeSwap. In most cases zapping should be kept enabled as it will also allow adding larger amounts of tokens to the liquidity pool.
Like when creating the liquidity pool, first step in adding more liquidity is enabling the tokens for which you are adding liquidity. Currently PancakeSwap doesn't allow preapproving larger amount or increasing existing allowance using increaseAllowance
method. When adding liquidity, the amounts specified when enabling the tokens much match the amounts when executing the actual swap as the router contract might be different depending on the amounts and status of zapping. When the swap is finished, special liquidity pool tokens representing the share of liquidity provider fee are sent to address of the user.
Adding liquidity to existing liquidity pool will cost about 157005 gas (0.000785025 BNB).