I'm trying to execute a swap using Uniswap V2 SDK in a Node.js environment. However, when I run the code below, I receive the following error:
"Warning! Error encountered during contract execution [execution reverted]"

async function createPair() {
  const pairAddress = Pair.getAddress(TOKEN, WETH9[TOKEN.chainId]);

  const pairContract = new ethers.Contract(pairAddress, UniswapV2PoolAbi, provider);

  const reserves = await pairContract['getReserves']();
  const [reserve0, reserve1] = reserves;

  const reserve0Parsed = BigInt(reserve0.toString()).toString();
  const reserve1Parsed = BigInt(reserve1.toString()).toString();

  const tokens = [TOKEN, WETH9[TOKEN.chainId]];
  const [token0, token1] = tokens[0].sortsBefore(tokens[1]) ? tokens : [tokens[1], tokens[0]];

  const pair = new Pair(
    CurrencyAmount.fromRawAmount(token0, reserve0Parsed),
    CurrencyAmount.fromRawAmount(token1, reserve1Parsed)
  );

  return pair;
}

async function swap() {
  const amountIn = ethers.parseEther('0.00001').toString();
  const slippageTolerance = new Percent('50', '10000');
  const to = WALLET_ADDRESS;
  const signer = new ethers.Wallet(WALLET_SECRET);
  const account = signer.connect(provider);
  const command = '0x08';
  const deadline = 2 * 10 ** 10;
  const fromEoa = true;

  const uniswap = new ethers.Contract(
    swapRouterAddress,
    [
      'function execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline) external payable returns (bytes[] memory outputs)',
    ],
    account
  );

  const pair = await createPair();
  const route = new Route([pair], WETH9[TOKEN.chainId], TOKEN);
  const trade = new Trade(
    route,
    CurrencyAmount.fromRawAmount(WETH9[TOKEN.chainId], amountIn),
    TradeType.EXACT_INPUT
  );

  const amountOutMin = trade.minimumAmountOut(slippageTolerance).toExact();

  const amoutOut = ethers.parseEther(amountOutMin);

  const pathData = ethers.solidityPacked(
    ['address', 'address'],
    [WETH9[ChainId.BASE].address, TOKEN.address]
  );

  const v2Calldata = ethers.AbiCoder.defaultAbiCoder().encode(
    ['address', 'uint256', 'uint256', 'bytes', 'bool'],
    [to, amountIn, amoutOut, pathData, fromEoa]
  );

  const tx = await uniswap.execute(command, [v2Calldata], deadline, {
    value: amountIn,
    gasPrice: ethers.parseUnits('0.15', 'gwei'),
    gasLimit: 100000,
    chainId: ChainId.BASE,
    from: WALLET_ADDRESS,
  });

  console.log(`Transaction hash: ${tx.hash}`);
  const receipt = await tx.wait();

  console.log(`Transaction was mined in block ${receipt.blockNumber}`);
}

*/

以下是该代码功能的简要概述:

  1. 导入必要的Unispu V2 SDK组件和ethers.js.
  2. 使用QuickNodehttp端点设置Provider .
  3. 定义钱包地址和秘密.
  4. 创建交换Router地址和TOKEN.
  5. 定义使用Uniswitch V2执行交换的交换函数.
  6. 交换函数内部:
  • a.设置收件箱、滑动容差、收件人地址和签名者.
  • B.创建Unispu合同实例.
  • C.调用DeliverPair()创建Uniswitch对.
  • D.计算交易详细信息并编码呼叫数据.
  • e.使用Unispu的execute()函数执行交换.

我怀疑这个问题可能与我如何编码数据或设置有关 本次交易有人能帮助我理解为什么我会遇到这个错误吗 以及我如何解决它?

Also check some of my transactions: https://basescan.org/tx/0x5a4ccdf8476eac2b41e00927cae6cb5817cff4acfb1c4746244ebd3d22784e9e tenderly analyzer

谢谢!


更新问题: 以下是我当前的代码:

async function swap() {
const swapRouterAddress = '0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad';
const TOKEN = new Token(ChainId.BASE, '0xBC45647eA894030a4E9801Ec03479739FA2485F0', 18);
const amountIn = ethers.parseEther('0.00001').toString();
  const to = WALLET_ADDRESS;
  const signer = new ethers.Wallet(WALLET_SECRET);
  const account = signer.connect(provider);
  const command = '0x0b08';
  const deadline = 2 * 10 ** 10;
  const fromEoa = false;
  const FEE = 500;

  const uniswap = new ethers.Contract(
    swapRouterAddress,
    [
      'function execute(bytes calldata commands, bytes[] calldata inputs) external payable returns (bytes[] memory outputs)',
    ],
    account
  );

  const pathData = ethers.AbiCoder.defaultAbiCoder().encode(
    ['address', 'address'],
    [WETH9[ChainId.BASE].address, TOKEN.address]
  );

  const wrap_calldata = ethers.AbiCoder.defaultAbiCoder().encode(
    ['address', 'uint256'],
    [swapRouterAddress, amountIn]
  );

  const v2Calldata = ethers.AbiCoder.defaultAbiCoder().encode(
    ['address', 'uint256', 'uint256', 'bytes', 'bool'],
    [to, amountIn, 0, pathData, fromEoa]
  );

  const tx = await uniswap.execute(command, [wrap_calldata, v2Calldata], {
    value: amountIn,
    gasPrice: ethers.parseUnits('0.15', 'gwei'),
    gasLimit: 150000,
    chainId: ChainId.BASE,
    from: WALLET_ADDRESS,
  });

  console.log(`Transaction hash: ${tx.hash}`);
  const receipt = await tx.wait();

  console.log(`Transaction was mined in block ${receipt.blockNumber}`);
}

我还发现了路径上的错误,正如马卡在他的回答中提到的那样:

https://basescan.org/tx/0xb661d0eb3fb7d4d6580424ce9c2462cdfa7735f256332c422187506f57a700f7

enter image description here

推荐答案

对代码进行一些调整后,我设法解决了执行错误的问题. 以下是更新后的正常工作的swap()函数:

async function swap() {
  const swapRouterAddress = '0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad';
  const TOKEN = new Token(ChainId.BASE, '0xBC45647eA894030a4E9801Ec03479739FA2485F0', 18);
  const amountIn = ethers.parseEther('0.00001').toString();
  const to = WALLET_ADDRESS;
  const signer = new ethers.Wallet(WALLET_SECRET);
  const account = signer.connect(provider);
  const command = '0x0b08';
  const deadline = 2 * 10 ** 10;
  const fromEoa = false;
  const FEE = 500;

  const uniswap = new ethers.Contract(
    swapRouterAddress,
    [
      'function execute(bytes calldata commands, bytes[] calldata inputs) external payable returns (bytes[] memory outputs)',
    ],
    account
  );

  const pathData = ethers.AbiCoder.defaultAbiCoder().encode(
    ['address', 'address'],
    [WETH9[ChainId.BASE].address, TOKEN.address]
  );

  const wrap_calldata = ethers.AbiCoder.defaultAbiCoder().encode(
    ['address', 'uint256'],
    [swapRouterAddress, amountIn]
  );

  const v2Calldata = ethers.AbiCoder.defaultAbiCoder().encode(
    ['address', 'uint256', 'uint256', 'address[]', 'bool'],
    [to, amountIn, 0, [WETH9[ChainId.BASE].address, TOKEN.address], fromEoa]
  );

  const tx = await uniswap.execute(command, [wrap_calldata, v2Calldata], {
    value: amountIn,
    gasPrice: ethers.parseUnits('0.15', 'gwei'),
    gasLimit: 200000,
    chainId: ChainId.BASE,
    from: WALLET_ADDRESS,
  });

  console.log(`Transaction hash: ${tx.hash}`);
  const receipt = await tx.wait();

  console.log(`Transaction was mined in block ${receipt.blockNumber}`);
}

Javascript相关问答推荐

在JavaScript中对大型级联数组进行切片的最有效方法?

JS、C++和C#给出不同的Base 64 Guid编码结果

如何使用JavaScript用等效的功能性HTML替换标记URL格式?

有Angular 的material .未应用收件箱中的价值变化

将状态向下传递给映射的子元素

如何从网站www.example.com获取表与Cheerio谷歌应用程序脚本

我怎么才能得到Kotlin的密文?

Html文件和客户端存储的相关问题,有没有可能?

如何将未排序的元素追加到数组的末尾?

映射类型定义,其中值对应于键

使用带有HostBinding的Angular 信号来更新样式?

Vaadin定制组件-保持对javascrip变量的访问

令牌JWT未过期

使用Reaction窗体挂钩注册日历组件

有没有办法更改Chart.js 3.x.x中主要刻度的字体?

JAVASCRIPT SWITCH CASE语句:当表达式为';ALL';

TypeORM QueryBuilder限制联接到一条记录

连续添加promise 时,如何在所有promise 都已结算时解除加载覆盖

如何在Web项目中同步语音合成和文本 colored颜色 更改

有角粘桌盒阴影