const { ethers } = require('ethers');
const { Token, CurrencyAmount, Percent, TradeType } = require('@uniswap/sdk-core');
const { Pool, Route, Trade, SwapRouter } = require('@uniswap/v3-sdk');
const IUniswapV3PoolABI = require('@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json').abi;
const Quoter = require('@uniswap/v3-periphery/artifacts/contracts/lens/Quoter.sol/Quoter.json').abi;
const IERC20 = require('@uniswap/v2-periphery/build/IERC20.json');

const SWAP_ROUTER_ADDRESS = '0xE592427A0AEce92De3Edee1F18E0157C05861564';

const WALLET_ADDRESS = '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266';
const WALLET_SECRET = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80';
const INFURA_TEST_URL = 'https://mainnet.infura.io/v3/2d5bc62bb8d748cebfc64763e719cb4f';
const POOL_FACTORY_CONTRACT_ADDRESS = '0x1F98431c8aD98523631AE4a59f267346ea31F984';
const QUOTER_CONTRACT_ADDRESS = '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6';

const provider = new ethers.providers.JsonRpcProvider(INFURA_TEST_URL);
const chainId = 1;

const wallet = new ethers.Wallet(WALLET_SECRET, provider);

const token0 = new Token(chainId, '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 18, 'WETH', 'Wrapped Ether');
const token1 = new Token(chainId, '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984', 18, 'UNI', 'Uniswap Token');

const fee = 3000; // Change the fee tier as required (500 for low, 3000 for medium, and 10000 for high)

async function main() {
  try {
    const poolInfo = await getPoolInfo();

    const pool = new Pool(token0, token1, fee, poolInfo.sqrtPriceX96.toString(), poolInfo.liquidity.toString(), poolInfo.tick);

    const swapRoute = new Route([pool], token0, token1);
    const amountIn = fromReadableAmount('0.001', 18);
    const quotedAmountOut = await getOutputQuote(swapRoute);

    const uncheckedTrade = Trade.createUncheckedTrade({
      route: swapRoute,
      inputAmount: CurrencyAmount.fromRawAmount(token0, amountIn),
      outputAmount: CurrencyAmount.fromRawAmount(token1, BigInt(quotedAmountOut)),
      tradeType: TradeType.EXACT_INPUT,
    });

    await getTokenTransferApproval(token0, SWAP_ROUTER_ADDRESS);

    const options = {
      slippageTolerance: new Percent(50, 10_000), // 50 bips, or 0.50%
      deadline: Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from the current Unix time
      recipient: WALLET_ADDRESS,
    };

    const methodParameters = SwapRouter.swapCallParameters([uncheckedTrade], options);

    const tx = {
      data: methodParameters.calldata,
      to: methodParameters.address,
      value: methodParameters.value,
      from: WALLET_ADDRESS,
      maxFeePerGas: await provider.getGasPrice(),
      maxPriorityFeePerGas: await provider.getGasPrice(),
    };

    const res = await sendTransaction(tx);
    console.log(res);
  } catch (e) {
    console.log(e);
  }
}
main();

async function getPoolInfo() {
  try {
    const currentPoolAddress = Pool.getAddress(token0, token1, fee);

    const poolContract = new ethers.Contract(currentPoolAddress, IUniswapV3PoolABI, provider);

    const [poolToken0, poolToken1, poolFee, tickSpacing, liquidity, slot0] = await Promise.all([
      poolContract.token0(),
      poolContract.token1(),
      poolContract.fee(),
      poolContract.tickSpacing(),
      poolContract.liquidity(),
      poolContract.slot0(),
    ]);

    // Convert amounts to BigInt
    const liquidityBigInt = BigInt(liquidity.toString());
    const sqrtPriceX96BigInt = BigInt(slot0[0].toString());

    return {
      token0: poolToken0,
      token1: poolToken1,
      fee: poolFee,
      tickSpacing,
      liquidity: liquidityBigInt,
      sqrtPriceX96: sqrtPriceX96BigInt,
      tick: slot0[1],
    };
  } catch (e) {
    console.log(e);
  }
}

async function getOutputQuote(amountIn) {
  try {
    const quoterContract = new ethers.Contract(QUOTER_CONTRACT_ADDRESS, Quoter, provider);

    const quotedAmountOut = await quoterContract.callStatic.quoteExactInputSingle(token0.address, token1.address, fee, amountIn, 0);
    return quotedAmountOut;
  } catch (e) {
    console.log(e);
  }
}

function fromReadableAmount(amount, decimals) {
  try {
    const value = ethers.utils.parseUnits(amount, decimals);
    return value.toString();
  } catch (e) {
    console.log(e);
  }
}

async function getTokenTransferApproval(tokenAddress) {
  try {
    const tokenContract = new ethers.Contract(tokenAddress, IERC20.abi, wallet);

    const approvalAmount = ethers.constants.MaxUint256;
    const connectedTokenContract = tokenContract.connect(wallet);
    // Approve the spender (swap router) to spend the tokens on behalf of the user
    const approvalTx = await connectedTokenContract.approve(SWAP_ROUTER_ADDRESS, approvalAmount);

    // Wait for the approval transaction to be mined
    const approvalReceipt = await approvalTx.wait();
    // Check if the approval transaction was successful
    if (approvalReceipt.status !== 1) {
      throw new Error('Token transfer approval failed');
    }

    // Return the approval transaction hash or any other relevant information
    return approvalReceipt.transactionHash;
  } catch (e) {
    console.log(e);
  }
}

async function sendTransaction(tx) {
  try {
    // Sign the transaction with the wallet's private key
    const signedTx = await wallet.signTransaction(tx);

    // Send the signed transaction
    const txResponse = await provider.sendTransaction(signedTx);

    // Wait for the transaction to be mined
    const txReceipt = await txResponse.wait();

    // Check if the transaction was successful
    if (txReceipt.status !== 1) {
      throw new Error('Transaction failed');
    }

    // Return the transaction hash or any other relevant information
    return txReceipt.transactionHash;
  } catch (e) {
    console.log(e); and this error PS C:\Users\lidor\Desktop\Trade Bot> node .
Error: invalid BigNumber value (argument="value", value={"_midPrice":null,"pools":[{"token0":{"chainId":1,"decimals":18,"symbol":"UNI","name":"Uniswap Token","isNative":false,"isToken":true,"address":"0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984"},"token1":{"chainId":1,"decimals":18,"symbol":"WETH","name":"Wrapped Ether","isNative":false,"isToken":true,"address":"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"},"fee":3000,"sqrtRatioX96":[578963018,613543493,353851453,3],"liquidity":[557916161,928492975,260152],"tickCurrent":-59124,"tickDataProvider":{}}],"tokenPath":[{"chainId":1,"decimals":18,"symbol":"WETH","name":"Wrapped Ether","isNative":false,"isToken":true,"address":"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"},{"chainId":1,"decimals":18,"symbol":"UNI","name":"Uniswap Token","isNative":false,"isToken":true,"address":"0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984"}],"input":{"chainId":1,"decimals":18,"symbol":"WETH","name":"Wrapped Ether","isNative":false,"isToken":true,"address":"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"},"output":{"chainId":1,"decimals":18,"symbol":"UNI","name":"Uniswap Token","isNative":false,"isToken":true,"address":"0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984"}}, code=INVALID_ARGUMENT, version=bignumber/5.7.0)
    at Logger.makeError (C:\Users\lidor\Desktop\Trade Bot\node_modules\@ethersproject\logger\lib\index.js:238:21)
    at Logger.throwError (C:\Users\lidor\Desktop\Trade Bot\node_modules\@ethersproject\logger\lib\index.js:247:20)
    at Logger.throwArgumentError (C:\Users\lidor\Desktop\Trade Bot\node_modules\@ethersproject\logger\lib\index.js:250:21)
    at BigNumber.from (C:\Users\lidor\Desktop\Trade Bot\node_modules\@ethersproject\bignumber\lib\bignumber.js:239:23)
    at NumberCoder.encode (C:\Users\lidor\Desktop\Trade Bot\node_modules\@ethersproject\abi\lib\coders\number.js:36:39)
    at C:\Users\lidor\Desktop\Trade Bot\node_modules\@ethersproject\abi\lib\coders\array.js:74:19
    at Array.forEach (<anonymous>)
    at pack (C:\Users\lidor\Desktop\Trade Bot\node_modules\@ethersproject\abi\lib\coders\array.js:60:12)
    at TupleCoder.encode (C:\Users\lidor\Desktop\Trade Bot\node_modules\@ethersproject\abi\lib\coders\tuple.js:71:33)
    at AbiCoder.encode (C:\Users\lidor\Desktop\Trade Bot\node_modules\@ethersproject\abi\lib\abi-coder.js:91:15) {
  reason: 'invalid BigNumber value',
  code: 'INVALID_ARGUMENT',
  argument: 'value',
  value: Route {
    _midPrice: null,
    pools: [ [Pool] ],
    tokenPath: [ [Token], [Token] ],
    input: Token {
      chainId: 1,
      decimals: 18,
      symbol: 'WETH',
      name: 'Wrapped Ether',
      isNative: false,
      isToken: true,
      address: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'
    },
    output: Token {
      chainId: 1,
      decimals: 18,
      symbol: 'UNI',
      name: 'Uniswap Token',
      isNative: false,
      isToken: true,
      address: '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984'
    }
  }
}
TypeError: Cannot convert undefined to a BigInt
    at JSBI.BigInt (C:\Users\lidor\Desktop\Trade Bot\node_modules\jsbi\dist\jsbi-cjs.js:1:805)
    at CurrencyAmount.Fraction (C:\Users\lidor\Desktop\Trade Bot\node_modules\@uniswap\sdk-core\dist\sdk-core.cjs.development.js:74:27)       
    at new CurrencyAmount (C:\Users\lidor\Desktop\Trade Bot\node_modules\@uniswap\sdk-core\dist\sdk-core.cjs.development.js:207:23)
    at Function.fromRawAmount (C:\Users\lidor\Desktop\Trade Bot\node_modules\@uniswap\sdk-core\dist\sdk-core.cjs.development.js:221:12)       
    at main (C:\Users\lidor\Desktop\Trade Bot\index.js:39:36)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  }
}
 this code 