-
Notifications
You must be signed in to change notification settings - Fork 39
/
web3-provider.js
254 lines (245 loc) · 6.71 KB
/
web3-provider.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import UniLoginProvider from "@unilogin/provider";
import WalletConnectWeb3Provider from "@walletconnect/web3-provider";
import Authereum from "authereum";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useReducer,
useState,
} from "react";
import { useStorageReducer } from "react-storage-hooks";
import usePromise from "react-use-promise";
import Web3 from "web3";
import Web3Modal from "web3modal";
const createWeb3 = (infuraURL) => {
const web3 = new Web3(infuraURL);
web3.modal = new Web3Modal({
cacheProvider: true,
providerOptions: {
walletconnect: {
package: WalletConnectWeb3Provider,
options: {
infuraId: infuraURL.slice(infuraURL.lastIndexOf("/") + 1),
},
},
authereum: {
package: Authereum,
},
unilogin: {
package: UniLoginProvider,
},
},
});
web3.infuraURL = infuraURL;
return web3;
};
const createWeb3FromModal = async (modal, infuraURL) => {
const web3 = new Web3(await modal.connect());
web3.modal = modal;
web3.infuraURL = infuraURL;
return web3;
};
const Context = createContext();
export default function Web3Provider({
infuraURL,
contracts,
onNetworkChange,
children,
}) {
const [web3, setWeb3] = useState(() => createWeb3(infuraURL));
useEffect(() => {
if (infuraURL !== web3.infuraURL) setWeb3(createWeb3(infuraURL));
}, [infuraURL, web3.infuraURL]);
useEffect(() => {
(async () => {
if (web3.modal.cachedProvider)
setWeb3(await createWeb3FromModal(web3.modal, web3.infuraURL));
})();
}, [web3.modal, web3.infuraURL]);
useEffect(() => {
let cancelled = false;
(async () => {
if (contracts !== web3._contracts) {
const [ETHNetID, accounts] = await Promise.all([
web3.eth.net.getId(),
web3.eth.getAccounts(),
]);
if (!cancelled) {
web3.contracts = contracts.reduce(
(acc, { name, abi, address, options }) => {
acc[name] = new web3.eth.Contract(abi, address[ETHNetID], {
from: accounts[0],
...options,
});
acc[name].jsonInterfaceMap = acc[name]._jsonInterface.reduce(
(_acc, method) => {
_acc[method.name] = method;
return _acc;
},
{}
);
return acc;
},
{}
);
web3._contracts = contracts;
onNetworkChange(ETHNetID);
}
}
})();
return () => (cancelled = true);
}, [contracts, web3, onNetworkChange]);
return (
<Context.Provider
value={useMemo(
() => ({
web3,
setWeb3,
async connect() {
web3.modal.clearCachedProvider();
setWeb3(await createWeb3FromModal(web3.modal, web3.infuraURL));
},
}),
[web3, setWeb3]
)}
>
{children}
</Context.Provider>
);
}
export function useWeb3(namespace, method, args) {
const isNotCall = !namespace || !method;
const web3Context = useContext(Context);
const data = usePromise(
() =>
!isNotCall &&
[...namespace.split("."), method].reduce(
(acc, key) => acc[key],
web3Context.web3
)(...(args || [])),
[isNotCall, namespace, method, web3Context, args]
);
return isNotCall ? web3Context : data;
}
const sendStateReducer = (
state,
{ type, transactionHash, confirmation, receipt, error }
) => {
switch (type) {
case "transactionHash":
return { transactionHash };
case "confirmation":
return { ...state, confirmation };
case "receipt":
return { ...state, receipt };
case "error":
return { ...state, error };
}
};
export function useContract(
contract,
method,
{ address, type, args, options } = {}
) {
const { web3 } = useWeb3();
contract = useMemo(() => {
let _contract = web3.contracts?.[contract];
if (_contract && address && _contract.options.address !== address) {
const jsonInterfaceMap = _contract.jsonInterfaceMap;
_contract = _contract.clone();
_contract.options.address = address;
_contract.jsonInterfaceMap = jsonInterfaceMap;
}
return _contract;
}, [web3, contract, address]);
type =
type ||
(contract &&
(contract.jsonInterfaceMap[method].constant ? "call" : "send"));
const run = useCallback(
(_args, _options) =>
contract &&
(!args ||
args.findIndex((value) => value === undefined || value === null) ===
-1) &&
contract.methods[method](...(args || []), ...(_args || []))[type]({
...options,
..._options,
}),
[contract, method, args, type, options]
);
const isSend = type === "send";
const [sendState, dispatch] = useStorageReducer(
localStorage,
JSON.stringify({ contract, method, type }),
sendStateReducer,
{}
);
const send = useCallback(
(...__args) => {
let _args;
let _options;
if (typeof __args[__args.length - 1] === "object") {
_args = __args.slice(0, -1);
_options = __args[__args.length - 1];
} else _args = __args;
return new Promise((resolve) =>
run(_args, _options)
.on("transactionHash", (transactionHash) =>
dispatch({ type: "transactionHash", transactionHash })
)
.on("confirmation", (confirmation) =>
dispatch({ type: "confirmation", confirmation })
)
.on("receipt", (receipt) => {
dispatch({ type: "receipt", receipt });
resolve(receipt);
})
.on("error", (error) => dispatch({ type: "error", error }))
);
},
[run, dispatch]
);
const [receipt] = usePromise(
() =>
sendState.transactionHash &&
!sendState.receipt &&
new Promise((resolve) => {
const poll = async () => {
const _receipt = await web3.eth.getTransactionReceipt(
sendState.transactionHash
);
if (_receipt) resolve(_receipt);
else setTimeout(poll, 2000);
};
poll();
}),
[sendState.transactionHash, sendState.receipt, web3]
);
const [reCallRef, reCall] = useReducer(() => ({}), {});
const data = usePromise(
() =>
reCallRef &&
type &&
!isSend &&
run().then?.((res) =>
typeof res === "boolean" ||
Number.isNaN(Number(res)) ||
res?.startsWith("0x")
? res
: web3.utils.toBN(res)
),
[reCallRef, type, isSend, run, web3]
);
return isSend
? {
receipt,
...sendState,
send,
loading: sendState.transactionHash && !sendState.receipt && !receipt,
}
: [...data, reCall];
}