-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathApp.tsx
1315 lines (1105 loc) · 39.3 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
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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { AnimatePresence } from 'framer-motion'
import React, { useState, useEffect, useMemo, SetStateAction } from 'react'
import { ethers } from 'ethers'
import { sequence } from '0xsequence'
import { walletContracts } from '@0xsequence/abi'
import {
Box,
Image,
Text,
Button,
ExternalLinkIcon,
Divider,
Card,
TransactionIcon,
Select,
TokenImage,
TextInput,
Modal
} from '@0xsequence/design-system'
import { ETHAuth } from '@0xsequence/ethauth'
import { configureLogger } from '@0xsequence/utils'
import { ConnectOptions, OpenWalletIntent, Settings } from '@0xsequence/provider'
import { ChainId, NetworkType } from '@0xsequence/network'
import { ERC_20_ABI } from './constants/abi'
import { Console } from './components/Console'
import { Group } from './components/Group'
import { getDefaultChainId, toHexString } from './helpers'
import logoUrl from './images/logo.svg'
import skyweaverBannerUrl from './images/skyweaver-banner.png'
import skyweaverBannerLargeUrl from './images/skyweaver-banner-large.png'
configureLogger({ logLevel: 'DEBUG' })
interface Environment {
name: string
walletUrl: string
projectAccessKey: string
}
const environments: Environment[] = [
{
name: 'production',
walletUrl: 'https://sequence.app',
projectAccessKey: 'AQAAAAAAAAbvrgpWEC2Aefg5qYStQmwjBpA'
},
{
name: 'development',
walletUrl: 'https://dev.sequence.app',
//projectAccessKey: 'AQAAAAAAAAVBNfoB30kz7Ph4I_Qs5mkYuDc',
projectAccessKey: 'AQAAAAAAAAVCXiQ9f_57R44MjorZ4SmGdhA'
},
{
name: 'local',
walletUrl: 'http://localhost:3333',
projectAccessKey: 'AQAAAAAAAAVCXiQ9f_57R44MjorZ4SmGdhA'
}
]
const DEFAULT_API_URL = 'https://api.sequence.app'
// Specify your desired default chain id. NOTE: you can communicate to multiple
// chains at the same time without even having to switch the network, but a default
// chain is required.
const defaultChainId = getDefaultChainId() || ChainId.MAINNET
// const defaultChainId = ChainId.POLYGON
// const defaultChainId = ChainId.GOERLI
// const defaultChainId = ChainId.ARBITRUM
// const defaultChainId = ChainId.AVALANCHE
// etc.. see the full list here: https://docs.sequence.xyz/multi-chain-support
// For Sequence core dev team -- app developers can ignore
// a custom wallet app url can specified in the query string
const urlParams = new URLSearchParams(window.location.search)
const env = urlParams.get('env') ?? 'production'
const envConfig = environments.find(x => x.name === env)
const walletAppURL = urlParams.get('walletAppURL') ?? envConfig.walletUrl
const { projectAccessKey } = envConfig
const showProhibitedActions = urlParams.has('showProhibitedActions')
if (walletAppURL && walletAppURL.length > 0) {
// Wallet can point to a custom wallet app url
// NOTICE: this is not needed, unless testing an alpha version of the wallet
sequence.initWallet(projectAccessKey, { defaultNetwork: defaultChainId, transports: { walletAppURL } })
} else {
// Init the sequence wallet library at the top-level of your project with
// your designed default chain id
sequence.initWallet(projectAccessKey, { defaultNetwork: defaultChainId, transports: { walletAppURL } })
}
// App component
const App = () => {
const [consoleMsg, setConsoleMsg] = useState<null | string>(null)
const [email, setEmail] = useState<null | string>(null)
const [consoleLoading, setConsoleLoading] = useState<boolean>(false)
const [isWalletConnected, setIsWalletConnected] = useState<boolean>(false)
const wallet = sequence.getWallet().getProvider()
const [showChainId, setShowChainId] = useState<number>(wallet.getChainId())
const [isOpen, toggleModal] = useState(false)
const [warning, setWarning] = useState(false)
useMemo(() => {
wallet.on('chainChanged', (chainId: string) => {
setShowChainId(Number(BigInt(chainId)))
})
}, [])
useEffect(() => {
setIsWalletConnected(wallet.isConnected())
}, [wallet])
useEffect(() => {
consoleWelcomeMessage()
// eslint-disable-next-line
}, [isWalletConnected])
useEffect(() => {
// Wallet events
wallet.client.onOpen(() => {
console.log('wallet window opened')
})
wallet.client.onClose(() => {
console.log('wallet window closed')
})
}, [wallet])
const defaultConnectOptions: ConnectOptions = {
app: 'Demo Dapp',
askForEmail: true
// keepWalletOpened: true,
}
// Methods
const connect = async (connectOptions: ConnectOptions = { app: 'Demo dapp' }) => {
if (isWalletConnected) {
resetConsole()
appendConsoleLine('Wallet already connected!')
setConsoleLoading(false)
return
}
connectOptions = {
...defaultConnectOptions,
...connectOptions,
settings: {
...defaultConnectOptions.settings,
...connectOptions.settings
}
}
try {
resetConsole()
appendConsoleLine('Connecting')
const wallet = sequence.getWallet()
const connectDetails = await wallet.connect(connectOptions)
// Example of how to verify using ETHAuth via Sequence API
if (connectOptions.authorize && connectDetails.connected) {
let apiUrl = urlParams.get('apiUrl')
if (!apiUrl || apiUrl.length === 0) {
apiUrl = DEFAULT_API_URL
}
const api = new sequence.api.SequenceAPIClient(apiUrl)
// or just
// const api = new sequence.api.SequenceAPIClient('https://api.sequence.app')
const { isValid } = await api.isValidETHAuthProof({
chainId: connectDetails.chainId,
walletAddress: connectDetails.session.accountAddress,
ethAuthProofString: connectDetails.proof!.proofString
})
appendConsoleLine(`isValid (API)?: ${isValid}`)
}
// Example of how to verify using ETHAuth directl on the client
if (connectOptions.authorize) {
const ethAuth = new ETHAuth()
if (connectDetails.proof) {
const decodedProof = await ethAuth.decodeProof(connectDetails.proof.proofString, true)
const isValid = await wallet.utils.isValidTypedDataSignature(
wallet.getAddress(),
connectDetails.proof.typedData,
decodedProof.signature,
Number(BigInt(connectDetails.chainId))
)
appendConsoleLine(`connected using chainId: ${BigInt(connectDetails.chainId).toString()}`)
appendConsoleLine(`isValid (client)?: ${isValid}`)
}
}
setConsoleLoading(false)
if (connectDetails.connected) {
appendConsoleLine('Wallet connected!')
appendConsoleLine(`shared email: ${connectDetails.email}`)
setIsWalletConnected(true)
} else {
appendConsoleLine('Failed to connect wallet - ' + connectDetails.error)
}
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const disconnect = () => {
const wallet = sequence.getWallet()
wallet.disconnect()
consoleWelcomeMessage()
setIsWalletConnected(false)
}
const openWallet = () => {
const wallet = sequence.getWallet()
wallet.openWallet()
}
const openWalletWithSettings = () => {
const wallet = sequence.getWallet()
const settings: Settings = {
theme: 'light',
includedPaymentProviders: ['moonpay', 'ramp'],
defaultFundingCurrency: 'eth',
defaultPurchaseAmount: 400,
lockFundingCurrencyToDefault: false
}
const intent: OpenWalletIntent = {
type: 'openWithOptions',
options: {
app: 'Demo Dapp',
settings
}
}
const path = 'wallet/add-funds'
wallet.openWallet(path, intent)
}
const closeWallet = () => {
const wallet = sequence.getWallet()
wallet.closeWallet()
}
const isConnected = async () => {
resetConsole()
const wallet = sequence.getWallet()
appendConsoleLine(`isConnected?: ${wallet.isConnected()}`)
setConsoleLoading(false)
}
const isOpened = async () => {
resetConsole()
const wallet = sequence.getWallet()
appendConsoleLine(`isOpened?: ${wallet.isOpened()}`)
setConsoleLoading(false)
}
const getChainID = async () => {
try {
resetConsole()
const topChainId = wallet.getChainId()
appendConsoleLine(`top chainId: ${topChainId}`)
const provider = wallet.getProvider()
const providerChainId = provider!.getChainId()
appendConsoleLine(`provider.getChainId(): ${providerChainId}`)
const signer = wallet.getSigner()
const signerChainId = await signer.getChainId()
appendConsoleLine(`signer.getChainId(): ${signerChainId}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const getAccounts = async () => {
try {
resetConsole()
const wallet = sequence.getWallet()
const address = wallet.getAddress()
appendConsoleLine(`getAddress(): ${address}`)
const provider = wallet.getProvider()
const accountList = provider.listAccounts()
appendConsoleLine(`accounts: ${JSON.stringify(accountList)}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const getBalance = async () => {
try {
resetConsole()
const wallet = sequence.getWallet()
const provider = wallet.getProvider()
const account = wallet.getAddress()
const balanceChk1 = await provider!.getBalance(account)
appendConsoleLine(`balance check 1: ${balanceChk1.toString()}`)
const signer = wallet.getSigner()
const balanceChk2 = await signer.getBalance()
appendConsoleLine(`balance check 2: ${balanceChk2.toString()}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const getNetworks = async () => {
try {
resetConsole()
const wallet = sequence.getWallet()
const networks = await wallet.getNetworks()
appendConsoleLine(`networks: ${JSON.stringify(networks, null, 2)}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const signMessageString = async () => {
try {
resetConsole()
const wallet = sequence.getWallet()
appendConsoleLine('signing message...')
const signer = wallet.getSigner()
const message = `1915 Robert Frost
The Road Not Taken
Two roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth
Then took the other, as just as fair,
And having perhaps the better claim,
Because it was grassy and wanted wear
Though as for that the passing there
Had worn them really about the same,
And both that morning equally lay
In leaves no step had trodden black.
Oh, I kept the first for another day!
Yet knowing how way leads on to way,
I doubted if I should ever come back.
I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I—
I took the one less traveled by,
And that has made all the difference.
\u2601 \u2600 \u2602`
// sign
const sig = await signer.signMessage(message)
appendConsoleLine(`signature: ${sig}`)
const isValid = await wallet.utils.isValidMessageSignature(wallet.getAddress(), message, sig, await signer.getChainId())
appendConsoleLine(`isValid?: ${isValid}`)
if (!isValid) throw new Error('sig invalid')
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const signMessageHex = async () => {
try {
resetConsole()
const wallet = sequence.getWallet()
appendConsoleLine('signing message...')
const signer = wallet.getSigner()
// Message in hex
const message = ethers.hexlify(ethers.toUtf8Bytes('Hello, world!'))
// sign
const sig = await signer.signMessage(message)
appendConsoleLine(`signature: ${sig}`)
const isValid = await wallet.utils.isValidMessageSignature(wallet.getAddress(), message, sig, await signer.getChainId())
appendConsoleLine(`isValid?: ${isValid}`)
if (!isValid) throw new Error('sig invalid')
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const signMessageBytes = async () => {
try {
resetConsole()
const wallet = sequence.getWallet()
appendConsoleLine('signing message...')
const signer = wallet.getSigner()
// Message in hex
const message = ethers.toUtf8Bytes('Hello, world!')
// sign
const sig = await signer.signMessage(message)
appendConsoleLine(`signature: ${sig}`)
const isValid = await wallet.utils.isValidMessageSignature(wallet.getAddress(), message, sig, await signer.getChainId())
appendConsoleLine(`isValid?: ${isValid}`)
if (!isValid) throw new Error('sig invalid')
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const signTypedData = async () => {
try {
resetConsole()
const wallet = sequence.getWallet()
appendConsoleLine('signing typedData...')
const typedData: sequence.utils.TypedData = {
types: {
Person: [
{ name: 'name', type: 'string' },
{ name: 'wallet', type: 'address' }
],
Mail: [
{ name: 'from', type: 'Person' },
{ name: 'to', type: 'Person' },
{ name: 'cc', type: 'Person[]' },
{ name: 'contents', type: 'string' },
{ name: 'attachements', type: 'string[]' }
]
},
primaryType: 'Mail',
domain: {
name: 'Ether Mail',
version: '1',
chainId: 1,
verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC'
},
message: {
from: {
name: 'Cow',
wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826'
},
to: {
name: 'Bob',
wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB'
},
cc: [
{ name: 'Dev Team', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB' },
{ name: 'Accounting', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB' }
],
contents: 'Hello, Bob!',
attachements: ['cat.png', 'dog.png']
}
}
const signer = wallet.getSigner()
const sig = await signer.signTypedData(typedData.domain, typedData.types, typedData.message)
appendConsoleLine(`signature: ${sig}`)
// validate
const isValid = await wallet.utils.isValidTypedDataSignature(wallet.getAddress(), typedData, sig, await signer.getChainId())
appendConsoleLine(`isValid?: ${isValid}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const estimateUnwrapGas = async () => {
try {
resetConsole()
const wallet = sequence.getWallet()
const wmaticContractAddress = '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270'
const wmaticInterface = new ethers.Interface(['function withdraw(uint256 amount)'])
const tx: sequence.transactions.Transaction = {
to: wmaticContractAddress,
data: wmaticInterface.encodeFunctionData('withdraw', ['1000000000000000000'])
}
const provider = wallet.getProvider()
const estimate = await provider.estimateGas(tx)
appendConsoleLine(`estimated gas needed for wmatic withdrawal : ${estimate.toString()}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const sendETH = async (signer?: sequence.provider.SequenceSigner) => {
try {
resetConsole()
const wallet = sequence.getWallet()
signer = signer || wallet.getSigner()
appendConsoleLine(`Transfer txn on ${signer.getChainId()} chainId`)
// NOTE: on mainnet, the balance will be of ETH value
// and on matic, the balance will be of MATIC value
// Sending the funds to the wallet itself
// so we don't lose any funds ;-)
// (of course, you can send anywhere)
const toAddress = await signer.getAddress()
const tx1: sequence.transactions.Transaction = {
delegateCall: false,
revertOnError: false,
gasLimit: '0x55555',
to: toAddress,
value: ethers.parseEther('1.234'),
data: '0x'
}
const tx2: sequence.transactions.Transaction = {
delegateCall: false,
revertOnError: false,
gasLimit: '0x55555',
to: toAddress,
value: ethers.parseEther('0.4242'),
data: '0x'
}
const provider = signer.provider
const balance1 = await provider.getBalance(toAddress)
appendConsoleLine(`balance of ${toAddress}, before: ${balance1}`)
const txnResp = await signer.sendTransaction([tx1, tx2])
appendConsoleLine(`txnResponse: ${JSON.stringify(txnResp)}`)
const balance2 = await provider.getBalance(toAddress)
appendConsoleLine(`balance of ${toAddress}, after: ${balance2}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const sendSepoliaUSDC = async (signer?: sequence.provider.SequenceSigner) => {
try {
resetConsole()
const wallet = sequence.getWallet()
signer = signer || wallet.getSigner() // select DefaultChain signer by default
// Sending the funds to the wallet itself
// so we don't lose any funds ;-)
// (of course, you can send anywhere)
const toAddress = await signer.getAddress()
const amount = ethers.parseUnits('1', 1)
// (USDC address on Sepolia)
const usdcAddress = '0x07865c6e87b9f70255377e024ace6630c1eaa37f'
const tx: sequence.transactions.Transaction = {
delegateCall: false,
revertOnError: false,
gasLimit: '0x55555',
to: usdcAddress,
value: 0,
data: new ethers.Interface(ERC_20_ABI).encodeFunctionData('transfer', [toAddress, toHexString(amount)])
}
const txnResp = await signer.sendTransaction([tx], { chainId: ChainId.SEPOLIA })
appendConsoleLine(`txnResponse: ${JSON.stringify(txnResp)}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const sendDAI = async (signer?: sequence.provider.SequenceSigner) => {
try {
resetConsole()
const wallet = sequence.getWallet()
signer = signer || wallet.getSigner() // select DefaultChain signer by default
// Sending the funds to the wallet itself
// so we don't lose any funds ;-)
// (of course, you can send anywhere)
const toAddress = await signer.getAddress()
const amount = ethers.parseUnits('0.05', 18)
const daiContractAddress = '0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063' // (DAI address on Polygon)
const tx: sequence.transactions.Transaction = {
delegateCall: false,
revertOnError: false,
gasLimit: '0x55555',
to: daiContractAddress,
value: 0,
data: new ethers.Interface(ERC_20_ABI).encodeFunctionData('transfer', [toAddress, toHexString(amount)])
}
const txnResp = await signer.sendTransaction([tx])
appendConsoleLine(`txnResponse: ${JSON.stringify(txnResp)}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const sendETHSidechain = async () => {
try {
const wallet = sequence.getWallet()
// Send either to Arbitrum or Optimism
// just pick one that is not the current chainId
const pick = wallet.getChainId() === ChainId.ARBITRUM ? ChainId.OPTIMISM : ChainId.ARBITRUM
sendETH(wallet.getSigner(pick))
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const send1155Tokens = async () => {
try {
resetConsole()
appendConsoleLine('TODO')
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const contractExample = async (signer?: sequence.provider.SequenceSigner) => {
try {
resetConsole()
const wallet = sequence.getWallet()
signer = signer || wallet.getSigner()
const abi = [
'function balanceOf(address owner) view returns (uint256)',
'function decimals() view returns (uint8)',
'function symbol() view returns (string)',
'function transfer(address to, uint amount) returns (bool)',
'event Transfer(address indexed from, address indexed to, uint amount)'
]
// USD Coin (PoS) on Polygon
const address = '0x2791bca1f2de4661ed88a30c99a7a9449aa84174'
const usdc = new ethers.Contract(address, abi)
const usdSymbol = await usdc.symbol()
appendConsoleLine(`Token symbol: ${usdSymbol}`)
const balance = await usdc.balanceOf(await signer.getAddress())
appendConsoleLine(`Token Balance: ${balance.toString()}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const fetchTokenBalances = async () => {
try {
resetConsole()
const wallet = sequence.getWallet()
const signer = wallet.getSigner()
const accountAddress = await signer.getAddress()
const networks = await wallet.getNetworks()
const network = networks.find(network => network.chainId === ChainId.POLYGON)
if (!network) {
throw new Error(`Could not find Polygon network in networks list`)
}
const indexer = new sequence.indexer.SequenceIndexer(network.indexerUrl)
const tokenBalances = await indexer.getTokenBalances({
accountAddress: accountAddress,
includeMetadata: true
})
appendConsoleLine(`tokens in your account: ${JSON.stringify(tokenBalances)}`)
// NOTE: you can put any NFT/collectible address in the `contractAddress` field and it will return all of the balances + metadata.
// We use the Skyweaver production contract address here for demo purposes, but try another one :)
const skyweaverCollectibles = await indexer.getTokenBalances({
accountAddress: accountAddress,
includeMetadata: true,
contractAddress: '0x631998e91476DA5B870D741192fc5Cbc55F5a52E'
})
appendConsoleLine(`skyweaver collectibles in your account: ${JSON.stringify(skyweaverCollectibles)}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const updateImplementation = async (signer?: sequence.provider.SequenceSigner) => {
try {
resetConsole()
const wallet = sequence.getWallet()
signer = signer || wallet.getSigner() // select DefaultChain signer by default
const transaction: sequence.transactions.Transaction = {
to: wallet.getAddress(),
data: new ethers.Interface(walletContracts.mainModule.abi).encodeFunctionData('updateImplementation', [
ethers.ZeroAddress
])
}
const response = await signer.sendTransaction(transaction)
appendConsoleLine(`response: ${JSON.stringify(response)}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const updateImageHash = async (signer?: sequence.provider.SequenceSigner) => {
try {
resetConsole()
const wallet = sequence.getWallet()
signer = signer || wallet.getSigner() // select DefaultChain signer by default
const transaction: sequence.transactions.Transaction = {
to: wallet.getAddress(),
data: new ethers.Interface(walletContracts.mainModuleUpgradable.abi).encodeFunctionData('updateImageHash', [
ethers.ZeroHash
])
}
const response = await signer.sendTransaction(transaction)
appendConsoleLine(`response: ${JSON.stringify(response)}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const delegateCall = async (signer?: sequence.provider.SequenceSigner) => {
try {
resetConsole()
const wallet = sequence.getWallet()
signer = signer || wallet.getSigner() // select DefaultChain signer by default
const transaction: sequence.transactions.Transaction = {
to: wallet.getAddress(),
delegateCall: true
}
const response = await signer.sendTransaction(transaction)
appendConsoleLine(`response: ${JSON.stringify(response)}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const addHook = async (signer?: sequence.provider.SequenceSigner) => {
try {
resetConsole()
const wallet = sequence.getWallet()
signer = signer || wallet.getSigner() // select DefaultChain signer by default
const transaction: sequence.transactions.Transaction = {
to: wallet.getAddress(),
data: new ethers.Interface(['function addHook(bytes4 _signature, address _implementation)']).encodeFunctionData(
'addHook',
['0x01234567', ethers.ZeroAddress]
)
}
const response = await signer.sendTransaction(transaction)
appendConsoleLine(`response: ${JSON.stringify(response)}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const setExtraImageHash = async (signer?: sequence.provider.SequenceSigner) => {
try {
resetConsole()
const wallet = sequence.getWallet()
signer = signer || wallet.getSigner() // select DefaultChain signer by default
const transaction: sequence.transactions.Transaction = {
to: wallet.getAddress(),
data: new ethers.Interface(['function setExtraImageHash(bytes32 _imageHash, uint256 _expiration)']).encodeFunctionData(
'setExtraImageHash',
[ethers.ZeroHash, ethers.MaxUint256]
)
}
const response = await signer.sendTransaction(transaction)
appendConsoleLine(`response: ${JSON.stringify(response)}`)
setConsoleLoading(false)
} catch (e) {
console.error(e)
consoleErrorMessage()
}
}
const appendConsoleLine = (message: string, clear = false) => {
console.log(message)
if (clear) {
return setConsoleMsg(message)
}
return setConsoleMsg(prevState => {
return `${prevState}\n\n${message}`
})
}
const resetConsole = () => {
setConsoleLoading(true)
}
const consoleWelcomeMessage = () => {
setConsoleLoading(false)
if (isWalletConnected) {
setConsoleMsg('Status: Wallet is connected :)')
} else {
setConsoleMsg('Status: Wallet not connected. Please connect wallet first.')
}
}
const consoleErrorMessage = () => {
setConsoleLoading(false)
setConsoleMsg('An error occurred')
}
// networks list, filtered and sorted
const omitNetworks = [
ChainId.RINKEBY,
ChainId.HARDHAT,
ChainId.HARDHAT_2,
ChainId.KOVAN,
ChainId.ROPSTEN,
ChainId.HOMEVERSE_TESTNET,
ChainId.BASE_GOERLI
]
const mainnets = Object.values(sequence.network.networks)
.filter(network => network.type === NetworkType.MAINNET)
.sort((a, b) => a.chainId - b.chainId)
const testnets = Object.values(sequence.network.networks)
.filter(network => network.type === NetworkType.TESTNET)
.sort((a, b) => a.chainId - b.chainId)
const networks = [...mainnets, ...testnets].filter(network => !network.deprecated && !omitNetworks.includes(network.chainId))
useEffect(() => {
if (email && !isOpen) {
console.log(email)
connect({
app: 'Demo Dapp',
authorize: true,
settings: {
// Specify signInWithEmail with an email address to allow user automatically sign in with the email option.
signInWithEmail: email,
theme: 'dark',
bannerUrl: `${window.location.origin}${skyweaverBannerUrl}`
}
})
setEmail(null)
}
}, [email, isOpen])
const sanitizeEmail = (email: string) => {
// Trim unnecessary spaces
email = email.trim()
// Check if the email matches the pattern of a typical email
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
if (emailRegex.test(email)) {
return true
}
return false
}
return (
<Box marginY="0" marginX="auto" paddingX="6" style={{ maxWidth: '720px', marginTop: '80px', marginBottom: '80px' }}>
<Box marginBottom="10">
<a href="https://sequence.xyz/" target="_blank" rel="noopener">
<Image height="6" alt="logo" src={logoUrl} />
</a>
</Box>
<Box>
<Text variant="normal" color="text100" fontWeight="bold">
Demo Dapp
</Text>
</Box>
<Box marginTop="1" marginBottom="4">
<Text variant="normal" color="text80">
A dapp example on how to use the Sequence Wallet. This covers how to connect, sign messages and send transctions.
</Text>
</Box>
<Card background="backgroundMuted" alignItems="center" gap="3">
<TransactionIcon />
<Text variant="normal" color="text80">
Please open your browser dev inspector to view output of functions below.
</Text>
</Card>
<Divider background="buttonGlass" />
<Box marginBottom="4">
<Select
name="environment"
label={'Environment'}
labelLocation="top"