Skip to content

Instantly share code, notes, and snippets.

@jm42
Created August 15, 2021 23:22
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 jm42/ba60165ecbda76134e215080f46abff3 to your computer and use it in GitHub Desktop.
Save jm42/ba60165ecbda76134e215080f46abff3 to your computer and use it in GitHub Desktop.
import { ethers } from "ethers"
import { update } from "./store"
const provider = new ethers.providers.Web3Provider(window.ethereum)
provider.on("network", (oldNetwork, newNetwork) => update(state => ({
...state,
chainId: ( newNetwork ?? oldNetwork ).chainId
})))
provider.getNetwork().then(({ chainId }) => update(state => ({
...state,
chainId
})))
window.ethereum.on("accountsChanged", accounts => update(state => ({
...state,
accounts
})))
window.ethereum.on("disconnect", () => update(state => ({
...state,
connected: false,
accounts: []
})))
function connect() {
window.ethereum
.request({ method: "eth_requestAccounts" })
.then(accounts => update(state => ({
...state,
connected: accounts.length > 0,
accounts
})))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment