/
App.tsx
489 lines (446 loc) · 14.6 KB
/
App.tsx
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import { useEffect, useState } from "react";
import { Web3Auth } from "@web3auth/modal";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { CHAIN_NAMESPACES, IProvider, WEB3AUTH_NETWORK } from "@web3auth/base";
import { OpenloginAdapter } from "@web3auth/openlogin-adapter";
import "./App.css";
import RPC from "./web3RPC"; // for using web3.js
// import RPC from "./ethersRPC"; // for using ethers.js
// Plugins
import { TorusWalletConnectorPlugin } from "@web3auth/torus-wallet-connector-plugin";
// Adapters
import { WalletConnectV2Adapter, getWalletConnectV2Settings } from "@web3auth/wallet-connect-v2-adapter";
import { MetamaskAdapter } from "@web3auth/metamask-adapter";
import { TorusWalletAdapter } from "@web3auth/torus-evm-adapter";
const clientId = "BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ"; // get from https://dashboard.web3auth.io
function App() {
const [web3auth, setWeb3auth] = useState<Web3Auth | null>(null);
const [torusPlugin, setTorusPlugin] = useState<TorusWalletConnectorPlugin | null>(null);
const [loggedIn, setLoggedIn] = useState(false);
useEffect(() => {
const init = async () => {
try {
const web3auth = new Web3Auth({
clientId,
chainConfig: {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth", // This is the public RPC we have added, please pass on your own endpoint while creating an app
},
// uiConfig refers to the whitelabeling options, which is available only on Growth Plan and above
// Please remove this parameter if you're on the Base Plan
uiConfig: {
appName: "W3A",
theme: {
primary: "red",
},
mode: "dark",
logoLight: "https://web3auth.io/images/web3auth-logo.svg",
logoDark: "https://web3auth.io/images/web3auth-logo---Dark.svg",
defaultLanguage: "en", // en, de, ja, ko, zh, es, fr, pt, nl
loginGridCol: 3,
primaryButton: "externalLogin", // "externalLogin" | "socialLogin" | "emailLogin"
},
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
});
const openloginAdapter = new OpenloginAdapter({
loginSettings: {
mfaLevel: "optional",
},
adapterSettings: {
uxMode: "redirect", // "redirect" | "popup"
whiteLabel: {
logoLight: "https://web3auth.io/images/web3auth-logo.svg",
logoDark: "https://web3auth.io/images/web3auth-logo---Dark.svg",
defaultLanguage: "en", // en, de, ja, ko, zh, es, fr, pt, nl
mode: "dark", // whether to enable dark, light or auto mode. defaultValue: auto [ system theme]
},
mfaSettings: {
deviceShareFactor: {
enable: true,
priority: 1,
mandatory: true,
},
backUpShareFactor: {
enable: true,
priority: 2,
mandatory: false,
},
socialBackupFactor: {
enable: true,
priority: 3,
mandatory: false,
},
passwordFactor: {
enable: true,
priority: 4,
mandatory: false,
},
},
},
});
web3auth.configureAdapter(openloginAdapter);
// plugins and adapters are optional and can be added as per your requirement
// read more about plugins here: https://web3auth.io/docs/sdk/web/plugins/
// adding torus wallet connector plugin
const torusPlugin = new TorusWalletConnectorPlugin({
torusWalletOpts: {},
walletInitOptions: {
whiteLabel: {
theme: { isDark: true, colors: { primary: "#00a8ff" } },
logoDark: "https://web3auth.io/images/web3auth-logo.svg",
logoLight: "https://web3auth.io/images/web3auth-logo---Dark.svg",
},
useWalletConnect: true,
enableLogging: true,
},
});
setTorusPlugin(torusPlugin);
await web3auth.addPlugin(torusPlugin);
// read more about adapters here: https://web3auth.io/docs/sdk/pnp/web/adapters/
// adding wallet connect v2 adapter
const defaultWcSettings = await getWalletConnectV2Settings("eip155", [1], "04309ed1007e77d1f119b85205bb779d");
const walletConnectV2Adapter = new WalletConnectV2Adapter({
adapterSettings: { ...defaultWcSettings.adapterSettings },
loginSettings: { ...defaultWcSettings.loginSettings },
});
web3auth.configureAdapter(walletConnectV2Adapter);
// adding metamask adapter
const metamaskAdapter = new MetamaskAdapter({
clientId,
sessionTime: 3600, // 1 hour in seconds
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
chainConfig: {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth", // This is the public RPC we have added, please pass on your own endpoint while creating an app
},
});
// we can change the above settings using this function
metamaskAdapter.setAdapterSettings({
sessionTime: 86400, // 1 day in seconds
chainConfig: {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth", // This is the public RPC we have added, please pass on your own endpoint while creating an app
},
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
});
// it will add/update the metamask adapter in to web3auth class
web3auth.configureAdapter(metamaskAdapter);
const torusWalletAdapter = new TorusWalletAdapter({
clientId,
});
// it will add/update the torus-evm adapter in to web3auth class
web3auth.configureAdapter(torusWalletAdapter);
setWeb3auth(web3auth);
await web3auth.initModal();
// await web3auth.initModal({
// modalConfig: {
// [WALLET_ADAPTERS.OPENLOGIN]: {
// label: "openlogin",
// loginMethods: {
// // Disable facebook and reddit
// facebook: {
// name: "facebook",
// showOnModal: false
// },
// reddit: {
// name: "reddit",
// showOnModal: false
// },
// // Disable email_passwordless and sms_passwordless
// email_passwordless: {
// name: "email_passwordless",
// showOnModal: false
// },
// sms_passwordless: {
// name: "sms_passwordless",
// showOnModal: false
// }
// }
// }
// }
// });
if (web3auth.connected) {
setLoggedIn(true);
}
} catch (error) {
console.error(error);
}
};
init();
}, []);
const login = async () => {
if (!web3auth) {
uiConsole("web3auth not initialized yet");
return;
}
await web3auth.connect();
// setLoggedIn(true);
};
const authenticateUser = async () => {
if (!web3auth) {
uiConsole("web3auth not initialized yet");
return;
}
const idToken = await web3auth.authenticateUser();
uiConsole(idToken);
};
const getUserInfo = async () => {
if (!web3auth) {
uiConsole("web3auth not initialized yet");
return;
}
const user = await web3auth.getUserInfo();
uiConsole(user);
};
const logout = async () => {
if (!web3auth) {
uiConsole("web3auth not initialized yet");
return;
}
await web3auth.logout();
setLoggedIn(false);
};
const showWCM = async () => {
if (!torusPlugin) {
uiConsole("torus plugin not initialized yet");
return;
}
torusPlugin.showWalletConnectScanner();
uiConsole();
};
const initiateTopUp = async () => {
if (!torusPlugin) {
uiConsole("torus plugin not initialized yet");
return;
}
torusPlugin.initiateTopup("moonpay", {
selectedAddress: "0x8cFa648eBfD5736127BbaBd1d3cAe221B45AB9AF",
selectedCurrency: "USD",
fiatValue: 100,
selectedCryptoCurrency: "ETH",
chainNetwork: "mainnet",
});
};
const getChainId = async () => {
if (!web3auth?.provider) {
uiConsole("provider not initialized yet");
return;
}
const rpc = new RPC(web3auth.provider as IProvider);
const chainId = await rpc.getChainId();
uiConsole(chainId);
};
const addChain = async () => {
if (!web3auth?.provider) {
uiConsole("provider not initialized yet");
return;
}
const newChain = {
chainId: "0x5",
displayName: "Goerli",
chainNamespace: CHAIN_NAMESPACES.EIP155,
tickerName: "Goerli",
ticker: "ETH",
decimals: 18,
rpcTarget: "https://rpc.ankr.com/eth_goerli",
blockExplorer: "https://goerli.etherscan.io",
};
await web3auth?.addChain(newChain);
uiConsole("New Chain Added");
};
const switchChain = async () => {
if (!web3auth?.provider) {
uiConsole("provider not initialized yet");
return;
}
await web3auth?.switchChain({ chainId: "0x5" });
uiConsole("Chain Switched");
};
const getAccounts = async () => {
if (!web3auth?.provider) {
uiConsole("provider not initialized yet");
return;
}
const rpc = new RPC(web3auth.provider as IProvider);
const address = await rpc.getAccounts();
uiConsole(address);
};
const getBalance = async () => {
if (!web3auth?.provider) {
uiConsole("provider not initialized yet");
return;
}
const rpc = new RPC(web3auth.provider as IProvider);
const balance = await rpc.getBalance();
uiConsole(balance);
};
const sendTransaction = async () => {
if (!web3auth?.provider) {
uiConsole("provider not initialized yet");
return;
}
const rpc = new RPC(web3auth.provider as IProvider);
const receipt = await rpc.sendTransaction();
uiConsole(receipt);
};
const signMessage = async () => {
if (!web3auth?.provider) {
uiConsole("provider not initialized yet");
return;
}
const rpc = new RPC(web3auth.provider as IProvider);
const signedMessage = await rpc.signMessage();
uiConsole(signedMessage);
};
const readContract = async () => {
if (!web3auth?.provider) {
uiConsole("provider not initialized yet");
return;
}
const rpc = new RPC(web3auth.provider as IProvider);
const message = await rpc.readContract();
uiConsole(message);
};
const writeContract = async () => {
if (!web3auth?.provider) {
uiConsole("provider not initialized yet");
return;
}
const rpc = new RPC(web3auth.provider as IProvider);
const receipt = await rpc.writeContract();
uiConsole(receipt);
if (receipt) {
setTimeout(async () => {
await readContract();
}, 2000);
}
};
const getPrivateKey = async () => {
if (!web3auth?.provider) {
uiConsole("provider not initialized yet");
return;
}
const rpc = new RPC(web3auth.provider as IProvider);
const privateKey = await rpc.getPrivateKey();
uiConsole(privateKey);
};
function uiConsole(...args: any[]): void {
const el = document.querySelector("#console>p");
if (el) {
el.innerHTML = JSON.stringify(args || {}, null, 2);
}
}
const loggedInView = (
<>
<div className="flex-container">
<div>
<button onClick={getUserInfo} className="card">
Get User Info
</button>
</div>
<div>
<button onClick={authenticateUser} className="card">
Get ID Token
</button>
</div>
<div>
<button onClick={showWCM} className="card">
Show Wallet Connect Modal
</button>
</div>
<div>
<button onClick={initiateTopUp} className="card">
initiateTopUp
</button>
</div>
<div>
<button onClick={getChainId} className="card">
Get Chain ID
</button>
</div>
<div>
<button onClick={addChain} className="card">
Add Chain
</button>
</div>
<div>
<button onClick={switchChain} className="card">
Switch Chain
</button>
</div>
<div>
<button onClick={getAccounts} className="card">
Get Accounts
</button>
</div>
<div>
<button onClick={getBalance} className="card">
Get Balance
</button>
</div>
<div>
<button onClick={signMessage} className="card">
Sign Message
</button>
</div>
<div>
<button onClick={sendTransaction} className="card">
Send Transaction
</button>
</div>
<div>
<button onClick={readContract} className="card">
Read Contract
</button>
</div>
<div>
<button onClick={writeContract} className="card">
Write Contract
</button>
</div>
<div>
<button onClick={getPrivateKey} className="card">
Get Private Key
</button>
</div>
<div>
<button onClick={logout} className="card">
Log Out
</button>
</div>
</div>
<div id="console" style={{ whiteSpace: "pre-line" }}>
<p style={{ whiteSpace: "pre-line" }}></p>
</div>
</>
);
const unloggedInView = (
<button onClick={login} className="card">
Login
</button>
);
return (
<div className="container">
<h1 className="title">
<a target="_blank" href="https://web3auth.io/docs/sdk/pnp/web/modal" rel="noreferrer">
Web3Auth{" "}
</a>
& ReactJS Ethereum Example
</h1>
<div className="grid">{loggedIn ? loggedInView : unloggedInView}</div>
<footer className="footer">
<a
href="https://github.com/Web3Auth/web3auth-pnp-examples/tree/main/web-modal-sdk/blockchain-connection-examples/evm-modal-example"
target="_blank"
rel="noopener noreferrer"
>
Source code
</a>
</footer>
</div>
);
}
export default App;