Let's Swap
Always practice solid risk management rules when experimenting with swaps: use the correct slippage values and trusted currency pairs, double-check the numbers before confirming, and compare external price sources.
Let's create a new module and import the router into it:
Basic module
As you try to compile the code above, you will get a warning; don't worry, it's fine.
Now let's add the dependencies we will need for this experiment, as well as a basic entry function that we can call in a transaction later:
Let's withdraw
1000
Aptos coins from an account and see how many BTC we can get in exchange:The provided code above wouldn't still compile as we can't drop Aptos coins; at the same time, it already shows how much BTC we can get back for 1000 Aptos coins because of
get_amount_out
function.Now let's indeed do a swap and finally deposit the swapped coins on our account:
Everything worked out well; using
swap_exact_coin_for_coin,
we have swapped Aptos coins for BTC.This looks simple, but what if someone decided to front-run us? Let's add some basic slippage checks for the minimum amount of BTC we want to receive (afterwards we can remove
get_amount_out
).All done. In the same way, you can try another function:
router::swap_coin_for_exact_coin
(see Router docs).An important note regarding decentralized AMM securities and user transactions:
- Always use safety checks.
- Never swap tokens without a slippage value provided offline.
Last modified 8mo ago