Performing a swap

Javascript example using viem

Quote Swap

You may first want to get a quote before executing a transaction to see the estimated amount you will receive.

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);
  }
}
Result [ 333222203700616769461576n, 2500000000000000000n ]

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.

Actual Swap

To Perform the actual swap, will require a 4th parameter, minReceiveAmount. This is basically how you set slippage. set to 0 means no slippage.

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.

[ 
1n, 
'0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', 
'0x5FbDB2315678afecb367f032d93F642f64180aa3', 
'0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512', 
1230000000000000000n, 
41164953n, 
20806901801573205n 
]

and the types

Swap(
uint256 indexed txCount,
address indexed user,
address payToken,
address receiveToken,
uint256 payAmount,
uint256 receiveAmount,
uint256 feeAmount
);

https://github.com/Moonshot-meme/swap-example-repo You can find more details in the repo, but you will have to provide your own credentials.

Last updated