Is there any solution to prompt users to change chain?
I would like to understand how to create a prompt with metamask for the user when connected with the wrong chain on my site.
exactly like pancakeswap does, if I’m on the ETH chain and connect to their site, a metamask prompt will ask me to switch to the BSC network.
Do you want to know how to do it with React or vanilla JS?
For React, you would do this -
import { useChain } from "react-moralis";
function Chains() {
const { switchNetwork, chainId, chain, account } = useChain();
return (
<>
<button onClick={() => switchNetwork("0x1")}>Switch to Ethereum</button>
<p>Current chainId: {chainId}</p>
</>
);
}
Vanilla –
// Check if this is the chain ID you want.
const chainId = await Moralis.getChainId();
console.log(chainId); // 56
// Then switch accordingly
const chainId = "0x1"; //Ethereum Mainnet
const chainIdHex = await Moralis.switchNetwork(chainId);
Superb! Just a few lines of code can do it.Thanks
One more question, is that any way to disconnect the site from the metamask?
Exactly like when user click logout button,metamask will disconnect from the website and click login button will prompt the singing message
Yes, the logout functionality is available as well.
await Moralis.User.logOut();
I have already included the following code in my logout function as shown below
async function logOut() {
await Moralis.User.logOut();
console.log(“logged out”);
}
But there seem to be a problem as when I call a write function from a smart contract, even when I have triggered the logout function and got the “logged out” string displayed in my console, the write function would still be able to proceed and prompt my metamask to sign the transaction. Isn’t await Moralis.User.logout();
supposed to forget my previous connection to metamask and prompt me to login again before asking me to sign the transaction.
Hey @testnet123
It can make you a bit confused, but the react-moralis detects active web3 wallet even if your user logged out and takes wallet info from it.
I guess we should remove this feature in the coming versions
It was added as a feature, for example you can get info about active network in the wallet even without connecting the user wallet. But we can see now that this feature really confuses some devs
I see… Then how will it be possible for me to actually log out from metamask through Moralis so that it does not detect the active web3 wallet and take wallet info from it when I’ve logged out? Is it possible currently?