Swap Execution

Using the Router

We recommend using the router for swapping stablecoins in Bunicorn. Before executing the swap, it is recommended that an external price source is use to fix the minimum output tokens receivable when selling a fixed amount of tokens, or maximum amount of input tokens to be used when purchasing a fixed amount of tokens.
Your smart contract should also:
    1.
    Have enough BNB / tokens when executing the swap
    2.
    Granted approval to the router when swapping from tokens

Obtaining Pool Addresses

It is necessary to specify which pools are to be used for the token swap. Get the list of pool addresses before proceeding.

Examples

USDC -> BUSD

swapTokensForExactTokens

Transferring tokens

Before swapping, the contract should be in possession of USDC. The caller can either send the tokens beforehand, or give allowance to the contract to call the transferFrom method. The short code snippet below showcases the latter.
1
uint256 amountIn = 50 * 10 ** usdc.decimals();
2
require(usdc.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed');
Copied!

Granting Approval

The next step is then to give the router some USDC
1
require(usdc.approve(address(buniCornRouter), amountIn), 'approve failed');
Copied!

swapTokensForExactTokens

1
IERC20[] memory path = new address[](2);
2
path[0] = usdc; // assuming core is specified as IERC20
3
path[1] = busd; // assuming usdt is specified as IERC20
4
buniCornRouter.swapTokensForExactTokens(
5
amountOutMin, // should be obtained via a price oracle, either off or on-chain
6
poolsPath, // eg. [usdc-busd-pool]
7
path,
8
msg.sender,
9
block.timestamp
10
);
Copied!
Last modified 3mo ago