Download

arrow_down

Build

arrow_down

More

arrow_down
activityactivityactivityactivity
  • themelight
  • languageIcon

  • menu
Skip to Content
En Docs
Reference
Dapp Mainnet and Token Management

Mainnet and Token Management

Tracking the user’s network chain ID is very important, as all RPC requests will be submitted to the currently connected network. Use the eth_chainId RPC method to detect the chain ID of the user’s current network.

Using the ETH chain as an example, listen for the chainChanged provider event to detect when the user changes the network:

        
const chainId = await provider.request({ method: "eth_chainId" }); provider.on("chainChanged", handleChainChanged); function handleChainChanged(chainId) { // We recommend reloading the page, unless you must do otherwise. window.location.reload(); }

The typical approach for determining supported mainnet support:

  1. Call the wallet method to switch to the target chain.
  2. If the switch fails, it indicates the chain does not exist.

For example, the code for switching to the ETH chain would be:

        
try { await provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId: "0xf00" }], }); } catch (switchError) { // This error code indicates that the chain has not been added to MetaMask. if (switchError.code === 4902) { try { await provider.request({ method: "wallet_addEthereumChain", params: [ { chainId: "0xf00", chainName: "...", rpcUrls: ["https://..."] /* ... */, }, ], }); } catch (addError) { // Handle "add" error. } } // Handle other "switch" errors. }

Adding a Mainnet

        
// Mainnet information to be added let chainInfo = { chainId: "0xaa36a7", // A 0x-prefixed hexadecimal string chainName: "sepolia", nativeCurrency: "ETH", iconUrls: "xxx", rpcUrls: ["https://sepolia.drpc.org"], blockExplorerUrls: ["https://sepolia.drpc.org"], nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18, }, }; await provider.request({ method: "wallet_addEthereumChain", params: [chainInfo], });

What are tokens?

Tokens are special fee carriers on smart contract platforms (such as Ethereum), where users can create, issue, and manage tokens (derivatives of the main blockchain).

Adding Tokens

        
const customTokenInfo = { type: "ERC20", options: { address: "0xd00981105....fe7e037d935b513", symbol: "BWB", decimals: 18, image: "http://...", }, }; const added = await provider.request({ method: "wallet_watchAsset", params: customTokenInfo, });
Last updated on