You may first want to get a quote before executing a transaction to see the estimated amount you will receive.
Copy async function getSwapQuote (
payTokenAddress : string ,
receiveTokenAddress : string ,
payAmount : string
) {
try {
const data = await client .readContract ({
address : contractAddress ,
abi : poolABI ,
functionName : 'quoteSwap' ,
args : [payTokenAddress , receiveTokenAddress , payAmount] ,
});
console .log ( 'data' , data);
} catch (error) {
console .error ( 'Error in quoteSwap:' , error);
}
}
Copy Result [ 333222203700616769461576 n , 2500000000000000000 n ]
The first item of the array response will be the expected amount of the receiveToken (dont forget to format in decimals), the second item is the fee amount in LP tokens.
To Perform the actual swap, will require a 4th parameter, minReceiveAmount. This is basically how you set slippage. set to 0 means no slippage.
Copy async function swap (
payTokenAddress : string ,
receiveTokenAddress : string ,
payAmount : string ,
minReceiveAmount : string
) {
try {
const data = await walletClient .writeContract ({
address : contractAddress ,
abi : poolABI ,
functionName : 'swap' ,
args : [payTokenAddress , receiveTokenAddress , payAmount , minReceiveAmount] ,
account : account ,
});
console .log ( 'swap data' , data);
} catch (error) {
console .error ( 'Error in swap:' , error);
}
}
Sample response.
Copy [
1 n ,
'0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' ,
'0x5FbDB2315678afecb367f032d93F642f64180aa3' ,
'0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512' ,
1230000000000000000 n ,
41164953 n ,
20806901801573205 n
]
Copy Swap (
uint256 indexed txCount ,
address indexed user ,
address payToken ,
address receiveToken ,
uint256 payAmount ,
uint256 receiveAmount ,
uint256 feeAmount
);