合约尚未部署到检测到的网络(网络/工件不匹配)



我在确定和连接正确的MetaMask网络时遇到了一些问题。

在Ganache中,我的RPC服务器是127.0.0.17545,网络id是5777。然而,当我试图用这个信息在MetaMask中创建一个自定义RPC时,我得到了以下错误:

The endpoint returned a different chain ID: 1337

这是我的松露。js:

module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
},
develop: {
port: 8545
}
}
};

我希望这将匹配我指定的任何网络id,但控制台显示以下错误:

Contract has not been deployed to a detected network (network/artifact mismatch)

我已经尝试过truffle migrate --reset,但没有成功。我还尝试在truffle-config.js中为testrpc创建一个显式网络,但也没有成功。

任何帮助都将不胜感激!

您看到这个错误是因为您的合同部署到Ganache,但您连接到了另一个网络。

您为加载合约而编写的代码应该在try/catch块内。

内部装载合同逻辑:

export const loadContract = async (name, provider) => {
// Load the contract
// set the provider
let deployedContract = null;
try {
// Get the contract
deployedContract = await _contract.deployed();
} catch {
console.error("You are connected to the wrong network");
}
return deployedContract;
};

在使用loadContract的组件中,在useEffect内部调用它。

useEffect(() => {
// Detect Provider
if (provider) {
// contract should be loaded when provider exists
const contract = await loadContract("ContractName", provider);
rLoaded: true,
// Add More logic
} else {
console.error("Please, install Metamask.");
}
};
}, []);

现在,你需要确保如果你没有连接到Ganache,请禁用该按钮,这样你的应用程序就不会崩溃。为此创建一个状态变量

// You probably already have logic to get account and contract
const canConnectToContract = account && contract;

现在写一个合适的ui:

{!canConnectToContract && (
<h2>Connect to Ganache</h2>
)}
<button
disabled={!canConnectToContract}

>
Donate 1 Ethreum
</button>

最新更新