112 lines
2.7 KiB
JavaScript
112 lines
2.7 KiB
JavaScript
import { simulateContract, writeContract, waitForTransactionReceipt } from "@wagmi/core";
|
|
import toast from "react-hot-toast";
|
|
|
|
import { UNISWAP_V2_ROUTER } from "../../constants/addresses";
|
|
import { abi as RouterAbi } from "../../abi/UniswapV2Router.json";
|
|
import { getTokenAddress } from "../helpers";
|
|
|
|
import { config } from "../../config";
|
|
|
|
export const swapExactTokensForTokens = async (
|
|
chainId,
|
|
amountDesired,
|
|
amountMin,
|
|
pathRaw,
|
|
destination,
|
|
deadline
|
|
) => {
|
|
|
|
const path = pathRaw.map(tokenName => getTokenAddress(chainId, tokenName));
|
|
const args = [
|
|
amountDesired,
|
|
amountMin,
|
|
path,
|
|
destination,
|
|
deadline
|
|
];
|
|
|
|
const messages = {
|
|
replacedMsg: "Swap transaction was replaced. Wait for inclusion please.",
|
|
successMsg: "Swap executed successfully! Wait for balances update.",
|
|
errorMsg: "Swap tokens failed. Check logs for error detalization.",
|
|
};
|
|
|
|
await executeOnChainTransaction(
|
|
chainId,
|
|
"swapExactTokensForTokens",
|
|
args,
|
|
destination,
|
|
messages
|
|
);
|
|
}
|
|
|
|
export const addLiquidity = async (
|
|
chainId,
|
|
tokenA,
|
|
tokenB,
|
|
amountADesired,
|
|
amountBDesired,
|
|
amountAMin,
|
|
amountBMin,
|
|
to,
|
|
deadline,
|
|
) => {
|
|
const token1 = getTokenAddress(chainId, tokenA);
|
|
const token2 = getTokenAddress(chainId, tokenB);
|
|
|
|
const args = [
|
|
token1,
|
|
token2,
|
|
amountADesired,
|
|
amountBDesired,
|
|
amountAMin,
|
|
amountBMin,
|
|
to,
|
|
deadline
|
|
];
|
|
const messages = {
|
|
replacedMsg: "Add liquidity transaction was replaced. Wait for inclusion please.",
|
|
successMsg: "Liquidity added successfully! You should get LP tokens to your wallet.",
|
|
errorMsg: "Adding liquidity failed. Check logs for error detalization.",
|
|
};
|
|
|
|
await executeOnChainTransaction(
|
|
chainId,
|
|
"addLiquidity",
|
|
args,
|
|
to,
|
|
messages
|
|
);
|
|
}
|
|
|
|
const executeOnChainTransaction = async (
|
|
chainId,
|
|
functionName,
|
|
args,
|
|
account,
|
|
messages
|
|
) => {
|
|
try {
|
|
const { request } = await simulateContract(config, {
|
|
abi: RouterAbi,
|
|
address: UNISWAP_V2_ROUTER[chainId],
|
|
functionName,
|
|
args,
|
|
account,
|
|
chainId
|
|
});
|
|
|
|
const txHash = await writeContract(config, request);
|
|
await waitForTransactionReceipt(config, {
|
|
hash: txHash,
|
|
onReplaced: () => toast(messages.replacedMsg),
|
|
chainId
|
|
});
|
|
|
|
toast.success(messages.successMsg);
|
|
} catch (err) {
|
|
console.error(err);
|
|
toast.error(messages.errorMsg)
|
|
}
|
|
}
|