-
Notifications
You must be signed in to change notification settings - Fork 86
/
App.js
778 lines (734 loc) · 24.4 KB
/
App.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
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
import React, { useState, useEffect } from 'react'
import { ethers } from 'ethers'
import VConsole from 'vconsole'
import {
initWeb3Onboard,
ethMainnetGasBlockPrices,
infuraRPC
} from './services'
import {
useAccountCenter,
useConnectWallet,
useNotifications,
useSetChain,
useWallets,
useSetLocale,
useWagmiConfig
} from '@web3-onboard/react'
import './App.css'
import Header from './views/Header/Header.js'
import Footer from './views/Footer/Footer.js'
import {
getConnectors,
disconnect as wagmiDisconnect,
switchChain,
sendTransaction as wagmiSendTransaction
} from '@web3-onboard/wagmi'
import { parseEther, isHex, fromHex } from 'viem'
if (window.innerWidth < 700) {
new VConsole()
}
let provider
const App = () => {
const [{ wallet }, connect, disconnect, updateBalances, setWalletModules] =
useConnectWallet()
const wagmiConfig = useWagmiConfig()
const [{ chains, connectedChain, settingChain }, setChain] = useSetChain()
const [notifications, customNotification, updateNotify] = useNotifications()
const connectedWallets = useWallets()
const updateAccountCenter = useAccountCenter()
const updateLocale = useSetLocale()
const [web3Onboard, setWeb3Onboard] = useState(null)
const [bnGasPrices, setBNGasPrices] = useState('')
const [rpcInfuraGasPrices, setRPCInfuraGasPrices] = useState('')
const [toAddress, setToAddress] = useState('')
// default test transaction to Sepolia
const [toChain, setToChain] = useState(11155111)
const [accountCenterPosition, setAccountCenterPosition] = useState('topRight')
const [notifyPosition, setNotifyPosition] = useState('topRight')
const [locale, setLocale] = useState('en')
const [accountCenterSize, setAccountCenterSize] = useState('normal')
useEffect(() => {
setWeb3Onboard(initWeb3Onboard)
}, [])
useEffect(() => {
console.log(notifications)
}, [notifications])
useEffect(() => {
if (!connectedWallets.length) return
const connectedWalletsLabelArray = connectedWallets.map(
({ label }) => label
)
// Check for Magic Wallet user session
if (connectedWalletsLabelArray.includes('Magic Wallet')) {
const [magicWalletProvider] = connectedWallets.filter(
provider => provider.label === 'Magic Wallet'
)
async function setMagicUser() {
try {
const { email } =
await magicWalletProvider.instance.user.getMetadata()
const magicUserEmail = localStorage.getItem('magicUserEmail')
if (!magicUserEmail || magicUserEmail !== email)
localStorage.setItem('magicUserEmail', email)
} catch (err) {
throw err
}
}
setMagicUser()
}
}, [connectedWallets, wallet])
useEffect(() => {
if (!wallet?.provider) {
provider = null
} else {
provider = new ethers.providers.Web3Provider(wallet.provider, 'any')
}
}, [wallet])
useEffect(() => {
ethMainnetGasBlockPrices.subscribe(estimates => {
setBNGasPrices(estimates[0].blockPrices[0].estimatedPrices)
})
}, [])
useEffect(() => {
console.log('wagmiConfig', wagmiConfig)
}, [wagmiConfig])
useEffect(() => {
async function getEtherGasFromRPC() {
try {
const customHttpProvider = new ethers.providers.JsonRpcProvider(
infuraRPC
)
if (!customHttpProvider) return console.warn('No provider found')
const fee = await customHttpProvider.getFeeData()
// Occasionally gas values are returned undefined
if (
!fee ||
!fee.gasPrice ||
!fee.maxPriorityFeePerGas ||
!fee.maxFeePerGas
)
return console.warn(
`Missing necessary gas properties in fee response - fee: ${JSON.stringify(
fee
)}`
)
const cleanFees = {
price: ethers.utils.formatUnits(fee.gasPrice, 'gwei'),
maxPriorityFeePerGas: ethers.utils.formatUnits(
fee.maxPriorityFeePerGas,
'gwei'
),
maxFeePerGas: ethers.utils.formatUnits(fee.maxFeePerGas, 'gwei')
}
setRPCInfuraGasPrices(cleanFees)
} catch (err) {
console.error(err)
}
}
getEtherGasFromRPC()
}, [bnGasPrices])
const gasView = gasObj => {
return Object.keys(gasObj)
.filter(prop => prop !== 'price')
.map(key => (
<section value={key} key={key}>
{key} : {gasObj[key]}
</section>
))
}
const gasDiff = bnGas => {
const priFeeDiff =
rpcInfuraGasPrices.maxPriorityFeePerGas - bnGas.maxPriorityFeePerGas
const maxFeeDiff = rpcInfuraGasPrices.maxFeePerGas - bnGas.maxFeePerGas
return priFeeDiff + maxFeeDiff
}
const readyToTransact = async () => {
if (!wallet) {
const walletSelected = await connect()
if (!walletSelected) return false
}
// prompt user to switch to Goerli for test
await setChain({ chainId: toChain })
return true
}
const gweiToWeiHex = gwei => {
return `0x${(gwei * 1e9).toString(16)}`
}
const sendHash = async () => {
if (!toAddress) {
alert('An Ethereum address to send Eth to is required.')
return
}
// const signer = provider.getUncheckedSigner()
// To set gas using the Web3-Onboard Gas package(support Eth Mainnet and Polygon)
// define desired confidence for transaction inclusion in block and set in transaction
// const bnGasForTransaction = bnGasPrices.find(gas => gas.confidence === 90)
// const rc = await signer.sendTransaction({
// to: toAddress,
// value: 1000000000000000
// // This will set the transaction gas based on desired confidence
// // maxPriorityFeePerGas: gweiToWeiHex(
// // bnGasForTransaction.maxPriorityFeePerGas
// // ),
// // maxFeePerGas: gweiToWeiHex(bnGasForTransaction.maxFeePerGas)
// })
// console.log(rc)
sendTransactionWagmi()
}
const sendTransaction = async () => {
if (!toAddress) {
alert('An Ethereum address to send Eth to is required.')
}
const balanceValue = Object.values(wallet.accounts[0].balance)[0]
const signer = provider.getUncheckedSigner()
const txDetails = {
to: toAddress,
value: 1000000000000000
}
const sendTransaction = () => {
return signer.sendTransaction(txDetails).then(tx => tx.hash)
}
const gasPrice = () => provider.getGasPrice().then(res => res.toString())
const estimateGas = () => {
return provider.estimateGas(txDetails).then(res => res.toString())
}
console.log(estimateGas)
// convert to hook when available
const transactionHash =
await web3Onboard.state.actions.preflightNotifications({
sendTransaction,
gasPrice,
estimateGas,
balance: balanceValue,
txDetails: txDetails
})
console.log(transactionHash)
}
// WAGMI functions
async function switchChainWagmi(chainId) {
let chainAsNumber
const { wagmiConnector } = wallet
console.log('wagmiConnector', wagmiConnector)
if (isHex(chainId)) {
chainAsNumber = fromHex(chainId, 'number')
} else if (!isHex(chainId) && typeof chainId === 'number') {
chainAsNumber = chainId
} else {
throw new Error('Invalid chainId')
}
await switchChain(wagmiConfig, {
chainId: chainAsNumber,
connector: wagmiConnector
})
}
const sendTransactionWagmi = async () => {
const { wagmiConnector } = wallet
console.log('transactWithThisWallet', wagmiConnector)
// current primary wallet - as multiple wallets can connect this value is the currently active
const result = await wagmiSendTransaction(wagmiConfig, {
to: toAddress,
value: parseEther('0.001'),
// desired connector to send txn from
connector: wagmiConnector
})
console.log(result)
}
const renderNotifySettings = () => {
if (window.innerWidth < 425) {
return (
<div className={'conditional-ui-settings'}>
<h3>Notify Mobile Positioning</h3>
<button
className={`bn-demo-button ${
notifyPosition === 'topRight'
? 'selected-toggle-btn'
: 'unselected-toggle-btn'
}`}
onClick={() => {
setNotifyPosition('topRight')
updateNotify({ position: 'topRight' })
}}
>
Top
</button>
<button
className={`bn-demo-button ${
notifyPosition === 'bottomRight'
? 'selected-toggle-btn'
: 'unselected-toggle-btn'
}`}
onClick={() => {
setNotifyPosition('bottomRight')
updateNotify({ position: 'bottomRight' })
}}
>
Bottom
</button>
</div>
)
}
return (
<div className={'conditional-ui-settings'}>
{' '}
<h3>Notify Positioning</h3>
<button
className={`bn-demo-button ${
notifyPosition === 'topLeft'
? 'selected-toggle-btn'
: 'unselected-toggle-btn'
}`}
onClick={() => {
setNotifyPosition('topLeft')
updateNotify({ position: 'topLeft' })
}}
>
Top Left
</button>
<button
className={`bn-demo-button ${
notifyPosition === 'topRight'
? 'selected-toggle-btn'
: 'unselected-toggle-btn'
}`}
onClick={() => {
setNotifyPosition('topRight')
updateNotify({ position: 'topRight' })
}}
>
Top Right
</button>
<button
className={`bn-demo-button ${
notifyPosition === 'bottomRight'
? 'selected-toggle-btn'
: 'unselected-toggle-btn'
}`}
onClick={() => {
setNotifyPosition('bottomRight')
updateNotify({ position: 'bottomRight' })
}}
>
Bottom Right
</button>
<button
className={`bn-demo-button ${
notifyPosition === 'bottomLeft'
? 'selected-toggle-btn'
: 'unselected-toggle-btn'
}`}
onClick={() => {
setNotifyPosition('bottomLeft')
updateNotify({ position: 'bottomLeft' })
}}
>
Bottom Left
</button>
</div>
)
}
const renderAccountCenterSettings = () => {
if (window.innerWidth < 425) {
return (
<div className={'conditional-ui-settings'}>
<h3>Account Center Mobile Positioning</h3>
<button
className={`bn-demo-button ${
accountCenterPosition === 'topRight'
? 'selected-toggle-btn'
: 'unselected-toggle-btn'
}`}
onClick={() => {
setAccountCenterPosition('topRight')
updateAccountCenter({
position: 'topRight'
})
}}
>
Top
</button>
<button
className={`bn-demo-button ${
accountCenterPosition === 'bottomRight'
? 'selected-toggle-btn'
: 'unselected-toggle-btn'
}`}
onClick={() => {
setAccountCenterPosition('bottomRight')
updateAccountCenter({
position: 'bottomRight'
})
}}
>
Bottom
</button>
</div>
)
}
return (
<div className={'conditional-ui-settings'}>
{' '}
<h3>Account Center Positioning</h3>
<button
className={`bn-demo-button ${
accountCenterPosition === 'topLeft'
? 'selected-toggle-btn'
: 'unselected-toggle-btn'
}`}
onClick={() => {
setAccountCenterPosition('topLeft')
updateAccountCenter({
position: 'topLeft'
})
}}
>
Top Left
</button>
<button
className={`bn-demo-button ${
accountCenterPosition === 'topRight'
? 'selected-toggle-btn'
: 'unselected-toggle-btn'
}`}
onClick={() => {
setAccountCenterPosition('topRight')
updateAccountCenter({
position: 'topRight'
})
}}
>
Top Right
</button>
<button
className={`bn-demo-button ${
accountCenterPosition === 'bottomRight'
? 'selected-toggle-btn'
: 'unselected-toggle-btn'
}`}
onClick={() => {
setAccountCenterPosition('bottomRight')
updateAccountCenter({
position: 'bottomRight'
})
}}
>
Bottom Right
</button>
<button
className={`bn-demo-button ${
accountCenterPosition === 'bottomLeft'
? 'selected-toggle-btn'
: 'unselected-toggle-btn'
}`}
onClick={() => {
setAccountCenterPosition('bottomLeft')
updateAccountCenter({
position: 'bottomLeft'
})
}}
>
Bottom Left
</button>
</div>
)
}
if (!web3Onboard) return <div>Loading...</div>
return (
<main>
<Header
connectedChain={wallet ? connectedChain : null}
address={wallet?.accounts[0]?.address}
balance={wallet?.accounts[0]?.balance}
ens={wallet?.accounts[0]?.ens}
/>
<section className="main">
<div className="main-content">
<div className="vertical-main-container">
<div className="container onboard">
<h2>Onboarding Users with Web3-Onboard</h2>
{wallet && (
<div className="network-select">
<label>Switch Chains</label>
{settingChain ? (
<span>Switching Chains...</span>
) : (
<select
className="chain-select"
onChange={({ target: { value } }) =>
// setChain({ chainId: value })
switchChainWagmi(value)
}
value={connectedChain?.id}
>
{chains.map(({ id, label }) => {
return (
<option value={id} key={id}>
{label}
</option>
)
})}
</select>
)}
</div>
)}
<div className="account-center-actions">
<div>
{!wallet && (
<button
className="bn-demo-button"
onClick={async () => {
const walletsConnected = await connect()
console.log('connected wallets: ', walletsConnected)
}}
>
Select a Wallet
</button>
)}
{wallet && (
<button
className="bn-demo-button"
onClick={async () => {
const walletsConnected = await connect()
console.log('connected wallets: ', walletsConnected)
}}
>
Connect Another Wallet
</button>
)}
{wallet && (
<button
className="bn-demo-button"
onClick={async () => {
// Disconnect using web3-onboard hook
await disconnect(wallet)
// Disconnect using WAGMI
// const disconnectThisWallet = getConnectors(
// wagmiConfig
// ).find(connector => connector.name === wallet.label)
// wagmiDisconnect(wagmiConfig, {
// connector: disconnectThisWallet
// })
}}
>
Reset Wallet State
</button>
)}
{wallet && wallet?.dashboard && (
<button
className="bn-demo-button"
onClick={wallet?.dashboard}
>
Open Wallet Dashboard
</button>
)}
{wallet &&
wallet?.type === 'hardware' &&
wallet.accounts[0].address && (
<button
className="bn-demo-button"
onClick={web3Onboard.accountSelect}
>
Switch Account
</button>
)}
</div>
<div>
{wallet && (
// If providing a DAppId w/ Notifications enabled within the
// onboard initialization balances are updated automatically
<button
className="bn-demo-button"
onClick={() => updateBalances}
>
Update Balances
</button>
)}
{wallet && (
<button
className="bn-demo-button"
onClick={e => {
updateLocale(locale === 'es' ? 'en' : 'es')
setLocale(locale === 'es' ? 'en' : 'es')
updateAccountCenter({ expanded: true })
e.stopPropagation()
}}
>
Set Locale To {locale === 'es' ? 'English' : 'Spanish'}
</button>
)}
{wallet && (
<button
className="bn-demo-button"
onClick={e => {
setAccountCenterSize(prevState => {
return prevState === 'minimal'
? 'normal'
: prevState === 'normal'
? 'expanded'
: 'minimal'
})
updateAccountCenter(
accountCenterSize === 'minimal'
? { minimal: false }
: accountCenterSize === 'normal'
? { minimal: true, expanded: true }
: { minimal: true, expanded: false }
)
e.stopPropagation()
}}
>
Set Account Center To{' '}
{accountCenterSize === 'minimal'
? 'Collapsed'
: accountCenterSize === 'normal'
? 'Expanded'
: 'Minimal'}
</button>
)}
</div>
</div>
</div>
<div className="container notify">
<h2>Transaction Notifications with Notify</h2>
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
marginBottom: '1rem'
}}
>
<div style={{ marginBottom: '1rem' }}>
<label>
Send 0.001{' '}
<select
onChange={({ target: { value } }) => setToChain(value)}
value={toChain}
>
{chains.map(({ id, label }) => {
if (
label === 'Sepolia' ||
label === 'Polygon - Mumbai'
) {
return (
<option value={id} key={id}>
{label}
</option>
)
}
return null
})}
</select>{' '}
Test Eth to:
</label>
<input
type="text"
style={{
padding: '0.5rem',
border: 'none',
borderRadius: '10px',
marginLeft: '0.5rem',
width: '18rem'
}}
value={toAddress}
placeholder="address"
onChange={e => setToAddress(e.target.value)}
/>
</div>
<div className={'send-transaction-container'}>
<button
className="bn-demo-button"
onClick={async () => {
const ready = await readyToTransact()
if (!ready) return
sendHash()
}}
>
Send
</button>
with in-flight notifications
</div>
<div className={'send-transaction-container'}>
<button
className="bn-demo-button"
onClick={async () => {
const ready = await readyToTransact()
if (!ready) return
sendTransactionWagmi()
}}
>
Send
</button>
with pre-flight and in-flight notifications
</div>
</div>
<div>
<button
className="bn-demo-button"
onClick={() => {
const { update, dismiss } = customNotification({
eventCode: 'dbUpdate',
type: 'hint',
message: 'Custom hint notification created by the dapp',
onClick: () => window.open(`https://www.blocknative.com`)
})
// Update your notification example below
// setTimeout(
// () =>
// update({
// eventCode: 'dbUpdateSuccess',
// message: 'Hint notification reason resolved!',
// type: 'success',
// autoDismiss: 5000
// }),
// 4000
// )
setTimeout(
() =>
// use the dismiss method returned or add an autoDismiss prop to the notification
dismiss(),
4000
)
}}
>
Custom Hint Notification
</button>
</div>
</div>
</div>
<div className="container ui-settings">{renderNotifySettings()}</div>
<div className="container ui-settings">
{renderAccountCenterSettings()}
</div>
</div>
{bnGasPrices && (
<div className="bn-gas-container">
Web3-Onboard Gas Package Mainnet Pricing
<div className="bn-gas">
{bnGasPrices.map(conf => {
return (
<div className="gas-container" key={conf.confidence}>
{gasView(conf)}
{rpcInfuraGasPrices && (
<section>gwei saved : {gasDiff(conf).toFixed(3)}</section>
)}
</div>
)
})}
</div>
</div>
)}
{rpcInfuraGasPrices && (
<div className="rpc-gas-container">
Ethers.js Mainnet Gas Pricing
<div className="gas-container rpc-gas">
{gasView(rpcInfuraGasPrices)}
</div>
</div>
)}
</section>
<Footer />
</main>
)
}
export default App