You need to enable JavaScript to run this app. Node.js中订阅UniswapV2 Factory的PairCreated事件报错如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中订阅UniswapV2 Factory的PairCreated事件报错如何解决?

问题原因

你遇到的错误由两个独立问题导致:

1. 地址带多余空白字符

看报错信息里明确给出的异常参数值:value="0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ",这个地址末尾多了一个空格。
你代码中addresses对象里的factory、router两个地址末尾都带有多余的空格,ethers库接收到不符合标准长度(42位)的地址参数时,会默认尝试将其作为ENS域名解析,显然带空格的字符串不是合法ENS域名,就触发了该解析错误。

2. 异步回调未做异常捕获

你监听PairCreated事件用了async异步回调,但没有添加异常捕获逻辑,异步代码运行中抛出的错误没有被处理,就会触发UnhandledPromiseRejectionWarning警告。


修复方案

  • 清理地址字符串前后的所有空白字符,确保每个地址都是长度为42位的合法十六进制字符串
  • 给异步回调添加try/catch块捕获异常

修复后的代码示例:

const Web3 = require('web3');
const ethers = require('ethers');

const INFURA_BASE_URL = 'https://mainnet.infura.io/v3/';
const INFURA_API_KEY = 'REPLACE';
web3 = new Web3(new Web3.providers.HttpProvider(INFURA_BASE_URL + INFURA_API_KEY));

const privateKey = "REPLACE";
const account = web3.eth.accounts.privateKeyToAccount(privateKey)
console.log(account.address)

const provider = new ethers.providers.JsonRpcProvider('https://mainnet.infura.io/v3/REPLACE');
const wallet = new ethers.Wallet(privateKey);
const account2 = wallet.connect(provider);

const addresses = {
    WETH: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
    // 去掉地址末尾的空格
    factory: '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f',
    // 去掉地址末尾的空格
    router: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
    recipient: account.address
};

const factory = new ethers.Contract(
    addresses.factory,
    [
        'event PairCreated(address indexed token0, address indexed token1, address pair, uint)',
        'function getPair(address tokenA, address tokenB) external view returns (address pair)'
    ],
    account2
);

// 添加try/catch捕获异步异常
factory.on('PairCreated', async (token0, token1, pairAddress) => {
    try {
        // 你的业务逻辑写在这里
    } catch (err) {
        console.error('事件处理出错:', err)
    }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 10:03:04