-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathswapAndBridge.ts
More file actions
2966 lines (2499 loc) · 101 KB
/
Copy pathswapAndBridge.ts
File metadata and controls
2966 lines (2499 loc) · 101 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 { formatUnits, getAddress, isAddress, parseUnits, ZeroAddress } from 'ethers'
import { getAccountNetworks } from '@/libs/networks/networks'
import { BindedRelayerCall } from '@/libs/relayerCall/relayerCall'
import { SwapAndBridgeFormStatus } from '@/libs/swapAndBridge/constants'
import EmittableError from '../../classes/EmittableError'
import { RecurringTimeout } from '../../classes/recurringTimeout/recurringTimeout'
import SwapAndBridgeError from '../../classes/SwapAndBridgeError'
import {
BRIDGE_STATUS_INTERVAL,
UPDATE_SWAP_AND_BRIDGE_QUOTE_INTERVAL
} from '../../consts/intervals'
import { IAccountsController } from '../../interfaces/account'
import { IActivityController } from '../../interfaces/activity'
import { IDappsController } from '../../interfaces/dapp'
import { IEventEmitterRegistryController, Statuses } from '../../interfaces/eventEmitter'
import { ExternalSignerControllers, 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 { ISelectedAccountController } from '../../interfaces/selectedAccount'
import { ISignAccountOpController, SignAccountOpError } from '../../interfaces/signAccountOp'
import { IStorageController } from '../../interfaces/storage'
import {
CachedSupportedChains,
CachedTokenListKey,
FromToken,
ISwapAndBridgeController,
SwapAndBridgeActiveRoute,
SwapAndBridgeQuote,
SwapAndBridgeRoute,
SwapAndBridgeRouteStatus,
SwapAndBridgeRouteStatusResult,
SwapAndBridgeSendTxRequest,
SwapAndBridgeToToken,
SwapProvider
} from '../../interfaces/swapAndBridge'
import { IUiController, View } from '../../interfaces/ui'
import { CallsUserRequest, UserRequest } from '../../interfaces/userRequest'
import { getBaseAccount } from '../../libs/account/getBaseAccount'
import { AccountOp } from '../../libs/accountOp/accountOp'
import { SubmittedAccountOp } from '../../libs/accountOp/submittedAccountOp'
import { AccountOpStatus, Call } from '../../libs/accountOp/types'
import { getBridgeBanners } from '../../libs/banners/banners'
import { getAmbirePaymasterService } from '../../libs/erc7677/erc7677'
import { randomId } from '../../libs/humanizer/utils'
import { TokenResult } from '../../libs/portfolio'
import { getTokenAmount } from '../../libs/portfolio/helpers'
import { PORTFOLIO_LIB_ERROR_NAMES } from '../../libs/portfolio/portfolio'
import {
addCustomTokensIfNeeded,
convertNullAddressToZeroAddressIfNeeded,
convertPortfolioTokenToSwapAndBridgeToToken,
enrichRouteWithOutputUsdPrice,
getActiveRoutesForAccount,
getActiveRoutesLowestServiceTime,
getBannedToTokenList,
getFeeTokenForSponsorship,
getIsBridgeRoute,
getIsTokenEligibleForSwapAndBridge,
getSwapAndBridgeCalls,
getSwapSponsorship,
isTxnBridge,
mapBannedToValidAddr,
sortPortfolioTokenList,
sortTokenListResponse
} from '../../libs/swapAndBridge/swapAndBridge'
import { getHumanReadableSwapAndBridgeError } from '../../libs/swapAndBridge/swapAndBridgeErrorHumanizer'
import { getSanitizedAmount } from '../../libs/transfer/amount'
import { NULL_ADDRESS } from '../../services/socket/constants'
import { validateSendTransferAmount, Validation } from '../../services/validations/validate'
import {
convertTokenPriceToBigInt,
getSafeAmountFromFieldValue
} from '../../utils/numbers/formatters'
import { generateUuid } from '../../utils/uuid'
import wait from '../../utils/wait'
import { withTimeout } from '../../utils/with-timeout'
import { EstimationStatus } from '../estimation/types'
import EventEmitter from '../eventEmitter/eventEmitter'
import {
OnBroadcastFailed,
OnBroadcastSuccess,
SignAccountOpController
} from '../signAccountOp/signAccountOp'
import { SignAccountOpPreferenceController } from '../signAccountOp/signAccountOpPreference'
type SwapAndBridgeErrorType = {
id: 'to-token-list-fetch-failed' | 'no-routes' | 'all-routes-failed'
title: string
text?: string
level: 'error' | 'warning'
}
const HARD_CODED_CURRENCY = 'usd'
const isSwapAndBridge = (route: string | undefined) => route === 'swap-and-bridge'
const CONVERSION_PRECISION = 16
const CONVERSION_PRECISION_POW = BigInt(10 ** CONVERSION_PRECISION)
const NETWORK_MISMATCH_MESSAGE =
'Swap & Bridge network configuration mismatch. Please try again or contact Ambire support.'
// For performance reasons, limit the max number of tokens in the to token list
const TO_TOKEN_LIST_LIMIT = 100
const TO_TOKEN_PRICE_TIMEOUT_MS = 4000
const STATUS_WRAPPED_METHODS = {
addToTokenByAddress: 'INITIAL'
} as const
const SUPPORTED_CHAINS_CACHE_THRESHOLD = 1000 * 60 * 60 * 24 // 1 day
const TO_TOKEN_LIST_CACHE_THRESHOLD = 1000 * 60 * 60 * 4 // 4 hours
export const sortSwapAndBridgeRoutes = (r1: SwapAndBridgeRoute, r2: SwapAndBridgeRoute) => {
const isBridge = r1.fromChainId !== r1.toChainId
// the amount threshold in %. If below, we check the time as
// the deciding sort factor
const threshold = 1.2
const sortByTime = () => {
const aTime = Number(r1.serviceTime)
const bTime = Number(r2.serviceTime)
if (aTime === bTime) return 0
if (aTime > bTime) return 1
return -1
}
const sortByPerformance = () => {
// if it's a bridge, prioritize across and relay as we find
// across and relay the best bridges out where with a close
// to 100% success rate and an approximate bridge time of 30s
if (isBridge) {
const aHasAcross = r1.usedBridgeNames?.includes('across')
const bHasAcross = r2.usedBridgeNames?.includes('across')
if (aHasAcross && !bHasAcross) return -1
if (bHasAcross && !aHasAcross) return 1
const aHasRelay = r1.usedBridgeNames?.includes('relaydepository')
const bHasRelay = r2.usedBridgeNames?.includes('relaydepository')
if (aHasRelay && !bHasRelay) return -1
if (bHasRelay && !aHasRelay) return 1
} else {
// if it's a swap, deprioritize the bungee auto route as it's an intent
// engine. And intent engines are bad UX
const aHasBungeeAutoRoute = r1.usedBridgeNames?.includes('bungeeAutoRoute')
const bHasBungeeAutoRoute = r2.usedBridgeNames?.includes('bungeeAutoRoute')
if (aHasBungeeAutoRoute && !bHasBungeeAutoRoute) return 1
if (bHasBungeeAutoRoute && !aHasBungeeAutoRoute) return -1
}
// outputValueAfterGas is just as it name suggest: the value
// each provider returns after the gas calculations have been made.
// Uniswap is very efficient at this althouhg the rates might be slightly
// worse. But slightly worse rates are better than paying a massive
// transaction fee for the swap. That's why we're applying this sort
const aOutputValueAfterGasInUsd = r1.outputValueAfterGasInUsd
const bOutputValueAfterGasInUsd = r2.outputValueAfterGasInUsd
if (
aOutputValueAfterGasInUsd !== undefined &&
bOutputValueAfterGasInUsd !== undefined &&
Number.isFinite(aOutputValueAfterGasInUsd) &&
Number.isFinite(bOutputValueAfterGasInUsd)
) {
if (aOutputValueAfterGasInUsd === bOutputValueAfterGasInUsd) {
if (!isBridge) return 0
return sortByTime()
}
const higherOutputValueAfterGasInUsd = Math.max(
aOutputValueAfterGasInUsd,
bOutputValueAfterGasInUsd
)
const lowerOutputValueAfterGasInUsd = Math.min(
aOutputValueAfterGasInUsd,
bOutputValueAfterGasInUsd
)
const outputComparison = aOutputValueAfterGasInUsd > bOutputValueAfterGasInUsd ? -1 : 1
// if it's not a bridge, just return the higher output route
if (!isBridge || higherOutputValueAfterGasInUsd <= 0) return outputComparison
const percentage =
((higherOutputValueAfterGasInUsd - lowerOutputValueAfterGasInUsd) /
higherOutputValueAfterGasInUsd) *
100
if (percentage < threshold) return sortByTime()
return outputComparison
}
const a = BigInt(r1.toAmount)
const b = BigInt(r2.toAmount)
// if value is the same, check time if bridge
if (a === b) {
if (!isBridge) return 0
return sortByTime()
}
const aUsd = Number(r1.outputValueInUsd ?? 0)
const bUsd = Number(r2.outputValueInUsd ?? 0)
if (a > b) {
// if it's not a bridge, just return the higher output route
if (!isBridge) return -1
// if the bigint amount says a > b but the usd amount says
// the opposite, we're stuck, so just return a as the winner
if (bUsd > aUsd || aUsd === 0) return -1
const percentage = ((aUsd - bUsd) / aUsd) * 100
if (percentage < threshold) return sortByTime()
return -1
}
// if it's not a bridge, just return the higher output route
if (!isBridge) return 1
// if the bigint amount says b > a but the usd amount says
// the opposite, we're stuck, so just return b as the winner
if (aUsd > bUsd || bUsd === 0) return 1
const percentage = ((bUsd - aUsd) / bUsd) * 100
if (percentage < threshold) return sortByTime()
return 1
}
// move the routes with service fee to the bottom
const r1ServiceFee = r1.serviceFee && Number(r1.serviceFee.amountUSD) > 0
const r2ServiceFee = r2.serviceFee && Number(r2.serviceFee.amountUSD) > 0
if (r1ServiceFee && !r2ServiceFee) return 1
if (r2ServiceFee && !r1ServiceFee) return -1
return sortByPerformance()
}
type SignAccountOpControllerMethods = {
[K in keyof SignAccountOpController as SignAccountOpController[K] extends (...args: any) => any
? K
: never]: SignAccountOpController[K]
}
/**
* The Swap and Bridge controller is responsible for managing the state and
* logic related to swapping and bridging tokens across different networks.
* Key responsibilities:
* - Initially setting up the swap and bridge form with the necessary data.
* - Managing form state for token swap and bridge operations (including user preferences).
* - Fetching and updating token lists (from and to).
* - Fetching and updating quotes for token swaps and bridges.
* - Manages token active routes
*/
export class SwapAndBridgeController extends EventEmitter implements ISwapAndBridgeController {
#callRelayer: BindedRelayerCall
#selectedAccount: ISelectedAccountController
#networks: INetworksController
#activity: IActivityController
#storage: IStorageController
#signAccountOpPreference: SignAccountOpPreferenceController
#serviceProviderAPI: SwapProvider
#activeRoutes: SwapAndBridgeActiveRoute[] = []
statuses: Statuses<keyof typeof STATUS_WRAPPED_METHODS> = STATUS_WRAPPED_METHODS
updateQuoteStatus: 'INITIAL' | 'LOADING' = 'INITIAL'
#updateQuoteId?: string
switchTokensStatus: 'INITIAL' | 'LOADING' = 'INITIAL'
sessionIds: string[] = []
fromChainId: number | null = 1
fromSelectedToken: FromToken | null = null
fromAmount: string = ''
fromAmountInFiat: string = ''
/**
* A counter used to trigger UI updates when the amount is changed programmatically
* by the controller.
*/
fromAmountUpdateCounter: number = 0
fromAmountFieldMode: 'fiat' | 'token' = 'token'
toChainId: number | null = 1
toSelectedToken: SwapAndBridgeToToken | null = null
toTokenSearchTerm: string = ''
toTokenSearchResults: SwapAndBridgeToToken[] = []
quote: SwapAndBridgeQuote | null = null
quoteRoutesStatuses: { [key: string]: { status: string } } = {}
portfolioTokenList: FromToken[] = []
isTokenListLoading: boolean = false
errors: SwapAndBridgeErrorType[] = []
#toTokenList: {
[key in CachedTokenListKey]?: {
status: 'INITIAL' | 'LOADING'
// Timestamp (in ms) of the last successful `apiTokens` update.
lastUpdate: number
// Raw tokens fetched from the API, refreshed periodically based on SUPPORTED_CHAINS_CACHE_THRESHOLD.
apiTokens: SwapAndBridgeToToken[]
// Final, processed list of tokens shown to the user.
// Includes: `apiTokens` + portfolio tokens + post-filtering and sorting logic.
// Use this array in all UI and presentation layers.
tokens: SwapAndBridgeToToken[]
}
} = {}
/**
* Similar to the `#toTokenList[key].apiTokens`, this helps in avoiding repeated API
* calls to fetch the supported chains from our service provider.
*/
#cachedSupportedChains: CachedSupportedChains = { lastFetched: 0, data: [] }
routePriority: 'output' | 'time' = 'output'
// Holds the initial load promise, so that one can wait until it completes
#initialLoadPromise?: Promise<void>
#shouldDebounceFlags: { [key: string]: boolean } = {}
#accounts: IAccountsController
#keystore: IKeystoreController
#portfolio: IPortfolioController
#externalSignerControllers: ExternalSignerControllers
#providers: IProvidersController
#phishing: IPhishingController
#dapps: IDappsController
/**
* A possibly outdated instance of the SignAccountOpController. Please always
* read the public getter `signAccountOpController` to get the up-to-date
* instance. If updating a route consists of:
* QUOTE FETCH -> ROUTE START -> ROUTE ESTIMATION
*
* This instance may be outdated during QUOTE FETCH -> ROUTE START
* The reason is that the controller is not immediately destroyed after the
* form changes, but instead is being updated after the route is started.
*/
#signAccountOpController: ISignAccountOpController | null = null
#portfolioUpdate?: (chainsToUpdate: Network['chainId'][]) => void
#isCurrentSignAccountOpThrowingAnEstimationError: Function | undefined
#getUserRequests: () => UserRequest[]
#getVisibleUserRequests: () => UserRequest[]
hasProceeded: boolean = false
#relayerUrl: string
#updateQuoteInterval: RecurringTimeout
get updateQuoteInterval() {
return this.#updateQuoteInterval
}
#updateActiveRoutesInterval: RecurringTimeout
get updateActiveRoutesInterval() {
return this.#updateActiveRoutesInterval
}
#continuouslyUpdateActiveRoutesPromise: Promise<void> | undefined
#continuouslyUpdateActiveRoutesSessionId: string | undefined
#onBroadcastSuccess: OnBroadcastSuccess
#onBroadcastFailed: OnBroadcastFailed
#ui: IUiController
#isOnSwapAndBridgeRoute: boolean = false
constructor({
eventEmitterRegistry,
callRelayer,
accounts,
keystore,
portfolio,
externalSignerControllers,
providers,
selectedAccount,
networks,
activity,
storage,
signAccountOpPreference,
phishing,
dapps,
portfolioUpdate,
relayerUrl,
isCurrentSignAccountOpThrowingAnEstimationError,
getUserRequests,
getVisibleUserRequests,
swapProvider,
onBroadcastSuccess,
onBroadcastFailed,
ui
}: {
eventEmitterRegistry?: IEventEmitterRegistryController
callRelayer: BindedRelayerCall
accounts: IAccountsController
keystore: IKeystoreController
portfolio: IPortfolioController
externalSignerControllers: ExternalSignerControllers
providers: IProvidersController
selectedAccount: ISelectedAccountController
networks: INetworksController
activity: IActivityController
storage: IStorageController
signAccountOpPreference: SignAccountOpPreferenceController
phishing: IPhishingController
dapps: IDappsController
relayerUrl: string
portfolioUpdate?: (chainsToUpdate: Network['chainId'][]) => void
isCurrentSignAccountOpThrowingAnEstimationError?: Function
getUserRequests: () => UserRequest[]
getVisibleUserRequests: () => UserRequest[]
swapProvider: SwapProvider
onBroadcastSuccess: OnBroadcastSuccess
onBroadcastFailed: OnBroadcastFailed
ui: IUiController
}) {
super(eventEmitterRegistry)
this.#callRelayer = callRelayer
this.#accounts = accounts
this.#keystore = keystore
this.#portfolio = portfolio
this.#externalSignerControllers = externalSignerControllers
this.#providers = providers
this.#portfolioUpdate = portfolioUpdate
this.#isCurrentSignAccountOpThrowingAnEstimationError =
isCurrentSignAccountOpThrowingAnEstimationError
this.#selectedAccount = selectedAccount
this.#networks = networks
this.#activity = activity
this.#serviceProviderAPI = swapProvider
this.#storage = storage
this.#signAccountOpPreference = signAccountOpPreference
this.#phishing = phishing
this.#dapps = dapps
this.#relayerUrl = relayerUrl
this.#getUserRequests = getUserRequests
this.#getVisibleUserRequests = getVisibleUserRequests
this.#onBroadcastSuccess = onBroadcastSuccess
this.#onBroadcastFailed = onBroadcastFailed
this.#ui = ui
this.#initialLoadPromise = this.#load().finally(() => {
this.#initialLoadPromise = undefined
})
this.#updateQuoteInterval = new RecurringTimeout(
async () => this.continuouslyUpdateQuote(),
UPDATE_SWAP_AND_BRIDGE_QUOTE_INTERVAL,
this.emitError.bind(this)
)
this.#updateActiveRoutesInterval = new RecurringTimeout(
async () => this.continuouslyUpdateActiveRoutes(),
BRIDGE_STATUS_INTERVAL,
this.emitError.bind(this)
)
this.#ui.uiEvent.on('updateView', (view: View) => {
if (isSwapAndBridge(view.currentRoute)) {
this.#isOnSwapAndBridgeRoute = true
// Fetch a fresh quote immediately if the form is ready and the last
// quote is older than 20 seconds (e.g. user was away on another screen).
// If the user just briefly switched screens, skip the immediate fetch
// and let the normal interval handle the next update.
const isQuoteStale = Date.now() - this.updateQuoteInterval.startedRunningAt > 20_000
this.updateQuoteInterval.restart({
runImmediately: !!this.#shouldAutoUpdateQuote && isQuoteStale
})
} else if (isSwapAndBridge(view.previousRoute)) {
this.#isOnSwapAndBridgeRoute = false
this.updateQuoteInterval.stop()
}
})
this.#ui.uiEvent.on('removeView', (view: View) => {
if (view.type === 'side-panel') {
if (isSwapAndBridge(view.currentRoute)) {
this.#isOnSwapAndBridgeRoute = false
this.updateQuoteInterval.stop()
}
if (this.sessionIds.includes('side-panel')) {
this.unloadScreen('side-panel', true)
}
return
}
if (!isSwapAndBridge(view.currentRoute)) return
this.#isOnSwapAndBridgeRoute = false
this.updateQuoteInterval.stop()
})
}
#emitUpdateIfNeeded(forceUpdate: boolean = false) {
const shouldSkipUpdate =
// No need to emit emit updates if there are no active sessions
!this.sessionIds.length &&
// but ALSO there are no active routes (otherwise, banners need the updates)
!this.activeRoutes.length &&
// Force update is needed when the form is reset
// as the sessions are cleared
!forceUpdate
if (shouldSkipUpdate) return
super.emitUpdate()
}
#setFromAmountAndNotifyUI(amount: string) {
this.fromAmount = amount
this.fromAmountUpdateCounter += 1
}
#setFromAmountInFiatAndNotifyUI(amountInFiat: string) {
this.fromAmountInFiat = amountInFiat
this.fromAmountUpdateCounter += 1
}
#setFromAmountAmount(fromAmount: string, isProgrammaticUpdate = false) {
const fromAmountFormatted = fromAmount.indexOf('.') === 0 ? `0${fromAmount}` : fromAmount
this.fromAmount = fromAmount
if (isProgrammaticUpdate) {
// There is no problem in updating this first as there are no
// emit updates in this method
this.fromAmountUpdateCounter += 1
}
if (fromAmount === '') {
this.fromAmountInFiat = ''
return
}
const tokenPrice = this.fromSelectedToken?.priceIn.find(
(p) => p.baseCurrency === HARD_CODED_CURRENCY
)?.price
if (!tokenPrice) {
this.fromAmountInFiat = ''
return
}
if (
this.fromAmountFieldMode === 'fiat' &&
typeof this.fromSelectedToken?.decimals === 'number'
) {
this.fromAmountInFiat = fromAmount
// Get the number of decimals
const amountInFiatDecimals = 10
const { tokenPriceBigInt, tokenPriceDecimals } = convertTokenPriceToBigInt(tokenPrice)
// Convert the numbers to big int
const amountInFiatBigInt = parseUnits(
getSanitizedAmount(fromAmountFormatted, amountInFiatDecimals),
amountInFiatDecimals
)
this.fromAmount = formatUnits(
(amountInFiatBigInt * CONVERSION_PRECISION_POW) / tokenPriceBigInt,
// Shift the decimal point by the number of decimals in the token price
amountInFiatDecimals + CONVERSION_PRECISION - tokenPriceDecimals
)
return
}
if (this.fromAmountFieldMode === 'token') {
this.fromAmount = fromAmount
if (!this.fromSelectedToken) return
// Convert the field value to big int
const formattedAmount = parseUnits(
getSafeAmountFromFieldValue(fromAmount, this.fromSelectedToken.decimals),
this.fromSelectedToken.decimals
)
if (!formattedAmount) return
const { tokenPriceBigInt, tokenPriceDecimals } = convertTokenPriceToBigInt(tokenPrice)
this.fromAmountInFiat = formatUnits(
formattedAmount * tokenPriceBigInt,
// Shift the decimal point by the number of decimals in the token price
this.fromSelectedToken.decimals + tokenPriceDecimals
)
}
}
async #load() {
await this.#networks.initialLoadPromise
await this.#selectedAccount.initialLoadPromise
// FIXME: Temporarily omit getting prev activeRoutes from storage, because of
// old records with different (unexpected) structure causing crashes.
// this.activeRoutes = await this.#storage.get('swapAndBridgeActiveRoutes', [])
// FIXME: Figure out a mechanism to clean up these routes in storage,
// otherwise this is a potential storage leak (although we have unlimited storage permission).
// also, just in case protection: filter out ready routes as we don't have
// retry mechanism or follow up transaction handling anymore. Which means
// ready routes in the storage are just leftover routes.
// Same is true for completed, failed and refunded routes - they are just
// leftover routes in storage
// const filterOutStatuses = ['ready', 'completed', 'failed', 'refunded']
// this.activeRoutes = this.activeRoutes.filter((r) => !filterOutStatuses.includes(r.routeStatus))
this.#selectedAccount.onUpdate(() => {
this.#debounceFunctionCallsOnSameTick('updateFormOnSelectedAccountUpdate', async () => {
if (this.#selectedAccount.portfolio.isReadyToVisualize && this.sessionIds.length) {
this.isTokenListLoading = false
await this.updatePortfolioTokenList(
structuredClone(this.#selectedAccount.portfolio.tokens)
)
// To token list includes selected account portfolio tokens, it should get an update too
await this.updateToTokenList(false)
}
})
})
// Fetch the supported networks in the beginning so we can disable the
// swap and bridge button of unsupported tokens on the dashboard, even if
// the user hasn't yet opened the swap and bridge screen
// (forceEmit true is crucial here)
this.#fetchSupportedChainsIfNeeded(true)
}
// The token in portfolio is the source of truth for the amount, it updates
// on every balance (pending or anything) change.
#getFromSelectedTokenInPortfolio = () =>
this.portfolioTokenList.find(
(t) =>
t.address === this.fromSelectedToken?.address &&
t.chainId === this.fromSelectedToken?.chainId &&
// We skip the positive balance requirement here,
// because we only need to retrieve the token from the portfolio list
// and apply the basic eligibility checks (not a reward or Gas Tank token).
// Enforcing a positive balance would prevent tokens with zero balance
// from being found, which would break the MIN amount validation in `validateFromAmount()`.
getIsTokenEligibleForSwapAndBridge(t, false)
)
get maxFromAmount(): string {
const tokenRef = this.#getFromSelectedTokenInPortfolio() || this.fromSelectedToken
if (!tokenRef || getTokenAmount(tokenRef) === 0n || typeof tokenRef.decimals !== 'number')
return '0'
return formatUnits(getTokenAmount(tokenRef), tokenRef.decimals)
}
get maxFromAmountInFiat(): string {
const tokenRef = this.#getFromSelectedTokenInPortfolio() || this.fromSelectedToken
if (!tokenRef || getTokenAmount(tokenRef) === 0n) return '0'
const tokenPrice = tokenRef?.priceIn.find((p) => p.baseCurrency === HARD_CODED_CURRENCY)?.price
if (!tokenPrice || !Number(this.maxFromAmount)) return '0'
const maxAmount = getTokenAmount(tokenRef)
const { tokenPriceBigInt, tokenPriceDecimals } = convertTokenPriceToBigInt(tokenPrice)
// Multiply the max amount by the token price. The calculation is done in big int to avoid precision loss
return formatUnits(
BigInt(maxAmount) * tokenPriceBigInt,
// Shift the decimal point by the number of decimals in the token price
tokenRef.decimals + tokenPriceDecimals
)
}
get isFormEmpty() {
return (
!this.fromChainId ||
!this.toChainId ||
!this.fromAmount ||
!this.fromSelectedToken ||
!this.toSelectedToken
)
}
/**
* Returns an instance of the SignAccountOpController that is ALWAYS up-to-date with the current
* quote and the current form state.
*/
get signAccountOpController() {
const controllerFromQuoteId = this.#signAccountOpController?.accountOp.meta?.fromQuoteId
const isSignAccountOpCtrlStale =
controllerFromQuoteId && controllerFromQuoteId !== this.#updateQuoteId
if (isSignAccountOpCtrlStale) return null
return this.#signAccountOpController
}
get formStatus() {
if (this.hasProceeded) return SwapAndBridgeFormStatus.Proceeded
if (this.isFormEmpty) return SwapAndBridgeFormStatus.Empty
if (this.validateFromAmount.message || this.swapSignErrors.length)
return SwapAndBridgeFormStatus.Invalid
if (this.updateQuoteStatus === 'LOADING') return SwapAndBridgeFormStatus.FetchingRoutes
if (!this.quote || !this.quote.routes.length) return SwapAndBridgeFormStatus.NoRoutesFound
if (this.quote?.selectedRoute?.disabled) return SwapAndBridgeFormStatus.InvalidRouteSelected
if (
!this.signAccountOpController ||
this.signAccountOpController.estimation.status !== EstimationStatus.Success
)
return SwapAndBridgeFormStatus.ReadyToEstimate
return SwapAndBridgeFormStatus.ReadyToSubmit
}
get validateFromAmount(): Validation {
const fromSelectedTokenWithUpToDateAmount = this.#getFromSelectedTokenInPortfolio()
if (!fromSelectedTokenWithUpToDateAmount) return { severity: 'error', message: '' }
if (
!this.isFormEmpty &&
!this.quote &&
Object.values(this.quoteRoutesStatuses).some((val) => val.status === 'MIN_AMOUNT_NOT_MET')
) {
return {
severity: 'success',
message: '🔔 A route was found for this pair but the minimum token amount was not met.'
}
}
return validateSendTransferAmount(this.fromAmount, fromSelectedTokenWithUpToDateAmount)
}
get activeRoutesInProgress() {
return this.activeRoutes.filter((r) => r.routeStatus === 'in-progress' && r.userTxHash)
}
get activeRoutes() {
return this.#activeRoutes
}
set activeRoutes(value: SwapAndBridgeActiveRoute[]) {
this.#activeRoutes = value
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.#storage.set('swapAndBridgeActiveRoutes', value)
if (!this.activeRoutesInProgress.length) {
this.#updateActiveRoutesInterval.stop()
return
}
const minServiceTime = getActiveRoutesLowestServiceTime(this.activeRoutesInProgress)
if (!this.#updateActiveRoutesInterval.running) {
this.#updateActiveRoutesInterval.start({ timeout: minServiceTime })
return
}
// If the interval is running, check if minServiceTime * 2 is still less than currentTimeout.
// If it is, restart it with the new minServiceTime, as the difference makes it worth it.
if (minServiceTime * 2 < this.#updateActiveRoutesInterval.currentTimeout) {
this.#updateActiveRoutesInterval.restart({ timeout: minServiceTime })
}
}
get shouldEnableRoutesSelection() {
return (
!!this.quote &&
!!this.quote.routes &&
this.quote.routes.length > 0 &&
this.updateQuoteStatus !== 'LOADING'
)
}
async initForm(
sessionId: string,
params?: {
preselectedFromToken?: Pick<TokenResult, 'address' | 'chainId'>
preselectedToToken?: Pick<TokenResult, 'address' | 'chainId'>
fromAmount?: string
activeRouteIdToDelete?: SwapAndBridgeSendTxRequest['activeRouteId']
}
) {
const { preselectedFromToken, preselectedToToken, fromAmount, activeRouteIdToDelete } =
params || {}
await this.#initialLoadPromise
// if the provider is socket, convert the null addresses
if (preselectedFromToken) {
this.#emitSilentErrorIfNullAddress(preselectedFromToken.address)
preselectedFromToken.address = mapBannedToValidAddr(
Number(preselectedFromToken.chainId),
convertNullAddressToZeroAddressIfNeeded(preselectedFromToken.address)
)
}
if (preselectedToToken) {
this.#emitSilentErrorIfNullAddress(preselectedToToken.address)
preselectedToToken.address = mapBannedToValidAddr(
Number(preselectedToToken.chainId),
convertNullAddressToZeroAddressIfNeeded(preselectedToToken.address)
)
}
if (this.sessionIds.includes(sessionId)) return
// reset only if there are no other instances opened/active
if (!this.sessionIds.length) {
this.reset() // clear prev session form state
// for each new session remove the completed activeRoutes from the previous session
this.activeRoutes = this.activeRoutes.filter((r) => r.routeStatus !== 'completed')
// remove activeRoutes errors from the previous session
this.activeRoutes.forEach((r) => {
if (r.routeStatus !== 'failed') {
delete r.error
}
})
if (this.activeRoutes.length) {
// Otherwise there may be an emitUpdate with [] tokens
this.isTokenListLoading = true
// update the activeRoute.route prop for the new session
this.activeRoutes.forEach((r) => {
this.updateActiveRoute(r.activeRouteId, undefined, true)
})
}
}
this.sessionIds.push(sessionId)
// do not await the health status check to prevent UI freeze while fetching
this.#serviceProviderAPI.updateHealth()
await this.updatePortfolioTokenList(structuredClone(this.#selectedAccount.portfolio.tokens), {
preselectedToken: preselectedFromToken,
preselectedToToken,
fromAmount
})
this.isTokenListLoading = false
// Do not await on purpose as it's not critical for the controller state to be ready
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.#fetchSupportedChainsIfNeeded()
if (activeRouteIdToDelete) {
await this.removeFailedRouteAndHideBanner(activeRouteIdToDelete)
}
this.#emitUpdateIfNeeded()
}
// Temporary helper to monitor if NULL token addresses are still passed
// to initForm or updateForm in the Swap & Bridge controller.
// In theory, this should no longer happen after the fixes in socket/api.ts,
// but we'll keep tracking it in Sentry for about a month to confirm.
// If no errors are reported, we'll remove both this function and the
// convertNullAddressToZeroAddressIfNeeded logic from initForm/updateForm.
#emitSilentErrorIfNullAddress(address: string) {
if (address.toLocaleLowerCase() === NULL_ADDRESS) {
const message =
'NULL token address detected while updating or initializing the Swap & Bridge controller.'
this.emitError({
level: 'silent',
message,
error: new Error(message)
})
}
}
get isHealthy() {
return this.#serviceProviderAPI.isHealthy
}
#fetchSupportedChainsIfNeeded = async (forceUpdate?: boolean) => {
const shouldNotReFetchSupportedChains =
this.#cachedSupportedChains.data.length &&
Date.now() - this.#cachedSupportedChains.lastFetched < SUPPORTED_CHAINS_CACHE_THRESHOLD
if (shouldNotReFetchSupportedChains) return
try {
const supportedChains = await this.#serviceProviderAPI.getSupportedChains()
this.#cachedSupportedChains = { lastFetched: Date.now(), data: supportedChains }
this.#emitUpdateIfNeeded(forceUpdate)
} catch (error: any) {
// Fail silently, as this is not a critical feature, Swap & Bridge is still usable
this.emitError({ error, level: 'silent', message: error?.message })
}
}
get supportedChainIds(): Network['chainId'][] {
return this.#cachedSupportedChains.data.map((c) => BigInt(c.chainId))
}
get #toTokenListKey(): CachedTokenListKey | null {
if (this.fromChainId === null || this.toChainId === null) return null
return `from-${this.fromChainId}-to-${this.toChainId}`
}
// Get the toTokenListKey from parameters instead of `this`,
// because during async execution, the class state may already point
// to a different chain pair.
static getToTokenListKey(
fromChainId: number | null,
toChainId: number | null
): CachedTokenListKey | null {
if (fromChainId === null || toChainId === null) return null
return `from-${fromChainId}-to-${toChainId}`
}
unloadScreen(sessionId: string, forceUnload?: boolean) {
const isFormDirty = !!this.fromAmount || !!this.toSelectedToken
const shouldPersistState = isFormDirty && sessionId === 'popup' && !forceUnload
if (shouldPersistState) return
this.sessionIds = this.sessionIds.filter((id) => id !== sessionId)
if (!this.sessionIds.length) {
this.reset(true)
// Reset health to prevent the error state from briefly flashing
// before the next health check resolves when the Swap & Bridge
// screen is opened after a some time
this.#serviceProviderAPI.resetHealth()
}
this.hasProceeded = false
}
addOrUpdateError(error: SwapAndBridgeErrorType) {
const errorIndex = this.errors.findIndex((e) => e.id === error.id)
if (errorIndex === -1) {
this.errors.push(error)
} else {
this.errors[errorIndex] = error
}
this.#emitUpdateIfNeeded()
}
removeError(id: SwapAndBridgeErrorType['id'], shouldEmit?: boolean) {
this.errors = this.errors.filter((e) => e.id !== id)
if (shouldEmit) this.#emitUpdateIfNeeded()
}
async updateForm(
props: {
fromAmount?: string
fromAmountInFiat?: string
shouldSetMaxAmount?: boolean
fromAmountFieldMode?: 'fiat' | 'token'
fromSelectedToken?: TokenResult | null
toChainId?: bigint | number
toSelectedTokenAddr?: SwapAndBridgeToToken['address'] | null
routePriority?: 'output' | 'time'
activeRouteIdToDelete?: SwapAndBridgeSendTxRequest['activeRouteId']
},
updateProps?: {
emitUpdate?: boolean
updateQuote?: boolean
shouldIncrementFromAmountUpdateCounter?: boolean
}
) {
const {
fromAmount,
fromAmountInFiat,
fromAmountFieldMode,