Created
May 6, 2019 10:12
-
-
Save ixtgorilla/02b9b620972e3d6ae9f0d525aa67ec55 to your computer and use it in GitHub Desktop.
Web3Singletone template
This file contains hidden or 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 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 |
This file contains hidden or 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 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