-
Notifications
You must be signed in to change notification settings - Fork 64
/
WalletConnectCommunicationClient.ts
1346 lines (1170 loc) · 40.2 KB
/
WalletConnectCommunicationClient.ts
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 {
BEACON_VERSION,
CommunicationClient,
Serializer,
ClientEvents,
Logger,
WCStorage
} from '@airgap/beacon-core'
import { SignClient } from '@walletconnect/sign-client'
import Client from '@walletconnect/sign-client'
import { IPairing, ProposalTypes, SessionTypes, SignClientTypes } from '@walletconnect/types'
import { getSdkError } from '@walletconnect/utils'
import {
ActiveAccountUnspecified,
ActiveNetworkUnspecified,
InvalidNetworkOrAccount,
InvalidReceivedSessionNamespace,
InvalidSession,
MissingRequiredScope,
NotConnected
} from '../error'
import {
AcknowledgeResponseInput,
BeaconBaseMessage,
BeaconErrorType,
BeaconMessageType,
BeaconResponseInputMessage,
ChangeAccountRequest,
DisconnectMessage,
ErrorResponse,
ErrorResponseInput,
ExtendedWalletConnectPairingRequest,
ExtendedWalletConnectPairingResponse,
IgnoredResponseInputProperties,
Network,
NetworkType,
OperationRequest,
OperationResponseInput,
Optional,
PermissionRequest,
PermissionResponseInput,
PermissionScope,
SignPayloadRequest,
SignPayloadResponse,
SignPayloadResponseInput,
StorageKey,
TransportType
} from '@airgap/beacon-types'
import { generateGUID, getAddressFromPublicKey } from '@airgap/beacon-utils'
const TEZOS_PLACEHOLDER = 'tezos'
const logger = new Logger('WalletConnectCommunicationClient')
export interface PermissionScopeParam {
networks: NetworkType[]
methods: PermissionScopeMethods[]
events?: PermissionScopeEvents[]
}
export enum PermissionScopeMethods {
GET_ACCOUNTS = 'tezos_getAccounts',
OPERATION_REQUEST = 'tezos_send',
SIGN = 'tezos_sign'
}
export enum PermissionScopeEvents {
CHAIN_CHANGED = 'chainChanged',
ACCOUNTS_CHANGED = 'accountsChanged',
REQUEST_ACKNOWLEDGED = 'requestAcknowledged'
}
type BeaconInputMessage =
| BeaconResponseInputMessage
| Optional<DisconnectMessage, IgnoredResponseInputProperties>
| Optional<ChangeAccountRequest, IgnoredResponseInputProperties>
function getStringBetween(str: string | undefined, startChar: string, endChar: string): string {
if (!str || !startChar || !endChar) {
return ''
}
const startIndex = str.indexOf(startChar)
const endIndex = str.indexOf(endChar, startIndex + 1)
if (startIndex === -1 || endIndex === -1) {
throw new Error('String not found')
}
return str.substring(startIndex + 1, endIndex)
}
export class WalletConnectCommunicationClient extends CommunicationClient {
protected readonly activeListeners: Map<string, (message: string) => void> = new Map()
protected readonly channelOpeningListeners: Map<
string,
(pairingResponse: ExtendedWalletConnectPairingResponse) => void
> = new Map()
private static instance: WalletConnectCommunicationClient
public signClient: Client | undefined
public storage: WCStorage = new WCStorage()
private session: SessionTypes.Struct | undefined
private activeAccount: string | undefined
private activeNetwork: string | undefined
readonly disconnectionEvents: Set<string> = new Set()
private pingInterval: NodeJS.Timeout | undefined
/**
* this queue stores each active message id
* [0] newest message
* [length - 1] oldest message
*/
private messageIds: string[] = []
constructor(private wcOptions: { network: NetworkType; opts: SignClientTypes.Options }) {
super()
this.getSignClient()
this.storage.onMessageHandler = this.onStorageMessageHandler.bind(this)
this.storage.onErrorHandler = this.onStorageErrorHandler.bind(this)
}
static getInstance(wcOptions: {
network: NetworkType
opts: SignClientTypes.Options
}): WalletConnectCommunicationClient {
if (!WalletConnectCommunicationClient.instance) {
WalletConnectCommunicationClient.instance = new WalletConnectCommunicationClient(wcOptions)
}
return WalletConnectCommunicationClient.instance
}
private getTopicFromSession(session: SessionTypes.Struct): string {
return session.pairingTopic?.length ? session.pairingTopic : session.topic
}
public async listenForEncryptedMessage(
senderPublicKey: string,
messageCallback: (message: string) => void
): Promise<void> {
if (this.activeListeners.has(senderPublicKey)) {
return
}
const callbackFunction = async (message: string): Promise<void> => {
messageCallback(message)
}
this.activeListeners.set(senderPublicKey, callbackFunction)
}
public async listenForChannelOpening(
messageCallback: (pairingResponse: ExtendedWalletConnectPairingResponse) => void
): Promise<void> {
const callbackFunction = async (
pairingResponse: ExtendedWalletConnectPairingResponse
): Promise<void> => {
messageCallback(pairingResponse)
}
this.channelOpeningListeners.set('channelOpening', callbackFunction)
}
/**
* WC Sign client doesn't sync between intances, meaning that a dApp signClient instance state may
* differ from a wallet state
*/
private async refreshState() {
this.clearEvents()
this.signClient = undefined
const client = await this.getSignClient()
const sessions = client?.session.getAll() ?? []
try {
this.session =
sessions?.find((el) => el.topic === this.session?.topic) ?? sessions[0] ?? this.session
this.session && (this.activeAccount = this.getAccounts()[0])
} catch (err: any) {
logger.error('refreshState', err.message)
}
}
private clearEvents() {
this.signClient?.removeAllListeners('session_event')
this.signClient?.removeAllListeners('session_update')
this.signClient?.removeAllListeners('session_delete')
this.signClient?.removeAllListeners('session_expire')
this.signClient?.core.pairing.events.removeAllListeners('pairing_delete')
this.signClient?.core.pairing.events.removeAllListeners('pairing_expire')
}
private onStorageMessageHandler(type: string) {
logger.debug('onStorageMessageHandler', type)
this.refreshState()
if (type === 'CLEAR_ACTIVE_ACCOUNT') {
if (this.messageIds.length) {
const errorResponse: any = {
type: BeaconMessageType.Disconnect,
id: this.messageIds.pop(),
errorType: BeaconErrorType.ABORTED_ERROR
}
this.session && this.notifyListeners(this.getTopicFromSession(this.session), errorResponse)
this.messageIds = [] // reset
}
this.session = undefined
this.activeAccount = undefined
return
}
}
private onStorageErrorHandler(data: any) {
logger.error('onStorageError', data)
}
async unsubscribeFromEncryptedMessages(): Promise<void> {
// implementation
}
async unsubscribeFromEncryptedMessage(_senderPublicKey: string): Promise<void> {
// implementation
}
private ping(target: Client | IPairing, topic: string) {
target
.ping({ topic })
.then(() => {
if (this.messageIds.length) {
this.acknowledgeRequest(this.messageIds[0])
}
})
.catch((error) => {
logger.error(`ping catch handler: ${error.message}`)
})
.then(() => {
clearInterval(this.pingInterval)
this.pingInterval = undefined
})
}
private checkWalletReadiness(topic: string) {
const target = this.signClient?.pairing.getAll().some((el) => el.topic === topic)
? this.signClient?.core.pairing
: this.signClient
if (!target || this.pingInterval) {
return
}
this.ping(target, topic)
this.pingInterval = setInterval(() => {
this.ping(target, topic)
}, 30000)
}
async sendMessage(_message: string, _peer?: any): Promise<void> {
const serializer = new Serializer()
const message = (await serializer.deserialize(_message)) as any
if (!message) {
return
}
this.messageIds.unshift(message.id)
switch (message.type) {
case BeaconMessageType.PermissionRequest:
this.requestPermissions(message)
break
case BeaconMessageType.OperationRequest:
this.sendOperations(message)
break
case BeaconMessageType.SignPayloadRequest:
this.signPayload(message)
break
default:
return
}
}
private async fetchAccounts(topic: string, chainId: string) {
const signClient = await this.getSignClient()
if (!signClient) {
return
}
return signClient.request<
[
{
algo: 'ed25519'
address: string
pubkey: string
}
]
>({
topic: topic,
chainId: chainId,
request: {
method: PermissionScopeMethods.GET_ACCOUNTS,
params: {}
}
})
}
private async notifyListenersWithPermissionResponse(
session: SessionTypes.Struct,
network: Network
) {
let publicKey: string | undefined
if (
session.sessionProperties?.pubkey &&
session.sessionProperties?.algo &&
session.sessionProperties?.address
) {
publicKey = session.sessionProperties?.pubkey
logger.log(
'[requestPermissions]: Have pubkey in sessionProperties, skipping "get_accounts" call',
session.sessionProperties
)
} else {
const accounts = this.getTezosNamespace(session.namespaces).accounts
const addressOrPbk = accounts[0].split(':', 3)[2]
if (addressOrPbk.startsWith('edpk')) {
publicKey = addressOrPbk
} else {
if (network.type !== this.wcOptions.network) {
throw new Error('Network in permission request is not the same as preferred network!')
}
const result = await this.fetchAccounts(
session.topic,
`${TEZOS_PLACEHOLDER}:${network.type}`
)
if (!result || result.length < 1) {
throw new Error('No account shared by wallet')
}
if (result.some((account) => !account.pubkey)) {
throw new Error('Public Key in `tezos_getAccounts` is empty!')
}
publicKey = result[0]?.pubkey
}
}
if (!publicKey) {
throw new Error('Public Key in `tezos_getAccounts` is empty!')
}
const permissionResponse: PermissionResponseInput = {
type: BeaconMessageType.PermissionResponse,
appMetadata: {
senderId: this.getTopicFromSession(session),
name: session.peer.metadata.name,
icon: session.peer.metadata.icons[0]
},
publicKey,
network,
scopes: [PermissionScope.SIGN, PermissionScope.OPERATION_REQUEST],
id: this.messageIds.pop() ?? '',
walletType: 'implicit'
}
this.notifyListeners(this.getTopicFromSession(session), permissionResponse)
}
async requestPermissions(message: PermissionRequest) {
logger.log('#### Requesting permissions')
if (!this.getPermittedMethods().includes(PermissionScopeMethods.GET_ACCOUNTS)) {
throw new MissingRequiredScope(PermissionScopeMethods.GET_ACCOUNTS)
}
if (this.activeAccount) {
try {
await this.openSession()
} catch (error: any) {
logger.error(error.message)
return
}
}
this.setDefaultAccountAndNetwork()
this.notifyListenersWithPermissionResponse(this.getSession(), message.network)
}
/**
* @description Once the session is establish, send payload to be approved and signed by the wallet.
* @error MissingRequiredScope is thrown if permission to sign payload was not granted
*/
async signPayload(signPayloadRequest: SignPayloadRequest) {
const signClient = await this.getSignClient()
if (!signClient) {
return
}
const session = this.getSession()
if (!this.getPermittedMethods().includes(PermissionScopeMethods.SIGN)) {
throw new MissingRequiredScope(PermissionScopeMethods.SIGN)
}
const network = this.getActiveNetwork()
const account = await this.getPKH()
this.validateNetworkAndAccount(network, account)
this.checkWalletReadiness(this.getTopicFromSession(session))
// TODO: Type
signClient
.request<{ signature: string }>({
topic: session.topic,
chainId: `${TEZOS_PLACEHOLDER}:${network}`,
request: {
method: PermissionScopeMethods.SIGN,
params: {
account: account,
payload: signPayloadRequest.payload
}
}
})
.then((response) => {
const signPayloadResponse: SignPayloadResponseInput = {
type: BeaconMessageType.SignPayloadResponse,
signingType: signPayloadRequest.signingType,
signature: response?.signature,
id: this.messageIds.pop()
} as SignPayloadResponse
this.notifyListeners(this.getTopicFromSession(session), signPayloadResponse)
if (this.session && this.messageIds.length) {
this.checkWalletReadiness(this.getTopicFromSession(session))
}
})
.catch(async () => {
const errorResponse: ErrorResponseInput = {
type: BeaconMessageType.Error,
id: this.messageIds.pop(),
errorType: BeaconErrorType.ABORTED_ERROR
} as ErrorResponse
this.notifyListeners(this.getTopicFromSession(session), errorResponse)
if (this.session && this.messageIds.length) {
this.checkWalletReadiness(this.getTopicFromSession(session))
}
})
}
/**
* @description Once the session is established, send Tezos operations to be approved, signed and inject by the wallet.
* @error MissingRequiredScope is thrown if permission to send operation was not granted
*/
async sendOperations(operationRequest: OperationRequest) {
const signClient = await this.getSignClient()
if (!signClient) {
return
}
const session = this.getSession()
if (!this.getPermittedMethods().includes(PermissionScopeMethods.OPERATION_REQUEST)) {
throw new MissingRequiredScope(PermissionScopeMethods.OPERATION_REQUEST)
}
const network = this.getActiveNetwork()
const account = await this.getPKH()
this.validateNetworkAndAccount(network, account)
this.checkWalletReadiness(this.getTopicFromSession(session))
signClient
.request<{
// The `operationHash` field should be provided to specify the operation hash,
// while the `transactionHash` and `hash` fields are supported for backwards compatibility.
operationHash?: string
transactionHash?: string
hash?: string
}>({
topic: session.topic,
chainId: `${TEZOS_PLACEHOLDER}:${network}`,
request: {
method: PermissionScopeMethods.OPERATION_REQUEST,
params: {
account,
operations: operationRequest.operationDetails
}
}
})
.then((response) => {
const sendOperationResponse: OperationResponseInput = {
type: BeaconMessageType.OperationResponse,
transactionHash:
response.operationHash ?? response.transactionHash ?? response.hash ?? '',
id: this.messageIds.pop() ?? ''
}
this.notifyListeners(this.getTopicFromSession(session), sendOperationResponse)
if (this.session && this.messageIds.length) {
this.checkWalletReadiness(this.getTopicFromSession(session))
}
})
.catch(async () => {
const errorResponse: ErrorResponseInput = {
type: BeaconMessageType.Error,
id: this.messageIds.pop(),
errorType: BeaconErrorType.ABORTED_ERROR
} as ErrorResponse
this.notifyListeners(this.getTopicFromSession(session), errorResponse)
if (this.session && this.messageIds.length) {
this.checkWalletReadiness(this.getTopicFromSession(session))
}
})
}
private isMobileSesion(session: SessionTypes.Struct): boolean {
const redirect = session.peer.metadata.redirect
return (
!!redirect &&
!!redirect.native &&
!redirect.native.includes('http') &&
!redirect.native.includes('ws')
)
}
/**
* Function used to fix appSwitching with web wallets when pairing through 'Other wallet flow'
* @param session the newly created session
*/
private updateStorageWallet(session: SessionTypes.Struct): void {
const selectedWallet = JSON.parse(localStorage.getItem(StorageKey.LAST_SELECTED_WALLET) ?? '{}')
if (!selectedWallet.key) {
return
}
if (this.isMobileSesion(session)) {
selectedWallet.type = 'mobile'
} else {
selectedWallet.type = 'web'
}
localStorage.setItem(StorageKey.LAST_SELECTED_WALLET, JSON.stringify(selectedWallet))
}
public async init(
forceNewConnection: boolean = false
): Promise<{ uri: string; topic: string } | undefined> {
logger.warn('init')
this.disconnectionEvents.size && this.disconnectionEvents.clear()
if (forceNewConnection) {
await this.closePairings()
}
const signClient = await this.getSignClient()
if (!signClient) {
const fun = this.eventHandlers.get(ClientEvents.CLOSE_ALERT)
fun && fun()
return
}
const sessions = signClient.session.getAll()
if (sessions && sessions.length > 0) {
this.session = sessions[0]
this.setDefaultAccountAndNetwork()
this.updateStorageWallet(this.session)
return undefined
}
logger.warn('before create')
const permissionScopeParams: PermissionScopeParam = {
networks: [this.wcOptions.network],
events: [],
methods: [
PermissionScopeMethods.GET_ACCOUNTS,
PermissionScopeMethods.OPERATION_REQUEST,
PermissionScopeMethods.SIGN
]
}
const optionalPermissionScopeParams: PermissionScopeParam = {
networks: [this.wcOptions.network],
events: [PermissionScopeEvents.REQUEST_ACKNOWLEDGED],
methods: []
}
const connectParams = {
requiredNamespaces: {
[TEZOS_PLACEHOLDER]: this.permissionScopeParamsToNamespaces(permissionScopeParams)
},
optionalNamespaces: {
[TEZOS_PLACEHOLDER]: this.permissionScopeParamsToNamespaces(optionalPermissionScopeParams)
}
}
const { uri, approval } = await signClient.connect(connectParams)
// Extract topic from uri. Format is wc:topic@2...
const topic = getStringBetween(uri, ':', '@')
if (!topic) {
return
}
let hasResponse = false
signClient.core.pairing
.ping({ topic })
.then(async () => {
if (!hasResponse) {
// Only show "waiting for acknowledge" message if pong arrives before response
const fun = this.eventHandlers.get(ClientEvents.WC_ACK_NOTIFICATION)
fun && fun('pending')
}
})
.catch((err) => {
console.error('--------', err)
})
approval()
.then((session) => {
logger.debug('session open')
hasResponse = true
this.updateStorageWallet(session)
const pairingResponse: ExtendedWalletConnectPairingResponse =
new ExtendedWalletConnectPairingResponse(
session.topic,
session.peer.metadata.name,
session.peer.publicKey,
'3',
session.topic,
session.peer.metadata.name
)
this.channelOpeningListeners.forEach((listener) => {
listener(pairingResponse)
})
if (session?.controller !== this.session?.controller) {
logger.debug('Controller doesnt match, closing active session', [session.pairingTopic])
this.activeAccount && this.closeActiveSession(this.activeAccount)
this.session = undefined // close the previous session
}
// We need this check in the event the user aborts the sync process on the wallet side
// but there is already a connection set
this.session = this.session ?? session
logger.debug('Session is now', [session.pairingTopic])
this.validateReceivedNamespace(permissionScopeParams, this.session.namespaces)
})
.catch(async (error: any) => {
hasResponse = true
if (
!error.message ||
!error.message.length ||
error.message.toLowerCase().includes('expir')
) {
const fun = this.eventHandlers.get(ClientEvents.CLOSE_ALERT)
fun && fun(TransportType.WALLETCONNECT)
return
}
logger.error('Error happened!', [error.message])
if (this.activeListeners.size === 0) {
logger.debug('No active listeners', [])
const fun = this.eventHandlers.get(ClientEvents.WC_ACK_NOTIFICATION)
fun && fun('error')
} else {
const _pairingTopic = topic ?? signClient.core.pairing.getPairings()[0]?.topic
logger.debug('New pairing topic?', [])
const errorResponse: ErrorResponseInput = {
type: BeaconMessageType.Error,
id: this.messageIds.pop(),
errorType: BeaconErrorType.ABORTED_ERROR
} as ErrorResponse
this.notifyListeners(_pairingTopic, errorResponse)
}
})
logger.warn('return uri and topic')
return { uri: uri ?? '', topic: topic }
}
public async close() {
this.storage.backup()
await this.closePairings()
}
private subscribeToSessionEvents(signClient: Client): void {
signClient.on('session_event', (event) => {
if (
event.params.event.name === PermissionScopeEvents.REQUEST_ACKNOWLEDGED &&
this.messageIds.length
) {
this.acknowledgeRequest(this.messageIds[0])
}
})
signClient.on('session_update', (event) => {
this.disconnectionEvents.add('session_update')
const session = signClient.session.get(event.topic)
if (!session) {
logger.warn('session_update', 'topic does not exist')
return
}
this.session = session
this.updateActiveAccount(event.params.namespaces)
this.notifyListenersWithPermissionResponse(this.session, {
type: this.wcOptions.network
})
})
signClient.on('session_delete', (event) => {
this.disconnectionEvents.add('session_delete')
this.disconnect(signClient, { type: 'session', topic: event.topic })
})
signClient.on('session_expire', (event) => {
this.disconnectionEvents.add('session_expire')
this.disconnect(signClient, { type: 'session', topic: event.topic })
})
signClient.core.pairing.events.on('pairing_delete', (event) => {
this.disconnectionEvents.add('pairing_delete')
this.disconnect(signClient, { type: 'pairing', topic: event.topic })
})
signClient.core.pairing.events.on('pairing_expire', (event) => {
this.disconnectionEvents.add('pairing_expire')
this.disconnect(signClient, { type: 'pairing', topic: event.topic })
})
}
private async acknowledgeRequest(id: string) {
const session = this.getSession()
const acknowledgeResponse: AcknowledgeResponseInput = {
type: BeaconMessageType.Acknowledge,
id
}
this.notifyListeners(this.getTopicFromSession(session), acknowledgeResponse)
}
private async updateActiveAccount(namespaces: SessionTypes.Namespaces) {
try {
const accounts = this.getTezosNamespace(namespaces).accounts
if (accounts.length) {
const [_namespace, chainId, addressOrPbk] = accounts[0].split(':', 3)
const session = this.getSession()
let publicKey: string | undefined
this.activeNetwork = chainId
if (addressOrPbk.startsWith('edpk')) {
publicKey = addressOrPbk
this.activeAccount = await getAddressFromPublicKey(publicKey)
} else {
this.activeAccount = addressOrPbk
const result = await this.fetchAccounts(session.topic, `${TEZOS_PLACEHOLDER}:${chainId}`)
publicKey = result?.find(({ address: _address }) => addressOrPbk === _address)?.pubkey
}
if (!publicKey) {
throw new Error('Public key for the new account not provided')
}
this.notifyListeners(this.getTopicFromSession(session), {
id: await generateGUID(),
type: BeaconMessageType.ChangeAccountRequest,
publicKey,
network: { type: chainId as NetworkType },
scopes: [PermissionScope.SIGN, PermissionScope.OPERATION_REQUEST],
walletType: 'implicit'
})
}
} catch {}
}
private async disconnect(
signClient: Client,
trigger: { type: 'session'; topic: string } | { type: 'pairing'; topic: string }
) {
let session
if (trigger.type === 'session') {
session = await this.onSessionClosed(signClient, trigger.topic)
}
if (trigger.type === 'pairing') {
session = await this.onPairingClosed(signClient, trigger.topic)
}
if (!this.activeAccount) {
const fun = this.eventHandlers.get(ClientEvents.RESET_STATE)
fun && fun(TransportType.WALLETCONNECT)
}
if (!session) {
return
}
this.notifyListeners(this.getTopicFromSession(session), {
id: await generateGUID(),
type: BeaconMessageType.Disconnect
})
this.clearState()
}
private async onPairingClosed(
signClient: Client,
topic: string
): Promise<SessionTypes.Struct | undefined> {
const session =
this.session?.pairingTopic === topic
? this.session
: signClient.session
.getAll()
.find((session: SessionTypes.Struct) => session.pairingTopic === topic)
if (!session) {
return undefined
}
try {
await signClient.disconnect({
topic: session.topic,
reason: {
code: -1, // TODO: Use constants
message: 'Pairing deleted'
}
})
} catch (error: any) {
// If the session was already closed, `disconnect` will throw an error.
logger.warn(error)
}
return session
}
private async onSessionClosed(
signClient: Client,
sessionTopic: string
): Promise<SessionTypes.Struct | undefined> {
if (!this.session || this.session.topic !== sessionTopic) {
return undefined
}
try {
// todo close the matching session and not just the first one
if (!this.session.pairingTopic) {
await signClient.core.pairing.disconnect({
topic: signClient.core.pairing.getPairings()[0]?.topic
})
} else {
await signClient.core.pairing.disconnect({ topic: this.session.pairingTopic })
}
} catch (error: any) {
// If the pairing was already closed, `disconnect` will throw an error.
logger.warn(error.message)
}
return this.session
}
public async getPairingRequestInfo(): Promise<ExtendedWalletConnectPairingRequest> {
let _uri = '',
_topic = ''
try {
logger.warn('getPairingRequestInfo')
const { uri, topic } = (await this.init(true)) ?? { uri: '', topic: '' }
_uri = uri
_topic = topic
} catch (error: any) {
console.warn(error.message)
}
return new ExtendedWalletConnectPairingRequest(
_topic,
'WalletConnect',
await generateGUID(),
BEACON_VERSION,
await generateGUID(),
_uri
)
}
// private async clearCache() {
// const signClient = await this.getSignClient()
// signClient?.proposal.map.clear()
// signClient?.pendingRequest.map.clear()
// signClient?.session.map.clear()
// ;(signClient?.core.expirer as Expirer).expirations.clear()
// signClient?.core.history.records.clear()
// signClient?.core.crypto.keychain.keychain.clear()
// signClient?.core.relayer.messages.messages.clear()
// signClient?.core.pairing.pairings.map.clear()
// signClient?.core.relayer.subscriber.subscriptions.clear()
// }
private async closePairings() {
await this.closeSessions()
const signClient = await this.getSignClient()
if (signClient) {
const pairings = signClient.pairing.getAll() ?? []
pairings.length &&
(await Promise.allSettled(
pairings.map((pairing) => signClient.core.pairing.disconnect({ topic: pairing.topic }))
))
}
// await this.clearCache()
await this.storage.resetState()
this.storage.notify('RESET')
}
private async closeSessions() {
const signClient = await this.getSignClient()
if (signClient) {
const sessions = signClient.session.getAll() ?? []
sessions.length &&
(await Promise.allSettled(
sessions.map((session) =>
signClient.disconnect({
topic: (session as any).topic,
reason: {
code: 0, // TODO: Use constants
message: 'Force new connection'
}
})
)
))
}
this.clearState()
}
private async openSession(pairingTopic?: string): Promise<SessionTypes.Struct> {
logger.debug('Starting open session with', [pairingTopic])
const signClient = await this.getSignClient()
if (!signClient) {
throw new Error('Transport error.')
}
const permissionScopeParams: PermissionScopeParam = {
networks: [this.wcOptions.network],
events: [],
methods: [
PermissionScopeMethods.GET_ACCOUNTS,
PermissionScopeMethods.OPERATION_REQUEST,
PermissionScopeMethods.SIGN
]
}
const optionalPermissionScopeParams: PermissionScopeParam = {
networks: [this.wcOptions.network],
events: [PermissionScopeEvents.REQUEST_ACKNOWLEDGED],
methods: []
}
const connectParams = {
requiredNamespaces: {
[TEZOS_PLACEHOLDER]: this.permissionScopeParamsToNamespaces(permissionScopeParams)
},
optionalNamespaces: {
[TEZOS_PLACEHOLDER]: this.permissionScopeParamsToNamespaces(optionalPermissionScopeParams)
},
pairingTopic: pairingTopic ?? signClient.core.pairing.getPairings()[0]?.topic
}
logger.debug('Checking wallet readiness', [pairingTopic])
this.checkWalletReadiness(connectParams.pairingTopic)
try {
logger.debug('connect', [pairingTopic])
const { approval } = await signClient.connect(connectParams)
logger.debug('before await approal', [pairingTopic])
const session = await approval()
logger.debug('after await approal, have session', [pairingTopic])
// if I have successfully opened a session and I already have one opened
if (session?.controller !== this.session?.controller) {
logger.debug('Controller doesnt match, closing active session', [pairingTopic])
this.activeAccount && this.closeActiveSession(this.activeAccount)
this.session = undefined // close the previous session
}
// I still need this check in the event the user aborts the sync process on the wallet side