-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb3.js
104 lines (81 loc) · 2.82 KB
/
web3.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
let web3;
import store from './redux/store.js';
import {
set_web3_instance,
set_web3_read_instance,
set_eth_injected,
set_initialized,
add_contract,
} from './redux/actions/web3Actions.js';
import {
set_wallet,
set_login_status,
set_address,
set_chain_id,
} from './redux/actions/walletActions.js';
const isEthInjected = typeof window !== 'undefined' && window.ethereum;
const initWeb3 = async () => {
/* injected */
if (!isEthInjected) return;
store.dispatch(set_eth_injected(true));
//1. get ethereum
const ethereum = window.ethereum;
//2. set wallet provider
if (ethereum.isMetaMask) store.dispatch(set_wallet('isMetamask'));
if (ethereum.isTrust) store.dispatch(set_wallet('isTrust'));
//instance web3
const web3 = await new Web3(ethereum);
store.dispatch(set_web3_instance(web3));
//detect if wallet is connected to site
const accArr = await web3.eth.getAccounts();
if (accArr.length === 0) store.dispatch(set_login_status(false));
else {
store.dispatch(set_login_status(true));
store.dispatch(set_address(accArr[0]));
store.dispatch(set_chain_id(await web3.eth.getChainId()));
}
//listen to eth change events
ethereum.on('accountsChanged', (accounts) => {
if (accounts.length > 0) {
store.dispatch(set_address(accounts[0]));
} else {
store.dispatch(set_login_status(false));
store.dispatch(set_address(null));
}
});
// ethereum.on('connect', connectInfo => {
// // if(accounts[0] != null)
// // store.dispatch( set_address(accounts[0]) );
// // store.dispatch( set_connection(true) );
// // console.log('cnx');
// });
ethereum.on('disconnect', (error) => {
// store.dispatch(set_address(''));
console.log(error);
});
ethereum.on('chainChanged', async () => {
// window.location.reload();
store.dispatch(set_chain_id(await web3.eth.getChainId()));
});
const rfcABI = await (await fetch('./abis/erc721.json')).json();
const rfcContract = new web3.eth.Contract(
rfcABI,
'0xAce6827f3E99834643cd9896E74Ab9256543fb1d'
);
store.dispatch(add_contract('RFC', rfcContract));
store.dispatch(set_initialized(true));
};
const initStaticWeb3 = (rpcs) => {
rpcs.forEach(async (rpc) => {
const { chainId, url } = rpc;
const web3 = new Web3(url);
store.dispatch(set_web3_read_instance(chainId, web3));
const rfcABI = await (await fetch('./abis/erc721.json')).json();
const rfcContract = new web3.eth.Contract(
rfcABI,
'0xAce6827f3E99834643cd9896E74Ab9256543fb1d'
);
store.dispatch(add_contract('RFC_READ', rfcContract));
});
};
export { initWeb3, initStaticWeb3 };