Swap
Integrating Swap to website
Integrating the PiperX Aggregator swap functionality to your website makes it easy for you to leverge the liquidity from PiperX without the needs of maintain your own pools. Some example applications including swapping staked $IP tokens to $IP tokens on the LSD website, allow users to buy NFT with stable coins (auto swap stable coins to $IP) on the NFT marketplace.
Steps to Integration
There are three steps in conducting a swap: 1) prepare input, 2) approve tokens, 3) conduct swap. You need to install PiperX sdk and import it to proceed.
0. Prepare Input
You need the following inputs before you can conduct a swap
token1_address: address, // if it is $IP native token, use WIP_ADDRESS
token2_address: address, // if it is $IP native token, use WIP_ADDRESS
amount1: bigint, // amount of token 1 you want to give
amount2Min: bigint, // minimal number of token 2 you want to receive
expire_time: bigint// expiration timestamp for a swap
signer: ethers.Signer. //
Note that, if you are swapping $IP token, you should pass in the PiperX wrapped $IP token address, because the $IP token is not a ERC-20 token. For example, if you are swapping from staked $IP token to $IP token, please use wrapped $IP address WIP_ADDRESS
1. Finding the best swap path
Depends on the swaps that you plan to do, we will use a universal router to find the best swap path, either through standard (V2) or concentrated (V3) path.
const res = await fetch(`https://piperxdb.piperxprotocol.workers.dev/api/swap/swapExactToken?tokenIn=${tokenIn}&tokenOut=${tokenOut}&amount=${amount}&type=exactInput&isAggregator=true`);
const { universalRoutes, num } = await res.json();
2. Approve tokens
Before performing a swap, you must approve the Aggregator contract to spend your input token. The approval is required regardless of which route (V2 or V3) is selected by the Aggregator.
const AGGREGATOR_ADDRESS = "0xf706FCb6C1E580B5070fAB19e8C1b44f095b3640"
export const approveForAggregator = async (
token: string,
amount: bigint,
signer: ethers.Signer
) => {
try {
const tokenContract = new ethers.Contract(token, erc20_abi, signer);
const tx = await tokenContract.approve(AGGREGATOR_ADDRESS, amount);
return await tx.wait();
} catch (e) {
console.error("approveForAggregator failed", e);
throw e;
}
}
3. conduct swap
All swaps are now executed through the Aggregator contract, which handles both V2 and V3 routes automatically. You can use the following function to perform the swap using the prepared universalRoutes. Please export the aggregator_abi from the attached aggregator_abi.ts
file
export const swapViaAggregator = async (
universalRoutes: any[],
signer: ethers.Signer
) => {
try {
const aggregatorContract = new ethers.Contract(AGGREGATOR_ADDRESS, aggregator_abi, signer);
const tx = await aggregatorContract.executeMultiPath(universalRoutes);
return await tx.wait();
} catch (e) {
console.error("swapViaAggregator failed", e);
throw e;
}
}
Last updated