Skip to content

Instantly share code, notes, and snippets.

@ixtgorilla
Created May 6, 2019 10:12
Show Gist options
  • Save ixtgorilla/02b9b620972e3d6ae9f0d525aa67ec55 to your computer and use it in GitHub Desktop.
Save ixtgorilla/02b9b620972e3d6ae9f0d525aa67ec55 to your computer and use it in GitHub Desktop.
Web3Singletone template
import Web3 from 'web3'
import Window from './window'
// Singletone Class
class Web3Factory {
public web3: Web3
private static _instance: Web3Factory
// Private Constructor
private constructor(window: Window) {
if (window.ethereum) {
this.getPermissionFromMetabask(window.ethereum)
this.web3 = new Web3(window.ethereum)
} else {
this.web3 = this.createNewHttpProvider()
}
}
public static get instance(): Web3Factory {
if (!this._instance) {
this._instance = new Web3Factory(window)
}
return this._instance
}
public getWeb3(): Web3 {
return this.web3
}
private async getPermissionFromMetabask(ethereum: any): Promise<void> {
try {
await ethereum.enable()
} catch (error) {}
}
private createNewHttpProvider(): Web3 {
return new Web3(
new Web3.providers.HttpProvider(
'https://{your infura url}'
)
)
}
}
export default Web3Factory
import Web3 from 'web3'
declare global {
interface Window {
web3: Web3
ethereum: any
}
}
export default Window
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment