Last active
May 10, 2022 13:47
-
-
Save Josh4324/b1e5fa0123269659be0fd238135fbc3a to your computer and use it in GitHub Desktop.
Connect Wallet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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