Last active
November 1, 2021 08:17
-
-
Save sawirricardo/cb8c34c0eec1069585586a423c3b62e9 to your computer and use it in GitHub Desktop.
Lightweb3 JS
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
import { ethers } from "ethers"; | |
import Web3Modal from "web3modal"; | |
// import WalletConnectProvider from "@walletconnect/web3-provider"; | |
import axios from "axios"; | |
class Lightweb3 { | |
constructor( | |
web3ModalOptions = { | |
cacheProvider: true, | |
disableInjectedProvider: false, | |
providerOptions: { | |
// walletconnect: { | |
// package: WalletConnectProvider, | |
// options: { | |
// infuraId: process.env.MIX_WEB3_INFURA_ID, | |
// }, | |
// }, | |
}, | |
} | |
) { | |
this.provider = null; | |
this.reloadAfterFetching = true; | |
this.web3Modal = new Web3Modal(web3ModalOptions); | |
} | |
async onConnect() { | |
try { | |
const provider = await this.web3Modal.connect(); | |
provider.on("accountsChanged", async (accounts) => { | |
console.log("accountsChanged", accounts); | |
web3Modal.clearCachedProvider(); | |
await this.fetchAccount(provider); | |
if (this.reloadAfterFetching) window.location.reload(); | |
}); | |
provider.on("chainChanged", async (chainId) => { | |
console.log("chainChanged", chainId); | |
web3Modal.clearCachedProvider(); | |
await this.fetchAccount(provider); | |
if (this.reloadAfterFetching) window.location.reload(); | |
}); | |
await this.fetchAccount(provider); | |
if (this.reloadAfterFetching) window.location.reload(); | |
} catch (e) { | |
console.log({ e }); | |
} | |
} | |
async fetchAccount(web3Provider) { | |
const provider = new ethers.providers.Web3Provider(web3Provider); | |
const message = await ( | |
await axios.get("/_web3/users/signature") | |
).data.message; | |
await axios.post("/_web3/users", { | |
signature: await provider.getSigner().signMessage(message), | |
address: await provider.getSigner().getAddress(), | |
}); | |
this.provider = provider; | |
} | |
async onDisconnect() { | |
await this.web3Modal.clearCachedProvider(); | |
await axios.delete("/_web3/users/logout"); | |
if (this.reloadAfterFetching) window.location.reload(); | |
} | |
getProvider() { | |
return this.provider; | |
} | |
} | |
window.lightweb3 = new Lightweb3(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment