Hooks for interacting with Uniswap V2 protocol on Avalanche.
BuilderKit provides hooks for interacting with Uniswap V2-compatible DEXs on Avalanche, such as Trader Joe.
The useUniswapV2
hook provides functions for swapping tokens and managing liquidity using Uniswap V2 protocol.
import { useUniswapV2 } from '@avalabs/builderkit';
const {
getPair,
getReserves,
getAmountOut,
getQuote,
getMinAmountOut,
getSwapTransaction
} = useUniswapV2();
// Get pair address
const pairAddress = await getPair(
43114, // Chain ID
tokenA, // Token A info
tokenB // Token B info
);
// Get pair reserves
const reserves = await getReserves(
43114, // Chain ID
pairAddress // Pair address
);
// Calculate output amount
const amountOut = getAmountOut(
reserves, // [reserve0, reserve1]
new BigNumber("1.0"), // Amount in
tokenA, // Token in info
tokenB // Token out info
);
// Get swap transaction data
const swapData = await getSwapTransaction(
43114, // Chain ID
tokenA, // Token in info
tokenB, // Token out info
new BigNumber("1.0"), // Amount in
amountOut, // Minimum amount out
"0x1234..." // Recipient
);
getPair(chain_id: number, token_in: any, token_out: any)
: Get pair contract address
getReserves(chain_id: number, pair: string)
: Get pair reserves
getAmountOut(reserves: [BigNumber, BigNumber], amount_in: BigNumber, token_in: any, token_out: any, fee?: number)
: Calculate output amount
getQuote(chain_id: number, token_in: any, token_out: any, amount_in: BigNumber)
: Get quote for swap
getMinAmountOut(amount: BigNumber, slippage?: number)
: Calculate minimum output with slippage
getSwapTransaction(chain_id: number, token_in: any, token_out: any, amount_in: BigNumber, amount_out: BigNumber, receiver: string)
: Generate swap transaction
function SwapInterface() {
const { getQuote, getMinAmountOut, getSwapTransaction } = useUniswapV2();
const [amountIn, setAmountIn] = useState("");
const [amountOut, setAmountOut] = useState("");
// Calculate output amount when input changes
useEffect(() => {
const calculateOutput = async () => {
if (!amountIn) return;
const output = await getQuote(
43114,
tokenA,
tokenB,
new BigNumber(amountIn)
);
setAmountOut(output.toString());
};
calculateOutput();
}, [amountIn]);
// Execute swap
const handleSwap = async () => {
const minOut = getMinAmountOut(new BigNumber(amountOut), 0.5); // 0.5% slippage
const data = await getSwapTransaction(
43114,
tokenA,
tokenB,
new BigNumber(amountIn),
minOut,
account
);
return (
<TransactionButton
chain_id={43114}
title="Swap Tokens"
description="Swapping tokens on Trader Joe"
data={data}
/>
);
};
return (
<div>
<input
type="text"
value={amountIn}
onChange={(e) => setAmountIn(e.target.value)}
placeholder="Amount in"
/>
<div>Output: {amountOut}</div>
{handleSwap()}
</div>
);
}