I am trying to create a simple DAI/ETH swapper which lets me swap some DAI for ETH using Uniswap Router V2. I am creating it using React and uniswapSDK. So far, I have managed to connect to my Metamask wallet, get the ABI for the Uniswap contract so I can invoke the method.
However, I am finding it difficult to understand how do I approve this method before calling it? I understand that sending a transaction over the chain needs to first signed, then be called. I am not sure 'how' to approve it? This is my code till now for swapping
export const makeSwap = async (
contract: any,
account: any,
library: any,
amount: any
) => {
const DAI: Token = await Fetcher.fetchTokenData(chainId, DAItokenAddress);
const pair: Pair = await Fetcher.fetchPairData(DAI, WETH[chainId]);
const route: Route = new Route([pair], DAI);
const trade = new Trade(
route,
new TokenAmount(DAI, library.utils.toWei(amount)),
TradeType.EXACT_INPUT
);
const slippageTolerance = new Percent("50", "10000"); //0.5%
const amountOutMin = ethers.BigNumber.from(
trade.minimumAmountOut(slippageTolerance).raw.toString()
).toHexString();
const path = [DAI.address, WETH[chainId].address];
const to = account;
const deadline = Math.floor(Date.now() / 1000) + 60 * 1;
const value = ethers.BigNumber.from(
trade.inputAmount.raw.toString()
).toHexString();
await contract.methods.approve(value, account);
const tx = await contract.methods
.swapExactTokensForETH(value, amountOutMin, path, to, deadline)
.call();
//Fails above this line
console.log(`Transaction hash: ${tx.hash}`);
const receipt = await tx.wait();
console.log(`Transaction was mined in block ${receipt.blockNumber}`);
};
Thank you for your help!