Fixing provider state and wallet change listener, formatting balance
Co-authored-by: RcleydsonR <rafael.cleydson@gmail.com>
This commit is contained in:
@@ -1,29 +1,44 @@
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
import { ethers } from "ethers";
|
||||
|
||||
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;
|
||||
const updateWalletStatus = async (walletAddress: string) => {
|
||||
const etherStore = useEtherStore();
|
||||
const window_ = window as any;
|
||||
const connection = window_.ethereum;
|
||||
|
||||
if (connection) {
|
||||
provider = new ethers.providers.Web3Provider(connection);
|
||||
if (!connection) return;
|
||||
|
||||
const walletAddress = await provider.send("eth_requestAccounts", []);
|
||||
const balance = await provider.getBalance(walletAddress[0]);
|
||||
const provider = new ethers.providers.Web3Provider(connection);
|
||||
const balance = await provider.getBalance(walletAddress);
|
||||
|
||||
etherStore.setProvider(provider);
|
||||
etherStore.setWalletAddress(walletAddress[0]);
|
||||
etherStore.setBalance(Number(balance));
|
||||
etherStore.setBalance(String(balance));
|
||||
etherStore.setWalletAddress(walletAddress);
|
||||
};
|
||||
|
||||
connection.on("accountsChanged", (accounts: string[]) => {
|
||||
etherStore.setWalletAddress(accounts[0]);
|
||||
});
|
||||
} else console.log("Browser não suporta conexão com metamask");
|
||||
const connectProvider = async () => {
|
||||
const etherStore = useEtherStore();
|
||||
const window_ = window as any;
|
||||
const connection = window_.ethereum;
|
||||
let provider: ethers.providers.Web3Provider | null = null;
|
||||
|
||||
return provider;
|
||||
};
|
||||
if (connection) {
|
||||
provider = new ethers.providers.Web3Provider(connection);
|
||||
|
||||
export default { connectProvider };
|
||||
const walletAddress = await provider.send("eth_requestAccounts", []);
|
||||
const balance = await provider.getBalance(walletAddress[0]);
|
||||
|
||||
etherStore.setWalletAddress(walletAddress[0]);
|
||||
etherStore.setBalance(String(balance));
|
||||
|
||||
connection.on("accountsChanged", (accounts: string[]) => {
|
||||
updateWalletStatus(accounts[0]);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const formatEther = (balance: string) => {
|
||||
const formatted = ethers.utils.formatEther(balance);
|
||||
return formatted;
|
||||
};
|
||||
|
||||
export default { connectProvider, formatEther };
|
||||
|
||||
Reference in New Issue
Block a user