-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathrequests.ts
More file actions
2222 lines (1916 loc) · 75 KB
/
Copy pathrequests.ts
File metadata and controls
2222 lines (1916 loc) · 75 KB
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 { ethErrors } from 'eth-rpc-errors'
import { getAddress, getBigInt, hexlify, isAddress, TypedDataDomain, TypedDataField } from 'ethers'
import { v4 as uuidv4 } from 'uuid'
import { hashTypedData, isHex } from 'viem'
import { BindedRelayerCall } from '@/libs/relayerCall/relayerCall'
import { SwapAndBridgeFormStatus } from '@/libs/swapAndBridge/constants'
import EmittableError from '../../classes/EmittableError'
import SwapAndBridgeError from '../../classes/SwapAndBridgeError'
import { Account, AccountOnchainState, IAccountsController } from '../../interfaces/account'
import { IActivityController } from '../../interfaces/activity'
import { AutoLoginStatus, IAutoLoginController } from '../../interfaces/autoLogin'
import { Banner } from '../../interfaces/banner'
import { Dapp, DappProviderRequest, IDappsController } from '../../interfaces/dapp'
import { IEventEmitterRegistryController, Statuses } from '../../interfaces/eventEmitter'
import { Hex } from '../../interfaces/hex'
import { ExternalSignerController, IKeystoreController } from '../../interfaces/keystore'
import { INetworksController, Network } from '../../interfaces/network'
import { IPhishingController } from '../../interfaces/phishing'
import { IPortfolioController } from '../../interfaces/portfolio'
import { IProvidersController } from '../../interfaces/provider'
import { BuildRequest, IRequestsController } from '../../interfaces/requests'
import { ISafeController } from '../../interfaces/safe'
import { ISelectedAccountController } from '../../interfaces/selectedAccount'
import { IStorageController } from '../../interfaces/storage'
import {
ISwapAndBridgeController,
SwapAndBridgeActiveRoute,
SwapAndBridgeQuote,
SwapAndBridgeSendTxRequest
} from '../../interfaces/swapAndBridge'
import { ITransactionManagerController } from '../../interfaces/transactionManager'
import { ITransferController } from '../../interfaces/transfer'
import { FocusWindowParams, IUiController, WindowProps } from '../../interfaces/ui'
import {
CallsUserRequest,
OpenRequestWindowParams,
PlainTextMessageUserRequest,
RequestExecutionType,
RequestPosition,
SignUserRequest,
SiweMessageUserRequest,
SwapAndBridgeRequest,
TransferRequest,
TypedMessageUserRequest,
UserRequest
} from '../../interfaces/userRequest'
import { isSmartAccount } from '../../libs/account/account'
import { getBaseAccount } from '../../libs/account/getBaseAccount'
import { AccountOp } from '../../libs/accountOp/accountOp'
import { Call } from '../../libs/accountOp/types'
import {
getAccountOpBanners,
getDappUserRequestsBanners,
getSafeMessageRequestBanners
} from '../../libs/banners/banners'
import { getAmbirePaymasterService, getPaymasterService } from '../../libs/erc7677/erc7677'
import { getShouldSimulateInTheBackground } from '../../libs/main/main'
import { TokenResult } from '../../libs/portfolio'
import { PortfolioRewardsResult } from '../../libs/portfolio/interfaces'
import {
buildSwitchAccountUserRequest,
dappRequestMethodToRequestKind,
getCallsUserRequestsByNetwork,
isSignRequest,
messageOnNewRequest
} from '../../libs/requests/requests'
import { parse } from '../../libs/richJson/richJson'
import { getSwapAndBridgeRequestParams } from '../../libs/swapAndBridge/swapAndBridge'
import {
getClaimWalletRequestParams,
getIntentRequestParams,
getMintVestingRequestParams,
getTransferRequestParams
} from '../../libs/transfer/userRequest'
import { generateUuid } from '../../utils/uuid'
import { AutoLoginController } from '../autoLogin/autoLogin'
import EventEmitter from '../eventEmitter/eventEmitter'
import {
OnBroadcastFailed,
OnBroadcastSuccess,
SignAccountOpController
} from '../signAccountOp/signAccountOp'
import { SignAccountOpPreferenceController } from '../signAccountOp/signAccountOpPreference'
import type { EIP712TypedData } from '@safe-global/types-kit'
const STATUS_WRAPPED_METHODS = {
buildSwapAndBridgeUserRequest: 'INITIAL'
} as const
const ONE_CLICK_WINDOW_SIZE = {
width: 600,
height: 600
}
/**
* The RequestsController is responsible for building and managing different user request types (within a request window).
* Prior to v2.66.0, all request logic resided in the MainController. To improve scalability, readability,
* and testability, this logic was encapsulated in this dedicated controller.
*
* After being opened, the request window will remain visible to the user until all requests are resolved or rejected,
* or until the user forcefully closes the window using the system close icon (X).
* After the request window is closed all pending/unresolved requests will be removed except for the requests of type 'calls' to allow batching to an already existing ones.
*/
export class RequestsController extends EventEmitter implements IRequestsController {
#eventEmitterRegistry?: IEventEmitterRegistryController
#relayerUrl: string
#callRelayer: BindedRelayerCall
#portfolio: IPortfolioController
#externalSignerControllers: Partial<{
internal: ExternalSignerController
trezor: ExternalSignerController
ledger: ExternalSignerController
lattice: ExternalSignerController
}>
#activity: IActivityController
#phishing: IPhishingController
#dapps: IDappsController
#accounts: IAccountsController
#networks: INetworksController
#providers: IProvidersController
#storage: IStorageController
#signAccountOpPreference: SignAccountOpPreferenceController
#selectedAccount: ISelectedAccountController
#keystore: IKeystoreController
#transfer: ITransferController
#swapAndBridge: ISwapAndBridgeController
#transactionManager?: ITransactionManagerController
#ui: IUiController
#safe: ISafeController
#autoLogin: IAutoLoginController
#getDapp: (id: string) => Promise<Dapp | undefined>
#updateSelectedAccountPortfolio: (networks?: Network[]) => Promise<void>
#addTokensToBeLearned: (tokenAddresses: string[], chainId: bigint) => void
#onSetCurrentUserRequest: (currentUserRequest: UserRequest | null) => void
#onBroadcastSuccess: OnBroadcastSuccess
#onBroadcastFailed: OnBroadcastFailed
userRequests: UserRequest[] = []
userRequestsWaitingAccountSwitch: UserRequest[] = []
requestWindow: {
windowProps: WindowProps
openWindowPromise?: Promise<WindowProps>
focusWindowPromise?: Promise<WindowProps>
closeWindowPromise?: Promise<void>
loaded: boolean
pendingMessage: {
message: string
options?: {
timeout?: number
type?: 'error' | 'success' | 'info' | 'warning'
sticky?: boolean
}
} | null
} = {
windowProps: null,
loaded: false,
pendingMessage: null
}
#currentUserRequest: UserRequest | null = null
private shouldSimulateAccountOps = true
get currentUserRequest() {
return this.#currentUserRequest
}
set currentUserRequest(val: UserRequest | null) {
this.#currentUserRequest = val
this.#onSetCurrentUserRequest(val)
}
statuses: Statuses<keyof typeof STATUS_WRAPPED_METHODS> = STATUS_WRAPPED_METHODS
// Holds the initial load promise, so that one can wait until it completes
initialLoadPromise?: Promise<void>
constructor({
eventEmitterRegistry,
relayerUrl,
callRelayer,
portfolio,
externalSignerControllers,
activity,
phishing,
dapps,
accounts,
networks,
providers,
storage,
signAccountOpPreference,
selectedAccount,
keystore,
transfer,
swapAndBridge,
transactionManager,
safe,
ui,
autoLogin,
getDapp,
updateSelectedAccountPortfolio,
addTokensToBeLearned,
onSetCurrentUserRequest,
onBroadcastSuccess,
onBroadcastFailed,
shouldSimulateAccountOps = true
}: {
eventEmitterRegistry?: IEventEmitterRegistryController
relayerUrl: string
callRelayer: BindedRelayerCall
portfolio: IPortfolioController
externalSignerControllers: Partial<{
internal: ExternalSignerController
trezor: ExternalSignerController
ledger: ExternalSignerController
lattice: ExternalSignerController
}>
activity: IActivityController
phishing: IPhishingController
dapps: IDappsController
accounts: IAccountsController
networks: INetworksController
providers: IProvidersController
storage: IStorageController
signAccountOpPreference: SignAccountOpPreferenceController
selectedAccount: ISelectedAccountController
keystore: IKeystoreController
transfer: ITransferController
swapAndBridge: ISwapAndBridgeController
transactionManager?: ITransactionManagerController
ui: IUiController
safe: ISafeController
autoLogin: IAutoLoginController
getDapp: (id: string) => Promise<Dapp | undefined>
updateSelectedAccountPortfolio: (networks?: Network[]) => Promise<void>
addTokensToBeLearned: (tokenAddresses: string[], chainId: bigint) => void
onSetCurrentUserRequest: (currentUserRequest: UserRequest | null) => void
onBroadcastSuccess: OnBroadcastSuccess
onBroadcastFailed: OnBroadcastFailed
shouldSimulateAccountOps?: boolean
}) {
super(eventEmitterRegistry)
this.#eventEmitterRegistry = eventEmitterRegistry
this.#relayerUrl = relayerUrl
this.#callRelayer = callRelayer
this.#portfolio = portfolio
this.#externalSignerControllers = externalSignerControllers
this.#activity = activity
this.#phishing = phishing
this.#dapps = dapps
this.#accounts = accounts
this.#networks = networks
this.#providers = providers
this.#storage = storage
this.#signAccountOpPreference = signAccountOpPreference
this.#selectedAccount = selectedAccount
this.#keystore = keystore
this.#transfer = transfer
this.#swapAndBridge = swapAndBridge
this.#transactionManager = transactionManager
this.#ui = ui
this.#safe = safe
this.#autoLogin = autoLogin
this.#getDapp = getDapp
this.#updateSelectedAccountPortfolio = updateSelectedAccountPortfolio
this.#addTokensToBeLearned = addTokensToBeLearned
this.#onSetCurrentUserRequest = onSetCurrentUserRequest
this.#onBroadcastSuccess = onBroadcastSuccess
this.#onBroadcastFailed = onBroadcastFailed
this.shouldSimulateAccountOps = shouldSimulateAccountOps
this.#ui.window.event.on('windowRemoved', async (winId: number) => {
// When windowManager.focus is called, it may close and reopen the request window as part of its fallback logic.
// To avoid prematurely running the cleanup logic during that transition, we wait for focusWindowPromise to resolve.
await this.requestWindow.focusWindowPromise
await this.#handleRequestWindowClose(winId)
})
this.#ui.window.event.on('windowFocusChange', async (winId: number) => {
const props = this.requestWindow.windowProps
if (!props) return
const newIsFocused = props.id === winId
if (newIsFocused === props.focused) return
props.focused = newIsFocused
this.emitUpdate()
})
this.initialLoadPromise = this.#load().finally(() => {
this.initialLoadPromise = undefined
})
}
async #load() {
await this.#networks.initialLoadPromise
await this.#providers.initialLoadPromise
await this.#accounts.initialLoadPromise
await this.#selectedAccount.initialLoadPromise
await this.#keystore.initialLoadPromise
await this.#safe.initialLoadPromise
await this.#signAccountOpPreference.initialLoadPromise
}
get visibleUserRequests(): UserRequest[] {
return this.userRequests.filter((r) => {
if (r.kind === 'calls') {
return r.signAccountOp.accountOp.accountAddr === this.#selectedAccount.account?.addr
}
if (
r.kind === 'typedMessage' ||
r.kind === 'message' ||
r.kind === 'authorization-7702' ||
r.kind === 'siwe' ||
r.kind === 'benzin' ||
r.kind === 'swapAndBridge' ||
r.kind === 'transfer'
) {
return r.meta.accountAddr === this.#selectedAccount.account?.addr
}
if (r.kind === 'switchAccount') {
return r.meta.switchToAccountAddr !== this.#selectedAccount.account?.addr
}
return true
})
}
async addUserRequests(
reqs: UserRequest[],
{
position = 'last',
executionType = 'open-request-window',
allowAccountSwitch = false,
skipFocus = false
}: {
position?: RequestPosition
executionType?: RequestExecutionType
allowAccountSwitch?: boolean
skipFocus?: boolean
} = {}
) {
await this.initialLoadPromise
const shouldSkipAddUserRequest = await this.#guardHWSigning(false)
if (shouldSkipAddUserRequest) return
let baseWindowId: number | undefined
const userRequestsToAdd = []
// If any of the requests is a dapp request, we know the source window ID,
// so we set it as the baseWindowId. This will be used as the reference
// for the request window that will be opened, making positioning and size
// calculations more accurate.
reqs.forEach((r) => {
r.dappPromises.forEach((p) => {
if (p.session.windowId && !baseWindowId) baseWindowId = p.session.windowId
})
})
let hasTxInProgressErrorShown = false
for (const req of reqs) {
const { kind, meta, dappPromises } = req
if (allowAccountSwitch && isSignRequest(kind)) {
if ((meta as SignUserRequest['meta']).accountAddr !== this.#selectedAccount.account?.addr) {
await this.#addSwitchAccountUserRequest(req as SignUserRequest)
return
}
}
if (kind === 'calls') {
const accountOpRequest = this.userRequests.find(
(r) => r.kind === 'calls' && r.id === `${meta.accountAddr}-${meta.chainId}`
) as CallsUserRequest | undefined
// Prevent adding a new request if a signing or broadcasting process is already in progress for the same account and chain.
//
// Why? When a transaction is being signed and broadcast, its calls are still unresolved.
// If a new request is added during this time, it gets incorrectly attached to the ongoing request.
// The next time the user starts a transaction, both requests appear in the batch, which is confusing.
// To avoid this, we block new requests until the current process is complete.
//
// Main issue: https://github.com/AmbireTech/ambire-app/issues/4771
if (accountOpRequest?.signAccountOp.signAndBroadcastPromise) {
// Make sure to show the error once
if (!hasTxInProgressErrorShown) {
const errorMessage =
'Please wait until the previous transaction is fully processed before adding a new one.'
this.emitError({
level: 'major',
message: errorMessage,
error: new Error(
'requestsController: Cannot add a new request (addUserRequests) while a signing or broadcasting process is still running.'
)
})
dappPromises.forEach((p) => {
p.reject(ethErrors.rpc.transactionRejected({ message: errorMessage }))
})
await this.#ui.notification.create({ title: 'Rejected!', message: errorMessage })
hasTxInProgressErrorShown = true
}
return
}
const accountStateBefore =
this.#accounts.accountStates?.[meta.accountAddr]?.[meta.chainId.toString()]
// Try to update the account state for 3 seconds. If that fails, use the previous account state if it exists,
// otherwise wait for the fetch to complete (no matter how long it takes).
// This is done in an attempt to always have the latest nonce, but without blocking the UI for too long if the RPC is slow to respond.
const accountState = await Promise.race([
this.#accounts.forceFetchPendingState(meta.accountAddr, meta.chainId),
// Fallback to the old account state if it exists and the fetch takes too long
accountStateBefore
? // `undefined` included intentionally - previous `accountStateBefore` may not always exist
new Promise<AccountOnchainState | undefined>((res) => {
setTimeout(() => res(accountStateBefore), 2000)
})
: new Promise<AccountOnchainState>(() => {}) // Explicitly never-resolving promise
])
if (!accountState) {
const message =
"Transaction couldn't be processed because required account data couldn't be retrieved. Please try again later or contact Ambire support."
const error = new Error(
`requestsController error: accountState for ${meta.accountAddr} is undefined on network with id ${meta.chainId}`
)
this.emitError({ level: 'major', message, error })
req.dappPromises.forEach((p) => {
p.reject(ethErrors.rpc.internal())
})
await this.#ui.notification.create({ title: "Couldn't Process Request", message })
return
}
userRequestsToAdd.push(req)
// Even without an initialized SignAccountOpController or Screen, we should still update the portfolio and run the simulation.
// It's necessary to continue operating with the token `amountPostSimulation` amount.
if (this.shouldSimulateAccountOps)
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.#portfolio.simulateAccountOp(req.signAccountOp.accountOp)
} else if (req.kind === 'typedMessage' || req.kind === 'message' || req.kind === 'siwe') {
const existingMessageRequest = this.userRequests.find(
(r) => r.kind === req.kind && r.meta.accountAddr === req.meta.accountAddr
) as PlainTextMessageUserRequest | TypedMessageUserRequest | undefined
// remove the request only if it's not a Safe req
if (existingMessageRequest && !this.#selectedAccount.account?.safeCreation) {
existingMessageRequest.meta.accountAddr
await this.rejectUserRequests('User rejected the message request', [
existingMessageRequest.id
])
}
userRequestsToAdd.push(req)
} else {
userRequestsToAdd.push(req)
}
}
this.userRequests = this.userRequests.filter((r) => {
if (r.kind === 'benzin') return false
if (r.kind === 'switchAccount') {
return r.meta.switchToAccountAddr !== this.#selectedAccount.account?.addr
}
return true
})
if (
this.currentUserRequest &&
!this.userRequests.find((r) => r.id === this.currentUserRequest!.id)
) {
await this.#setCurrentUserRequest(null)
}
userRequestsToAdd.forEach((newReq) => {
const existingIndex = this.userRequests.findIndex((r) => r.id === newReq.id)
if (existingIndex !== -1) {
this.userRequests[existingIndex] = newReq
if (executionType === 'open-request-window') {
this.sendNewRequestMessage(newReq, 'updated')
} else if (executionType === 'queue-but-open-request-window') {
this.sendNewRequestMessage(newReq, 'queued')
}
} else if (position === 'first') {
this.userRequests.unshift(newReq)
} else {
this.userRequests.push(newReq)
}
})
const nextRequest = userRequestsToAdd[0]!
if (executionType !== 'queue') {
let currentUserRequest = null
if (executionType === 'open-request-window') {
currentUserRequest = this.visibleUserRequests.find((r) => r.id === nextRequest.id) || null
} else if (executionType === 'queue-but-open-request-window') {
this.sendNewRequestMessage(nextRequest, 'queued')
currentUserRequest = this.currentUserRequest || this.visibleUserRequests[0] || null
}
await this.#setCurrentUserRequest(currentUserRequest, { skipFocus, baseWindowId })
} else {
this.emitUpdate()
}
}
async #awaitPendingPromises() {
await this.requestWindow.closeWindowPromise
await this.requestWindow.focusWindowPromise
await this.requestWindow.openWindowPromise
}
async #setCurrentUserRequest(nextRequest: UserRequest | null, params?: OpenRequestWindowParams) {
// Pause the previously active signAccountOp request
if (
this.currentUserRequest &&
this.currentUserRequest.kind === 'calls' &&
this.currentUserRequest.signAccountOp
) {
if (
!getShouldSimulateInTheBackground(
this.currentUserRequest,
this.visibleUserRequests.filter((r) => r.kind === 'calls')
)
) {
await this.#portfolio.overrideSimulationResults(
this.currentUserRequest.signAccountOp.accountOp
)
}
this.currentUserRequest.signAccountOp.pause()
}
// Resume the signAccountOp of the incoming request
if (nextRequest && nextRequest.kind === 'calls' && nextRequest.signAccountOp) {
nextRequest.signAccountOp.resume()
}
this.currentUserRequest = nextRequest
this.emitUpdate()
if (nextRequest) {
await this.openRequestWindow(params)
return
}
await this.closeRequestWindow()
}
// When the wallet runs in the Chrome side panel and the panel is open, the action
// requests are rendered inside the panel itself (over the dashboard) instead of a
// separate request window. A side-panel view only exists in `views` while the panel
// is open, so its presence is the signal to skip the window entirely.
get #isSidePanelOpen() {
return this.#ui.views.some((view) => view.type === 'side-panel')
}
async openRequestWindow(params?: OpenRequestWindowParams) {
const { skipFocus, baseWindowId } = params || {}
await this.#awaitPendingPromises()
if (this.#isSidePanelOpen) {
// The side panel reacts to `currentUserRequest` and renders the request in-place.
await this.forceEmitUpdate()
return
}
if (this.requestWindow.windowProps) {
if (!skipFocus) {
// Force-emitting here updates currentUserRequest on the FE before the window regains focus,
// preventing the user from briefly seeing the previous request.
await this.forceEmitUpdate()
await this.focusRequestWindow()
}
} else {
let customSize
if (
this.currentUserRequest?.kind === 'swapAndBridge' ||
this.currentUserRequest?.kind === 'transfer'
) {
customSize = ONE_CLICK_WINDOW_SIZE
}
try {
await this.#ui.window.remove('popup')
this.requestWindow.openWindowPromise = this.#ui.window
.open({ customSize, baseWindowId })
.finally(() => {
this.requestWindow.openWindowPromise = undefined
})
this.requestWindow.windowProps = await this.requestWindow.openWindowPromise
this.emitUpdate()
} catch (err) {
this.emitError({
message:
'Failed to open a new request window. Please restart your browser if the issue persists.',
level: 'major',
error: err as Error
})
}
}
}
async focusRequestWindow(params?: FocusWindowParams) {
await this.#awaitPendingPromises()
// In side-panel mode there is no separate window to focus; the panel already shows it.
if (this.#isSidePanelOpen) {
await this.forceEmitUpdate()
return
}
if (
!this.visibleUserRequests.length ||
!this.currentUserRequest ||
!this.requestWindow.windowProps
)
return
try {
await this.#ui.window.remove('popup')
this.requestWindow.focusWindowPromise = this.#ui.window
.focus(this.requestWindow.windowProps, params)
.finally(() => {
this.requestWindow.focusWindowPromise = undefined
})
const newRequestWindowProps = await this.requestWindow.focusWindowPromise
if (newRequestWindowProps) {
this.requestWindow.windowProps = newRequestWindowProps
}
this.emitUpdate()
} catch (err) {
this.emitError({
message:
'Failed to focus the request window. Please restart your browser if the issue persists.',
level: 'major',
error: err as Error
})
}
}
async closeRequestWindow() {
await this.#awaitPendingPromises()
if (!this.requestWindow.windowProps) return
this.requestWindow.closeWindowPromise = this.#ui.window
.remove(this.requestWindow.windowProps.id)
.finally(() => {
this.requestWindow.closeWindowPromise = undefined
})
await this.requestWindow.closeWindowPromise
if (!this.requestWindow.windowProps) return
await this.#handleRequestWindowClose(this.requestWindow.windowProps.id)
}
async #onActiveRequestDismissed() {
const requestIdsSnapshotAtClose = new Set(this.userRequests.map((r) => r.id))
this.requestWindow.windowProps = null
this.requestWindow.loaded = false
this.requestWindow.pendingMessage = null
await this.#setCurrentUserRequest(null)
const callsCount = this.visibleUserRequests.reduce((acc, request) => {
if (request.kind !== 'calls') return acc
return acc + (request.signAccountOp.accountOp.calls?.length || 0)
}, 0)
if (callsCount) {
await this.#ui.notification.create({
title: callsCount > 1 ? `${callsCount} transactions queued` : 'Transaction queued',
message: 'Queued pending transactions are available on your Dashboard.'
})
}
for (const r of this.userRequests) {
if (r.kind === 'walletAddEthereumChain') {
const chainId = r.meta.params[0].chainId
if (!chainId) continue
const network = this.#networks.networks.find((n) => n.chainId === BigInt(chainId))
if (network && !network.disabled) await this.resolveUserRequest(null, r.id)
}
}
const userRequestsToRejectOnWindowClose = this.userRequests.filter(
(r) => r.kind !== 'calls' && !r.meta.keepRequestAlive && requestIdsSnapshotAtClose.has(r.id)
)
await this.rejectUserRequests(
ethErrors.provider.userRejectedRequest().message,
userRequestsToRejectOnWindowClose.map((r) => r.id),
// If the user closes a window and non-calls user requests exist,
// the window will reopen with the next request.
// For example: if the user has both a sign message and sign account op request,
// closing the window will reject the sign message request but immediately
// reopen the window for the sign account op request.
{ shouldOpenNextRequest: false }
)
this.userRequestsWaitingAccountSwitch = []
this.emitUpdate()
}
async dismissActiveRequest() {
await this.#awaitPendingPromises()
if (!this.currentUserRequest) return
try {
// In the side panel there is no window to close; apply the same queue semantics as
// closing the request window (keep calls queued, clear the active request).
if (this.#isSidePanelOpen) {
await this.#onActiveRequestDismissed()
return
}
if (this.requestWindow.windowProps) {
await this.closeRequestWindow()
}
} catch (err) {
this.emitError({
message: 'Failed to dismiss the active request. Please try again.',
level: 'major',
error: err as Error
})
}
}
async #handleRequestWindowClose(winId: number) {
if (
winId === this.requestWindow.windowProps?.id ||
(!this.visibleUserRequests.length &&
this.currentUserRequest &&
this.requestWindow.windowProps)
) {
await this.#onActiveRequestDismissed()
}
}
async rejectCalls({
callIds = [],
activeRouteIds: paramActiveRouteIds = [],
errorMessage = 'User rejected the transaction request!'
}: {
callIds?: Call['id'][]
activeRouteIds?: string[]
errorMessage?: string
}) {
if (!callIds.length && !paramActiveRouteIds.length) return
const findRequestByCall = (predicate: (c: Call) => boolean) =>
this.userRequests.find(
(r) => r.kind === 'calls' && r.signAccountOp.accountOp.calls.some(predicate)
) as CallsUserRequest | undefined
const rejectAndCleanup = async (request: CallsUserRequest, callIdsToRemove: Call['id'][]) => {
request.signAccountOp.update({
accountOpData: {
calls: request.signAccountOp.accountOp.calls.filter((c) => {
const shouldRemove = callIdsToRemove.some((id) => id === c.id)
if (shouldRemove) {
if (c.activeRouteId) this.#swapAndBridge.removeActiveRoute(c.activeRouteId)
if (c.dappPromiseId) {
request.dappPromises
.find((p) => p.id === c.dappPromiseId)
?.reject(ethErrors.provider.userRejectedRequest<any>(errorMessage))
request.dappPromises = request.dappPromises.filter((p) => p.id !== c.dappPromiseId)
}
}
return !shouldRemove
})
}
})
if (!request.signAccountOp.accountOp.calls.length) {
await this.rejectUserRequests('User rejected the transaction request.', [request.id], {
shouldOpenNextRequest: true
})
} else {
this.emitUpdate()
}
}
const activeRouteIdsToRemove = [...paramActiveRouteIds]
for (const callId of callIds) {
const request = findRequestByCall((c) => c.id === callId)
if (!request) continue
const call = request.signAccountOp.accountOp.calls.find((c) => c.id === callId)
if (call?.activeRouteId) {
// What we are doing here is finding all calls for a swap
// and removing them together if one of them is being removed.
// Example: The user removes the approval call only,
// and we also remove the actual swap call.
if (!activeRouteIdsToRemove.includes(call.activeRouteId)) {
activeRouteIdsToRemove.push(call.activeRouteId)
}
continue
}
if (!call) continue
await rejectAndCleanup(request, [call.id])
}
for (const activeRouteId of activeRouteIdsToRemove) {
const request = findRequestByCall((c) => c.activeRouteId === activeRouteId)
if (!request) continue
const callIdsToRemove = request.signAccountOp.accountOp.calls
.filter((c) => c.activeRouteId === activeRouteId)
.map((c) => c.id)
.filter(Boolean) as string[]
if (callIdsToRemove.length === 0) continue
await rejectAndCleanup(request, callIdsToRemove)
}
}
async removeUserRequests(
ids: UserRequest['id'][],
options?: {
shouldRemoveSwapAndBridgeRoute?: boolean
shouldOpenNextRequest?: boolean
shouldRejectSafeRequests?: boolean
}
) {
const {
shouldRemoveSwapAndBridgeRoute = true,
shouldOpenNextRequest = true,
shouldRejectSafeRequests = true
} = options || {}
const userRequestsToAdd: UserRequest[] = []
const safeResolveIds: { txnIds: string[]; nonce: bigint }[] = []
const safeRejectIds: string[] = []
ids.forEach((id) => {
const req = this.userRequests.find((uReq) => uReq.id === id)
if (!req) return
// remove from the request queue
this.userRequests.splice(this.userRequests.indexOf(req), 1)
// update the pending stuff to be signed
const { kind, meta } = req
if (kind === 'calls') {
const account = this.#accounts.accounts.find((x) => x.addr === meta.accountAddr)
if (!account)
throw new Error(
`removeUserRequests: tried to run for non-existent account ${meta.accountAddr}`
)
if (this.#swapAndBridge.activeRoutes.length && shouldRemoveSwapAndBridgeRoute) {
req.signAccountOp.accountOp.calls.forEach((c) => {
if (c.activeRouteId) this.#swapAndBridge.removeActiveRoute(c.activeRouteId)
})
}
// if it's a Safe txn:
// - reject it upon a normal reject req;
// - resolve it on accountOp resolve
if (
!!req.signAccountOp.account.safeCreation &&
req.signAccountOp.accountOp.txnId &&
req.signAccountOp.accountOp.nonce !== null
) {
if (shouldRejectSafeRequests) safeRejectIds.push(req.signAccountOp.accountOp.txnId)
else {
const resolved = safeResolveIds.find(
(txns) => txns.nonce === req.signAccountOp.accountOp.nonce
)
if (!resolved)
safeResolveIds.push({
nonce: req.signAccountOp.accountOp.nonce,
txnIds: [req.signAccountOp.accountOp.txnId]
})
else resolved.txnIds.push(req.signAccountOp.accountOp.txnId)
}
}
req.signAccountOp.destroy()
return
}
if (kind === 'switchAccount') {
const requestsToAddOrRemove = this.userRequestsWaitingAccountSwitch.filter(
(r) =>
isSignRequest(r.kind) &&
(r as SignUserRequest).meta.accountAddr === this.#selectedAccount.account?.addr
)
requestsToAddOrRemove.forEach((r) => {
this.userRequestsWaitingAccountSwitch.splice(this.userRequests.indexOf(r), 1)
userRequestsToAdd.push(r)
})
}
if (kind === 'message' || kind === 'siwe' || kind === 'typedMessage') {
const account = this.#accounts.accounts.find((x) => x.addr === meta.accountAddr)
if (!account || !account.safeCreation) return
safeRejectIds.push(`${meta.hash}`)
}
})
// reject all Safe txns so they do not appear by accident again
if (safeRejectIds.length) await this.#safe.rejectTxnId(safeRejectIds)
if (safeResolveIds.length) await this.#safe.resolveTxnId(safeResolveIds)
if (userRequestsToAdd.length) {
await this.addUserRequests(userRequestsToAdd, { skipFocus: true })
}
if (!this.visibleUserRequests.length) {
await this.#setCurrentUserRequest(null)
} else if (shouldOpenNextRequest) {
await this.#setCurrentUserRequest(this.visibleUserRequests[0] || null, {
skipFocus: true
})
} else {
this.emitUpdate()
}
}
async resolveUserRequest(data: any, requestId: UserRequest['id']) {
const userRequest = this.userRequests.find((r) => r.id === requestId)
if (!userRequest) return // TODO: emit error
const { kind, meta, dappPromises } = userRequest
dappPromises.forEach((p) => {
// WE SHOULD NEVER RESOLVE THE PROMISE. It should only be rejected if the user rejects the request