When building a smart contract that performs swaps through Zealous Swap, itβs essential to ensure your contract is using up-to-date pricing information to avoid slippage or price manipulation. This is especially important in an on-chain environment where transactions can be front-run.
π Using the Router
The Zealous Swap Router provides convenient functions to swap between tokens, including KAS and other tokens. Youβll use different functions depending on whether you are providing the input or output amount.
Before initiating a swap, your contract must:
Own the tokens being sold.
Approve the router to spend those tokens.
Define safety limits like minimum received or maximum paid.
π Quoting a Swap with getAmountsOut
Before executing a swap, it's recommended to preview the expected output using the getAmountsOut function. Zealous Swap enhances this quoting logic by supporting discounted swap rates for eligible users.
To determine if the user is eligible for a discount, query the ZealousSwapDiscountManager contract:
Then, use that flag when calling getAmountsOut:
β οΈ Note: This is only a quote β actual output may vary due to price movement or slippage at the time of execution. Use this result to set amountOutMin safely.
This allows your contract (or frontend) to estimate how much of the output token it will receive, taking into account any discounts that may apply.
π§ͺ Example: Swapping 50 USDT for KAS
1. Transfer USDT to Your Contract
Your smart contract needs to have custody of the tokens before performing a swap.
2. Approve the Router to Spend USDT
Once the contract holds the tokens, you must approve the router.
3. Define the Swap Path and Execute the Swap
Now, perform the swap using the appropriate function. In this example, we are selling an exact amount of USDT for as much KAS as possible.
π‘οΈ Safety Tips
Always use a trusted price source to set amountOutMin or amountInMax in your swaps. This protects against front-running and price manipulation.
For best protection, use external oracles or calculate expected output from off-chain price sources and pass those as parameters to the swap.
Even in highly liquid pools, adding price validation logic increases security and reduces the chance of slippage-related losses.
β Summary
To safely implement a token swap in your smart contract using Zealous Swap:
Transfer tokens to your contract.
Approve the Zealous Swap Router to spend those tokens.
Use the router's swap functions with safety parameters.
This ensures your contracts interact securely and reliably with the Zealous Swap AMM.