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 here is a record of it!

Problem Description#

When a Dapp integrates with the MetaMask wallet, the lack of a disconnect API from MetaMask prevents the wallet from disconnecting from the current website when the user logs out. This results in the inability to display the account selection interface the next time the user logs in.
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, the account selection interface is invoked by calling wallet_requestPermissions, and then the user's selected account is obtained by calling eth_requestAccounts.

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 considerations are behind this? If it is 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.