You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为合约Swap事件回调函数的参数指定Swap类型

问题原因

ethers合约的Swap事件回调是按顺序逐个传递参数,而非将所有参数打包为单个对象传入,所以你直接用单个swap: Swap参数的写法,会和实际的参数列表签名不匹配,导致类型绑定失败。

解决方法

方法1:为每个参数单独指定类型

直接对应Swap类型的字段,给回调的每个参数添加类型注解:

poolContract.on(
  "Swap",
  (
    sender: string,
    recipient: string,
    amount0: BigNumber,
    amount1: BigNumber,
    sqrtPriceX96: BigNumber,
    liquidity: BigNumber,
    tick: number
  ) => {
    console.log({
      sender,
      recipient,
      amount0: ethers.utils.formatUnits(amount0, 6),
      amount1: ethers.utils.formatUnits(amount1, 18),
      sqrtPriceX96,
      liquidity,
      tick,
    });
  }
);

方法2:解构参数并绑定类型

将参数收集为数组后,通过类型断言关联Swap类型的字段,再解构使用:

poolContract.on(
  "Swap",
  (...args) => {
    const [sender, recipient, amount0, amount1, sqrtPriceX96, liquidity, tick] = args as [
      Swap["sender"],
      Swap["recipient"],
      Swap["amount0"],
      Swap["amount1"],
      Swap["sqrtPriceX96"],
      Swap["liquidity"],
      Swap["tick"]
    ];
    
    console.log({
      sender,
      recipient,
      amount0: ethers.utils.formatUnits(amount0, 6),
      amount1: ethers.utils.formatUnits(amount1, 18),
      sqrtPriceX96,
      liquidity,
      tick,
    });
  }
);

方法3:定义参数元组类型复用

先基于Swap类型生成对应的参数元组,再直接用于回调函数:

// 基于Swap类型生成参数元组
export type SwapParams = [
  Swap["sender"],
  Swap["recipient"],
  Swap["amount0"],
  Swap["amount1"],
  Swap["sqrtPriceX96"],
  Swap["liquidity"],
  Swap["tick"]
];

// 使用元组类型
poolContract.on(
  "Swap",
  (...args: SwapParams) => {
    const [sender, recipient, amount0, amount1, sqrtPriceX96, liquidity, tick] = args;
    console.log({
      sender,
      recipient,
      amount0: ethers.utils.formatUnits(amount0, 6),
      amount1: ethers.utils.formatUnits(amount1, 18),
      sqrtPriceX96,
      liquidity,
      tick,
    });
  }
);

内容的提问来源于stack exchange,提问作者Kendrick Lamar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 14:30:53