我正在使用安全帽框架来测试我的智能合同。我还在开发一个前端应用程序,使用React和NextJS。
目前,我正在本地机器中的分叉中使用多边形测试网,并使用它来部署我的合同。然而,我希望我的前端与分叉测试网中的智能契约进行交互,而不是真正的实时测试网。
为了分叉测试网,我在我的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
允许我的前端与实时测试网上的智能契约进行交互,这不是我想要的。如何更改开发环境以与分叉网络进行交互?
发布于 2022-10-20 18:14:04
当您启动本地硬顶帽节点npx hardhat node
时,您将看到如下消息:Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/
然后,只需将您的钱包或应用程序连接到http://127.0.0.1:8545。
发布于 2022-10-20 19:17:11
用硬帽子叉子意味着
您可以启动一个硬帽子网络的实例,分叉主板。这意味着它将模拟具有与mainnet相同的状态,但它将作为本地开发网络工作。
因此,对于您的配置,您需要启动本地硬顶帽节点(请参阅多么):
$ npx hardhat node
Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/
这个本地URL (RPC )是您需要指向钱包的地方。
MetaMask
对于硬帽子,请确保将chainId: 1337
添加到您的hardhat.config.js
中(参见超链问题):
module.exports = {
solidity: "0.8.17",
networks: {
hardhat: {
chainId: 1337,
forking: {
url: "https://polygon-mumbai.g.alchemy.com/v2/xxxxxxxxxxxxxxxxxxxxxxxxx",
blockNumber: 27270000,
},
},
},
};
然后,在本地运行分叉节点之后,您应该能够通过将本地网络添加到MetaMask钱包中来连接。
请参阅如何添加自定义网络RPC
http://127.0.0.1:8545
1337
MATIC
。备注:
要设置web3js
对象并连接到本地节点(通过WebSocket),您应该能够调用:
const web3 = new Web3(Web3.givenProvider || "ws://localhost:8545")
为了检测Next.js应用程序中的Next.js钱包,我建议使用@元查询/检测-提供者包。
为了与区块链交互,我建议使用ethers.js而不是web3.js
(参见关于虚实StackExchange的讨论)。它还有更好的工具,特别是使用hardhat
。
https://stackoverflow.com/questions/74102327
复制相似问题