I want to programmatically swap using Uniswap Universal Router, but the transaction always gets reverted
Here is my code:
const ethers = require("ethers");
const { abi: V3SwapRouterABI } = require('@uniswap/v3-periphery/artifacts/contracts/SwapRouter.sol/SwapRouter.json')
const ROUTER_ADDRESS = "0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad"
const WETH_ADDRESS = "0xf531B8F309Be94191af87605CfBf600D71C2cFe0"
const UNI_ADDRESS = "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984"
privateKey = ""
const provider = new ethers.JsonRpcProvider("https://ethereum-sepolia.rpc.subquery.network/public")
const signer = new ethers.Wallet(privateKey, provider)
const router = new ethers.Contract(ROUTER_ADDRESS, V3SwapRouterABI, signer)
async function main() {
const inputAmount = ethers.parseEther("0.0001")
const params = {
tokenIn: WETH_ADDRESS,
tokenOut: UNI_ADDRESS,
fee: 3000,
recipient: signer.address,
deadline: Math.floor(Date.now() / 1000) + 60 * 10,
amountIn: ethers.parseEther("0.00001"),
amountOutMinimum: 0,
sqrtPriceLimitX96: 0,
};
const data = router.interface.encodeFunctionData(
"exactInputSingle",
[params]);
const txArgs = {
to: ROUTER_ADDRESS,
value: inputAmount,
data: data,
gasLimit: "343433",
}
const tx = await signer.sendTransaction(txArgs);
const reciept = await tx.wait();
console.log(reciept);
}
main();
Here is the transaction that got reverted: Sepolia Etherscan
What is the problem here, are the parameters not correctly set up?
I have also double-checked my ETH and WETH balance, there are enough to make the swap!
Best Answer
As Ismael mentioned in the comments, you're not using the correct contract.
You're using the UniversalRouter contract instead of the SwapRouter.
Since, the SwapRouter is not available on the Sepolia testnet, you can use SwapRouter02 instead. All the parameters would remain the same, you just need to remove the
deadline
parameter in case of SwapRouter02.Also, the
WETH_ADDRESS
should be0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14
, as specified in the Uniswap Docs:You can find all the available deployed addresses on this page of Uniswap Docs.
Here's the revised code with the changes:
And, here's the successful transaction for the same.
Since
swapExactTokensToETH
is not available in SwapRouter02, so here's what you can do in order to swap back (from UNI to ETH):Call the approve function of UNI token contract by passing in the amount of UNI tokens from your balance that you want to swap back.
Then, execute the exactInputSingle function of SwapRouter02 by passing
tokenIn
as UNI address,tokenOut
as WETH address,amountIn
as UNI amount andvalue
as0
.Finally, call the withdraw function of the WETH token contract, passing in the amount of WETH tokens that you want to convert to ETH.