1

I'm trying to run a script in order to execute a Uniswap swap. When the transaction is submitted, MetaMask doesn't allow me to confirm the transaction (the confirm button is greyed out). On MetaMask's website it says that the reason for this greyed out confirm button is insufficient funds, however, I have more than enough ETH to cover the transaction + gas fees.

The script looks as follows:

import Web3 from 'web3';
import uniswapABI from './uniswapABI.json';

const web3 = new Web3([Goerli Infura URL]);
// const web3 = new Web3(window.web3.currentProvider);
const uniswapContract = new web3.eth.Contract(uniswapABI, '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D');

const fromToken = '0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6'; // WETH
const toToken = '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984'; // UNI
const amountIn = web3.utils.toWei('0.01', 'ether');
const amountOutMin = web3.utils.toWei('0', 'ether');
const deadline = Math.floor(Date.now() / 1000) + 60 * 3; // 3 minutes from now

if (typeof window.ethereum !== 'undefined') {
  console.log('MetaMask is installed!');
}

ethereum.request({ method: 'eth_requestAccounts' });

async function executeExactSwap() {
    console.log("executeExactSwap");
    const accounts = await ethereum.request({ method: 'eth_requestAccounts' });

    console.log("accounts", accounts);

    const account = accounts[0];

    console.log("account", account);

    const uniswapData = uniswapContract.methods.swapExactTokensForTokens(
        amountIn,
        amountOutMin,
        [fromToken, toToken],
        account,
        deadline
    ).encodeABI();


    const transactionParameters = {
        nonce: '0x00', // ignored by MetaMask
        value: '0x00', // Only required to send ether to the recipient from the initiating external account.
        chainId: '0x5', // Used to prevent transaction reuse across blockchains. Auto-filled by MetaMask.
        from: account,
        to: uniswapContract.options.address,
        data: uniswapData,
        gasPrice: '0x09184e72a000', // customizable by user during MetaMask confirmation
        gas: '0x2710', // customizable by user during MetaMask confirmation
        value: '0x00', // Only required to send ether to the recipient from the initiating external account
    };

    console.log("eth_sendTransaction");

    const txHash = await ethereum.request({
        method: 'eth_sendTransaction',
        params: [transactionParameters],
    });

    console.log("sendTransaction complete", txHash);
}


console.log("function call");
executeExactSwap();
1
  • Did you approve the uniswap contract to access the tokens?
    – Ismael
    Mar 26, 2023 at 20:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.