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

如何让Next.js前端与Hardhat本地分叉Polygon测试网交互?

问题描述

我正在使用Hardhat框架测试智能合约,同时采用React和NextJS开发前端应用。目前我在本地机器上forking(分叉)Polygon测试网,并将合约部署到该分叉网络,但希望前端能与该分叉测试网而非真实测试网的智能合约交互。

我的hardhat.config.js中有如下配置:

networks: {
  hardhat: {
    forking: {
      url: "https://polygon-mumbai.g.alchemy.com/v2/xxxxxxxxxxxxxxxxxxxxxxxxx",
      blockNumber: 27270000
    }
  }
},

前端的web3配置如下:

if (typeof window !== "undefined" && typeof window.ethereum !== "undefined") {
  // We are in the browser and metamask is running.
  window.ethereum.request({ method: "eth_requestAccounts" });
  web3 = new Web3(window.ethereum);
} else {
  // We are on the server *OR* the user is not running metamask
  const provider = new Web3.providers.HttpProvider(
    "https://polygon-mumbai.g.alchemy.com/v2/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  );
  web3 = new Web3(provider);
}

我已成功将合约部署到分叉网络,但当前运行npm next dev时,前端仍与真实测试网的智能合约交互,请问如何调整开发环境以实现需求?


解决方案

要让前端连接到本地Hardhat分叉网络,需从Provider配置、MetaMask设置、合约地址确认三方面调整:

1. 修改前端Web3 Provider配置

当前前端无论浏览器还是服务端环境,都指向了真实Mumbai测试网,需要将服务端/无MetaMask场景的Provider切换到本地Hardhat节点,同时确保浏览器环境的MetaMask指向本地网络:

if (typeof window !== "undefined" && typeof window.ethereum !== "undefined") {
  window.ethereum.request({ method: "eth_requestAccounts" });
  web3 = new Web3(window.ethereum);
} else {
  // 替换为本地Hardhat节点默认地址
  const provider = new Web3.providers.HttpProvider(
    "http://127.0.0.1:8545"
  );
  web3 = new Web3(provider);
}

2. 配置MetaMask连接本地分叉网络

Hardhat本地节点默认运行在http://127.0.0.1:8545,链ID为31337,需要在MetaMask中手动添加该网络:

  • 网络名称:自定义(比如Hardhat Local Fork)
  • RPC URL:http://127.0.0.1:8545
  • 链ID:31337
  • 货币符号:ETH(或MATIC,按需自定义)
  • 区块浏览器URL:留空

添加完成后,切换MetaMask到该网络,浏览器环境下的前端就会通过MetaMask连接到本地分叉网络。

3. 确认前端使用的合约地址

部署到本地分叉网络后,要确保前端调用的是本地分叉网络上的合约地址,而非真实Mumbai测试网的地址。可以通过以下方式传递地址:

  • 在部署脚本执行后复制输出的合约地址,手动更新前端代码
  • 将地址存入.env.local文件(比如NEXT_PUBLIC_CONTRACT_ADDRESS=0x...),前端通过process.env.NEXT_PUBLIC_CONTRACT_ADDRESS读取

4. 启动本地Hardhat分叉节点

确保本地分叉节点处于运行状态,执行命令:

npx hardhat node

该命令会启动节点并加载你配置的Mumbai分叉数据,同时输出测试账户的私钥和地址,可导入这些账户到MetaMask进行测试。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:50:25