Skip to content

Commit

Permalink
[feature] switching chain ID request
Browse files Browse the repository at this point in the history
  • Loading branch information
steward379 committed Dec 8, 2023
1 parent f8f7974 commit 18551f9
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/pages/mintNFT.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,28 @@ export default function MintPage() {
if ((window as any).ethereum) {
const web3 = new Web3((window as any).ethereum);
try {

const networkId = await web3.eth.net.getId();

// Polygon 主網的 ID 是 137
const polygonNetworkId = 137;

if (networkId !== polygonNetworkId) {
try {
// 請求切換到 Polygon 網路
await (window as any).ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: web3.utils.toHex(polygonNetworkId) }],
});
} catch (switchError) {
// 用戶拒絕切換網路
if (switchError.code === 4001) {
console.log('用戶拒絕切換到 Polygon 鏈');
}
// 未知錯誤
console.error(switchError);
}
}
// await window.ethereum.enable();
// const accounts = await web3.eth.getAccounts();
const accounts = await (window as any).ethereum.request({ method: 'eth_requestAccounts' });
Expand Down

1 comment on commit 18551f9

@vercel
Copy link

@vercel vercel bot commented on 18551f9 Dec 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.