Hexi

Hexi

Record my life

Programmatically disconnect MetaMask / Wagmi shimDisconnect implementation

Recently, I spent some time researching the issue of MetaMask not being able to switch accounts when connected. Previously, I thought it was not supported because the official documentation did not provide the corresponding API. Later, I observed that Wagmi experimentally supported programmatically disconnect through the shimDisconnect feature. I studied its source code a bit, and I'll record it here!

Problem Description#

When a Dapp integrates with the MetaMask wallet, when the Dapp logs out, MetaMask does not provide a disconnect API, which prevents the wallet from disconnecting from the current website. The next time the user logs in, the account selection interface cannot pop up. See details in the issue: https://github.com/MetaMask/metamask-extension/issues/8990

Solution#

Refer to the replies in the issue and the implementation of the shimdisconnect feature in Wagmi: https://github.com/wevm/wagmi/pull/616/files

The core code is as follows: When logging in, call wallet_requestPermissions to invoke the account selection interface, and then call eth_requestAccounts to get the user's selected account.

const accounts = await window.ethereum.request({
    method: "wallet_requestPermissions",
    params: [{
        eth_accounts: {}
    }]
}).then(() => ethereum.request({
    method: 'eth_requestAccounts'
}))

const account = accounts[0]

Thoughts#

  • Although MetaMask and OKX wallets can meet the requirements through this method, this may be a last resort.

  • Currently, most Web3 wallets do not support programmatically disconnect. I wonder what the consideration behind this is? If it's a security issue, it should be reasonable for Dapps to control their connection status with the wallet, without any security concerns.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.