Event Flow
Provider events are used to notify DApp: whether the user switches accounts, whether the network changes, and whether the connection is disconnected. Applications should treat these events as a source of state and update the page upon receipt of the event.
Watch Accounts
accountsChanged will be triggered when the user switches accounts, disconnects authorization or clears the connection in the wallet.
provider.on("accountsChanged", (accounts: string[]) => {
if (accounts.length === 0) {
console.log("The user disconnected the wallet");
} else {
console.log("Current active account:", accounts[0]);
}
});
Listening for chain changes
chainChanged will be triggered when the user switches networks. If the chain ID, contract address or balance information is cached in the page, refresh it here.
provider.on("chainChanged", (chainId: string) => {
console.log("Updated chain ID:", chainId);
window.location.reload();
});
Listen for connections/disconnects
connect means that the Provider is connected to a certain chain, disconnect means that the current connection is unavailable. Please stop sending new RPC requests after disconnecting and prompt the user to reconnect.
provider.on("connect", (connectInfo) => {
console.log("Connection established:", connectInfo.chainId);
});
provider.on("disconnect", (error) => {
console.log("Disconnected reason:", error.message);
});