add change account event listener

This commit is contained in:
RcleydsonR 2022-11-16 01:29:06 -03:00
parent 097837ddee
commit fefebcf91e
3 changed files with 12 additions and 7 deletions

View File

@ -8,7 +8,7 @@ const etherStore = useEtherStore();
const { walletAddress } = storeToRefs(etherStore);
const connectMetaMask = () => {
ethers.getProvider();
ethers.connectProvider();
};
const formatWalletAddress = (): string => {

View File

@ -1,23 +1,28 @@
import { useEtherStore } from "@/store/ether";
import { ethers } from "ethers";
const getProvider = async (): Promise<ethers.providers.Web3Provider | null> => {
const connectProvider = async (): Promise<ethers.providers.Web3Provider | null> => {
const etherStore = useEtherStore();
const window_ = window as any;
const connection = window_.ethereum;
let provider: ethers.providers.Web3Provider | null = null;
if (window_.ethereum) {
provider = new ethers.providers.Web3Provider(window_.ethereum);
if (connection) {
provider = new ethers.providers.Web3Provider(connection);
const walletAddress = await provider.send("eth_requestAccounts", []);
const balance = await provider.getBalance(walletAddress[0]);
etherStore.setProvider(provider);
etherStore.setWalletAddress(walletAddress);
etherStore.setWalletAddress(walletAddress[0]);
etherStore.setBalance(Number(balance));
connection.on('accountsChanged', (accounts: string[]) => {
etherStore.setWalletAddress(accounts[0])
});
} else console.log("Browser não suporta conexão com metamask");
return provider;
};
export default { getProvider };
export default { connectProvider };

View File

@ -2,7 +2,7 @@
import ethers from "../utils/ethers";
const connectMetaMask = () => {
ethers.getProvider().then((web3Provider) => {
ethers.connectProvider().then((web3Provider) => {
console.log(web3Provider);
});
};