@@ -3,6 +3,7 @@ import './App.css';
3
3
4
4
import SetProtocol from 'setprotocol.js' ;
5
5
import BigNumber from 'bignumber.js' ;
6
+ import Web3 from 'web3' ;
6
7
7
8
// Kovan configuration
8
9
const config = {
@@ -15,27 +16,44 @@ const config = {
15
16
class App extends Component {
16
17
constructor ( ) {
17
18
super ( ) ;
18
- const injectedWeb3 = window . web3 || undefined ;
19
- let setProtocol ;
20
- try {
21
- // Use MetaMask/Mist provider
22
- const provider = injectedWeb3 . currentProvider ;
23
- setProtocol = new SetProtocol ( provider , config ) ;
24
- } catch ( err ) {
25
- // Throws when user doesn't have MetaMask/Mist running
26
- throw new Error ( `No injected web3 found when initializing setProtocol: ${ err } ` ) ;
27
- }
28
-
29
19
this . state = {
30
- setProtocol,
31
- web3 : injectedWeb3 ,
20
+ setProtocol : null ,
21
+ web3 : null ,
32
22
// Etherscan Links
33
23
createdSetLink : '' ,
34
24
} ;
35
25
this . createSet = this . createSet . bind ( this ) ;
36
26
this . getAccount = this . getAccount . bind ( this ) ;
37
27
}
38
28
29
+ componentDidMount ( ) {
30
+ if ( ! this . state . web3 ) {
31
+ this . requestWeb3Access ( ) ;
32
+ }
33
+ }
34
+
35
+ async requestWeb3Access ( ) {
36
+ let setProtocol , injectedWeb3 ;
37
+ if ( window . ethereum ) {
38
+ try {
39
+ injectedWeb3 = new Web3 ( window . ethereum ) ;
40
+ await window . ethereum . enable ( ) ;
41
+ } catch ( err ) {
42
+ console . error ( `Unable to access web3: ${ err . message } ` ) ;
43
+ }
44
+ }
45
+ else if ( window . web3 ) {
46
+ injectedWeb3 = window . web3 ;
47
+ }
48
+ if ( injectedWeb3 ) {
49
+ setProtocol = new SetProtocol ( injectedWeb3 . currentProvider , config ) ;
50
+ this . setState ( ( prevState ) => ( { web3 : injectedWeb3 , setProtocol } ) ) ;
51
+ }
52
+ else {
53
+ console . error ( 'Web3 provider not found.' ) ;
54
+ }
55
+ }
56
+
39
57
async createSet ( ) {
40
58
const { setProtocol } = this . state ;
41
59
@@ -99,8 +117,8 @@ class App extends Component {
99
117
100
118
getAccount ( ) {
101
119
const { web3 } = this . state ;
102
- if ( web3 . eth . accounts [ 0 ] ) return web3 . eth . accounts [ 0 ] ;
103
- throw new Error ( 'Your MetaMask is locked. Unlock it to continue.' ) ;
120
+ if ( web3 && web3 . eth . accounts [ 0 ] ) return web3 . eth . accounts [ 0 ] ;
121
+ throw new Error ( 'Unlock MetaMask or allow account access when prompted to continue.' ) ;
104
122
}
105
123
106
124
renderEtherScanLink ( link , content ) {
0 commit comments