Skip to content

Commit 1e15a58

Browse files
committed
fix chain id issue
1 parent 222b967 commit 1e15a58

1 file changed

Lines changed: 11 additions & 8 deletions

File tree

client/src/lib/web3.ts

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,11 @@ export const getContract = async () => {
2727

2828
const web3 = window.web3!
2929
const accounts = await web3.eth.getAccounts()
30-
const networkId = await web3.eth.net.getId()
31-
const networkIdStr = networkId.toString()
32-
const networkData = deployments.networks[networkIdStr as keyof typeof deployments.networks]
30+
// Use EIP-155 chainId (NOT "network id") to match deployments.json keys.
31+
// Ganache commonly reports network id 5777 while chainId is 1337 (or vice versa).
32+
const chainId = await web3.eth.getChainId()
33+
const chainIdStr = chainId.toString()
34+
const networkData = deployments.networks[chainIdStr as keyof typeof deployments.networks]
3335

3436
if (networkData && networkData.SupplyChain && networkData.SupplyChain.address) {
3537
const contract = new web3.eth.Contract(SupplyChainArtifact.abi as any, networkData.SupplyChain.address)
@@ -38,9 +40,9 @@ export const getContract = async () => {
3840
// Get available networks from deployments
3941
const availableNetworks = Object.keys(deployments.networks).join(', ')
4042
throw new Error(
41-
`Contract not found on network ${networkIdStr}.\n\n` +
43+
`Contract not found on chainId ${chainIdStr}.\n\n` +
4244
`Available networks: ${availableNetworks}\n` +
43-
`Please switch MetaMask to one of these networks or deploy the contract to network ${networkIdStr}.\n\n` +
45+
`Please switch MetaMask to one of these networks or deploy the contract to chainId ${chainIdStr}.\n\n` +
4446
`To deploy: npx hardhat run scripts/deploy.ts --network <network>`
4547
)
4648
}
@@ -51,7 +53,8 @@ export const switchToNetwork = async (chainId: string | number) => {
5153
throw new Error('MetaMask is not installed')
5254
}
5355

54-
const chainIdHex = `0x${Number(chainId).toString(16)}`
56+
const chainIdNum = Number(chainId)
57+
const chainIdHex = `0x${chainIdNum.toString(16)}`
5558

5659
try {
5760
await window.ethereum.request({
@@ -68,13 +71,13 @@ export const switchToNetwork = async (chainId: string | number) => {
6871
params: [
6972
{
7073
chainId: chainIdHex,
71-
chainName: chainId === '1337' || chainId === '5777' ? 'Ganache Local' : 'Hardhat Local',
74+
chainName: chainIdNum === 1337 || chainIdNum === 5777 ? 'Ganache Local' : 'Hardhat Local',
7275
nativeCurrency: {
7376
name: 'ETH',
7477
symbol: 'ETH',
7578
decimals: 18,
7679
},
77-
rpcUrls: chainId === '1337' || chainId === '5777'
80+
rpcUrls: chainIdNum === 1337 || chainIdNum === 5777
7881
? ['http://127.0.0.1:7545']
7982
: ['http://127.0.0.1:8545'],
8083
},

0 commit comments

Comments
 (0)