Skip to content

Instantly share code, notes, and snippets.

@Josh4324
Last active May 10, 2022 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Josh4324/b1e5fa0123269659be0fd238135fbc3a to your computer and use it in GitHub Desktop.
Save Josh4324/b1e5fa0123269659be0fd238135fbc3a to your computer and use it in GitHub Desktop.
Connect Wallet
const connectWallet = async () => {
try {
// When used for the first time, it prompts the user to connect their wallet
const prov = await getProviderOrSigner();
const web3 = new Web3(provider);
const accounts = await web3.eth.getAccounts();
setAddress(accounts[0]);
const bal = await prov.getBalance(accounts[0]);
setBalance(Number(BigNumber.from(bal)) / 10 ** 18);
// track when wallet is connected
localStorage.setItem("wall", "true");
// Subscribe to accounts change
provider.on("accountsChanged", async (accounts) => {
if (accounts[0]) {
const provider = new ethers.providers.JsonRpcProvider(
"https://eth-rinkeby.alchemyapi.io/v2/0mjCfRXMhCmlg6NpHLkztqcvtEbqG9__"
);
const bal = await provider.getBalance(accounts[0]);
setAddress(accounts[0]);
setBalance(Number(BigNumber.from(bal)) / 10 ** 18);
}
});
// Subscribe to chainId change
provider.on("chainChanged", async (chainId) => {
console.log("chain", chainId);
await getProviderOrSigner();
});
// Subscribe to provider connection
provider.on("connect", async (info) => {
console.log("inf", info);
});
// Subscribe to provider disconnection
provider.on("disconnect", (error) => {
console.log("dis", error);
setAddress("");
});
} catch (err) {
console.error(err);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment