简体   繁体   中英

How to Logout of MetaMask account Using web3.js

I am using MetaMask for sending transactions to contract in my DApp. I need help in How to Disconnect MetaMask account from my DApp when the user clicks on logout button .

Front-end: ReactJS

Back-end: Web3js, Solidity (Ethereum)

I don't know if you still have the issue, but inside of an async function you can call clearCachedProvider. The web3Modal variable is cast to my instansiation of web3, eg const web3Modal = new Web3Modal...:

await web3Modal.clearCachedProvider()

Once a wallet is connected it's up to the user to disconnect, you have no control over metamask. You essentially simulate the concept of logging in and logging out by checking if you can get access to their accounts.

const {ethereum} = window;
const accounts = await ethereum.request({method: 'eth_accounts'});
if (accounts && accounts.length > 0) {
    console.log("user is connected");
} else {
    console.log("user not connected");
}

One thing I do is to watch for any account changes:

window.ethereum.on('accountsChanged', async () => {
    // Do something
});

Typically in my app I have an initialise function that checks for metamask, is it installed? is it connected? then I store the state so the app can persist as though the user is logged in even on page refresh. If anything happens such as account change or disconnect the above script runs and I run my initialise script again to reset the state.

// Runs on page load
initialise();

// Runs whenever the user changes account state
window.ethereum.on('accountsChanged', async () => {
    initialise();
});

So, doesn't really answer your question, as far as I know there is now way to reach out and disconnect the user.

let connected = false;
let installed = false;

function isMetaMaskInstalled() {
    return Boolean(window.ethereum && window.ethereum.isMetaMask);
}

async function isMetaMaskConnected() {
    const {ethereum} = window;
    const accounts = await ethereum.request({method: 'eth_accounts'});
    return accounts && accounts.length > 0;
}

async function initialise() {
    connected = await isMetaMaskConnected();
    installed = isMetaMaskInstalled();
}

initialise();

window.ethereum.on('accountsChanged', async () => {
    initialise();
});

I then have my UI reactive to the installed and connected variables.

There is a nice framework https://usedapp.io/ to set up frontend in typescript to interact with smart contracts. You basically wrap your top-level component with its Provider:

import { Mainnet,ChainId} from "@usedapp/core";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <DAppProvider
      config={{
        supportedChains: [ChainId.Kovan, ChainId.Rinkeby],
      }}
    >
      <Component {...pageProps} />
    </DAppProvider>
  );
}

Then write a Header component:

import { useEthers } from "@usedapp/core";

export const Header = () => {
  
  const { account, activateBrowserWallet, deactivate } = useEthers();
  const isConnected = account !== undefined;
  return (
    <div >
      {isConnected ? (
        <Button  onClick={deactivate}>
          Disconnect
        </Button>
      ) : (
        <Button onClick={() => activateBrowserWallet()}>
          Connect
        </Button>
      )}
    </div> );};

Be aware that this is not going to lock metamask it will just disconnect your app from the account.

The user can disconnect MetaMask account using the account disconnect button within the MetaMask itself. Also any page refresh or reload automatically disconnects MetaMask.

as per documentation we can use onboard.walletReset() and it returns undefined and its doesn't disconnect from wallet.from frontend we needs to make the state emp The below is the clear understanding lins from documentations // user wants to log out of session and the wallet state needs to be reset... onboard.walletReset() // this method is synchronous and returns undefined

as attached on EIP-1193, web3.js currently still working for connections and events only, such as disconnect events, network changes and wallet account changes only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM