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

如何使用Web3.js在Polygon测试网发送交易?需修改代码吗?

在Polygon Mumbai测试网使用Web3.js发送交易的修改方案

你的核心问题是Web3实例未正确关联Polygon Mumbai测试网——MetaMask添加并切换网络只是用户端操作,代码需要确保连接到对应链的节点,或验证当前链是否为目标测试网。以下是具体修改步骤:

1. 验证并切换链ID(关键)

Polygon Mumbai测试网的链ID是80001(十六进制为0x13881),代码中需先检查当前连接的链是否匹配,若不匹配则请求用户切换:

// 定义Mumbai测试网的链配置
const MUMBAI_NETWORK = {
  chainId: '0x13881',
  chainName: 'Polygon Mumbai Testnet',
  rpcUrls: ['https://rpc-mumbai.maticvigil.com/'],
  nativeCurrency: {
    name: 'MATIC',
    symbol: 'MATIC',
    decimals: 18
  }
};

const initPayButton = async () => {
  // 检查当前连接的链ID
  const currentChainId = await window.ethereum.request({ method: 'eth_chainId' });
  
  if (currentChainId !== MUMBAI_NETWORK.chainId) {
    try {
      // 请求用户切换到Mumbai测试网
      await window.ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: MUMBAI_NETWORK.chainId }]
      });
    } catch (switchError) {
      // 若用户未添加该链,自动请求添加
      if (switchError.code === 4902) {
        await window.ethereum.request({
          method: 'wallet_addEthereumChain',
          params: [MUMBAI_NETWORK]
        });
      } else {
        console.error('切换链失败:', switchError);
        $('#status').html('请切换到Polygon Mumbai测试网');
        return;
      }
    }
  }

  // 初始化Web3实例,确保连接到Mumbai节点
  const web3 = new Web3(window.ethereum);
  
  // 发送交易
  try {
    const txResult = await web3.eth.sendTransaction({
      to: paymentAddress,
      value: web3.utils.toWei(amountEth, 'ether')
      // 可选:手动指定gas参数适配Polygon网络(MetaMask通常会自动估算,可省略)
      // gasPrice: web3.utils.toWei('50', 'gwei'),
      // gasLimit: '21000'
    });
    console.log("Payment Successful", txResult.transactionHash);
    $('#status').html("Payment Successful");
  } catch (err) {
    console.log("Payment Failed", err);
    $('#status').html("Payment failed");
  }
};

2. 关键修改点说明

  • 替换回调风格的sendTransaction为async/await,更易处理异步逻辑与错误
  • 增加链ID验证与自动切换逻辑,确保交易发送到目标测试网
  • 显式初始化Web3实例,避免依赖旧注入式Web3的兼容性问题

额外注意事项

  • 确保用户钱包中有足够的Mumbai MATIC测试币(可通过官方水龙头领取)
  • Polygon网络的gas费用以MATIC计价,无需ETH

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:35:20