-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathtransfer.ts
More file actions
1284 lines (1049 loc) · 40.7 KB
/
Copy pathtransfer.ts
File metadata and controls
1284 lines (1049 loc) · 40.7 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, isAddress, parseUnits } from 'ethers'
import { BindedRelayerCall } from '@/libs/relayerCall/relayerCall'
import { FEE_COLLECTOR } from '../../consts/addresses'
import { IAccountsController } from '../../interfaces/account'
import { IActivityController } from '../../interfaces/activity'
import { IAddressBookController } from '../../interfaces/addressBook'
import { IDappsController } from '../../interfaces/dapp'
import { AddressState } from '../../interfaces/domains'
import { IEventEmitterRegistryController } from '../../interfaces/eventEmitter'
import { ExternalSignerControllers, IKeystoreController } from '../../interfaces/keystore'
import { INetworksController } 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 } from '../../interfaces/signAccountOp'
import { IStorageController } from '../../interfaces/storage'
import {
AddressPoisoningMatch,
ITransferController,
TransferUpdate
} from '../../interfaces/transfer'
import { IUiController, View } from '../../interfaces/ui'
import { getBaseAccount } from '../../libs/account/getBaseAccount'
import { AccountOp } from '../../libs/accountOp/accountOp'
import { Call } from '../../libs/accountOp/types'
import { AssetType } from '../../libs/defiPositions/types'
import { getAmbirePaymasterService } from '../../libs/erc7677/erc7677'
import { HumanizerMeta } from '../../libs/humanizer/interfaces'
import { randomId } from '../../libs/humanizer/utils'
import { TokenResult } from '../../libs/portfolio'
import { getTokenAmount, getTokenBalanceInUSD } from '../../libs/portfolio/helpers'
import {
getAmountAfterFeeReserve,
getAmountAfterFeeSync,
getSanitizedAmount
} from '../../libs/transfer/amount'
import { getTransferRequestParams } from '../../libs/transfer/userRequest'
import {
validateSendTransferAddress,
validateSendTransferAmount,
Validation
} from '../../services/validations'
import { getIsViewOnly } from '../../utils/accounts'
import { getAddressFromAddressState, getDomainFromAddressState } from '../../utils/domains'
import {
convertTokenPriceToBigInt,
getSafeAmountFromFieldValue
} from '../../utils/numbers/formatters'
import { generateUuid } from '../../utils/uuid'
import EventEmitter from '../eventEmitter/eventEmitter'
import { OnBroadcastSuccess, SignAccountOpController } from '../signAccountOp/signAccountOp'
import { SignAccountOpPreferenceController } from '../signAccountOp/signAccountOpPreference'
const CONVERSION_PRECISION = 16
const CONVERSION_PRECISION_POW = BigInt(10 ** CONVERSION_PRECISION)
const DEFAULT_ADDRESS_STATE: AddressState = {
fieldValue: '',
resolvedAddress: '',
resolvedAddressType: null,
isDomainResolving: false
}
const DEFAULT_VALIDATION_FORM_MSGS: {
[key in 'amount' | 'recipientAddress']: Validation
} = {
amount: {
severity: 'error',
message: ''
},
recipientAddress: {
message: '',
severity: 'error'
}
}
const HARD_CODED_CURRENCY = 'usd'
const isTransfer = (route: string | undefined) => {
return route === 'transfer' || route === 'top-up-gas-tank'
}
type SignAccountOpControllerMethods = {
[K in keyof SignAccountOpController as SignAccountOpController[K] extends (...args: any) => any
? K
: never]: SignAccountOpController[K]
}
export class TransferController extends EventEmitter implements ITransferController {
#callRelayer: BindedRelayerCall
#storage: IStorageController
#signAccountOpPreference: SignAccountOpPreferenceController
#networks: INetworksController
#addressBook: IAddressBookController
#selectedToken: TokenResult | null = null
#selectedAccount: ISelectedAccountController
#humanizerInfo: HumanizerMeta | null = null
// session / debounce
#currentTransferSessionId: string | null = null
/**
* The field value for the amount input. Not sanitized and can contain
* invalid values. Use #getSafeAmountFromFieldValue() to get a formatted value.
*/
amount = ''
amountInFiat = ''
/**
* A counter used to trigger UI updates when a form values is
* changed programmatically by the controller.
*/
programmaticUpdateCounter = 0
amountFieldMode: 'fiat' | 'token' = 'token'
addressState: AddressState = { ...DEFAULT_ADDRESS_STATE }
areDefaultsSet = false
isRecipientAddressUnknown = false
isRecipientAddressUnknownAgreed = false
isRecipientHumanizerKnownTokenOrSmartContract = false
isRecipientAddressViewOnly = false
isTopUp: boolean = false
#shouldSkipTransactionQueuedModal: boolean = false
#isMaxAmountSelected: boolean = false
#maxFeeReservation: { key: string; amount: bigint } | null = null
#accounts: IAccountsController
#keystore: IKeystoreController
#portfolio: IPortfolioController
#externalSignerControllers: ExternalSignerControllers
#providers: IProvidersController
#phishing: IPhishingController
#dapps: IDappsController
#relayerUrl: string
isRecipientAddressFirstTimeSend: boolean = false
lastSentToRecipientAt: Date | null = null
// Set only for first-time sends when the recipient matches a known address
// by both prefix and suffix, which may indicate address poisoning.
addressPoisoningMatch: AddressPoisoningMatch | null = null
/**
* Set when the recipient is a domain (ENS/Namoshi) the user has sent to before, but it now resolves
* to a DIFFERENT address than last time (possible expiry/snipe).
*/
recipientDomainAddressChange: { previousAddress: string } | null = null
signAccountOpController: ISignAccountOpController | null = null
latestBroadcastedAccountOp: AccountOp | null = null
latestBroadcastedToken: TokenResult | null = null
hasProceeded: boolean = false
// Holds the initial load promise, so that one can wait until it completes
#initialLoadPromise?: Promise<void>
#activity: IActivityController
#onBroadcastSuccess: OnBroadcastSuccess
#ui: IUiController
#tokens: TokenResult[] = []
#getHasAnotherTransferViewOpen() {
const views = this.#ui.views.filter((view) => isTransfer(view.currentRoute))
return views.length >= 1
}
constructor(
callRelayer: BindedRelayerCall,
storage: IStorageController,
signAccountOpPreference: SignAccountOpPreferenceController,
humanizerInfo: HumanizerMeta,
selectedAccount: ISelectedAccountController,
networks: INetworksController,
addressBook: IAddressBookController,
accounts: IAccountsController,
keystore: IKeystoreController,
portfolio: IPortfolioController,
activity: IActivityController,
externalSignerControllers: ExternalSignerControllers,
providers: IProvidersController,
phishing: IPhishingController,
dapps: IDappsController,
relayerUrl: string,
onBroadcastSuccess: OnBroadcastSuccess,
ui: IUiController,
eventEmitterRegistry?: IEventEmitterRegistryController
) {
super(eventEmitterRegistry)
this.#callRelayer = callRelayer
this.#storage = storage
this.#signAccountOpPreference = signAccountOpPreference
this.#humanizerInfo = humanizerInfo
this.#selectedAccount = selectedAccount
this.#networks = networks
this.#addressBook = addressBook
this.#accounts = accounts
this.#keystore = keystore
this.#portfolio = portfolio
this.#activity = activity
this.#externalSignerControllers = externalSignerControllers
this.#providers = providers
this.#phishing = phishing
this.#dapps = dapps
this.#relayerUrl = relayerUrl
this.#onBroadcastSuccess = onBroadcastSuccess
this.#ui = ui
this.#initialLoadPromise = this.#load().finally(() => {
this.#initialLoadPromise = undefined
})
this.#ui.uiEvent.on('updateView', (view: View) => {
if (isTransfer(view.currentRoute)) {
this.#enterTransfer(view)
} else if (isTransfer(view.previousRoute) && !this.#getHasAnotherTransferViewOpen()) {
// Update view is handled differently as it implies that the user has
// navigated out to another route, thus state persistence is irrelevant
this.unloadScreen(view.type, { isNavigateOut: true })
}
})
this.#ui.uiEvent.on('removeView', (view: View) => {
if (!isTransfer(view.currentRoute) || this.#getHasAnotherTransferViewOpen()) return
this.unloadScreen(view.type)
})
this.#selectedAccount.onUpdate(async (forceEmit) => {
// Don't update anything if the transfer screen is not open or
// if the user has proceeded with the transfer and is about to sign/broadcast
if (!this.#currentTransferSessionId || this.hasProceeded) return
this.#setTokens()
if (this.#selectedAccount.portfolio.isReadyToVisualize && !this.selectedToken) {
this.#setDefaultSelectedToken()
if (this.selectedToken || this.#selectedAccount.portfolio.isAllReady)
this.areDefaultsSet = true
}
this.propagateUpdate(forceEmit)
})
this.emitUpdate()
}
#enterTransfer(view: View) {
this.#ensureTransferSessionId()
const nextIsTopUp = view.currentRoute === 'top-up-gas-tank'
const searchParams = view.searchParams
const isFormInitialized = this.hasPersistedState && this.areDefaultsSet
const isSameMode = this.isTopUp === nextIsTopUp
const hasNoSearchParams = Object.keys(searchParams || {}).length === 0
const shouldKeepExistingForm =
isFormInitialized && isSameMode && hasNoSearchParams && view.type !== 'side-panel'
if (shouldKeepExistingForm) {
if (!this.areDefaultsSet) {
this.areDefaultsSet = true
this.emitUpdate()
}
return
}
const tokenParams =
searchParams && searchParams.address && searchParams.chainId
? {
address: String(searchParams.address),
chainId: String(searchParams.chainId)
}
: undefined
this.isTopUp = nextIsTopUp
this.#setTokens()
this.#setDefaultSelectedToken(tokenParams)
this.areDefaultsSet = true
this.emitUpdate()
}
#ensureTransferSessionId() {
if (!this.#currentTransferSessionId) {
this.#currentTransferSessionId = String(randomId())
}
}
get transferSessionId() {
return this.#currentTransferSessionId
}
#setTokens() {
const tokens = this.#selectedAccount.portfolio.tokens
.filter((token) => {
const hasAmount = Number(getTokenAmount(token)) > 0
const isVisible = !token.flags.isHidden
if (this.isTopUp) {
const tokenNetwork = this.#networks.networks.find(
(network) => network.chainId === token.chainId
)
return (
hasAmount &&
isVisible &&
tokenNetwork?.hasRelayer &&
token.flags.canTopUpGasTank &&
!token.flags.onGasTank
)
}
return (
hasAmount &&
isVisible &&
!token.flags.onGasTank &&
!token.flags.rewardsType &&
token.flags.defiTokenType !== AssetType.Borrow
)
})
.sort((a, b) => {
const tokenAinUSD = getTokenBalanceInUSD(a)
const tokenBinUSD = getTokenBalanceInUSD(b)
return tokenBinUSD - tokenAinUSD
})
this.#tokens = tokens
if (this.selectedToken) {
this.selectedToken =
this.#tokens.find(
(t) =>
t.address === this.selectedToken?.address &&
t.chainId === this.selectedToken?.chainId &&
!t.flags.onGasTank
) ||
this.#tokens[0] ||
null
}
}
#setDefaultSelectedToken(tokenData?: { address: string; chainId: string | number }) {
if (!this.#tokens.length) return
const tokenAddress = tokenData?.address.toLowerCase() || ''
const tokenChainId = tokenData?.chainId.toString() || ''
let newSelectedToken = null
// 1. If a valid address is provided → try to match it
if (tokenAddress) {
newSelectedToken = this.#tokens.find(
(t: TokenResult) =>
t.address.toLowerCase() === tokenAddress &&
tokenChainId === t.chainId.toString() &&
t.flags.onGasTank === false
)
}
// 2. If no valid address or no match → fallback to first token
if (!newSelectedToken) newSelectedToken = this.#tokens[0]
// 3. Only update if changed
if (
newSelectedToken &&
(!this.selectedToken ||
this.selectedToken.address !== newSelectedToken.address ||
this.selectedToken.chainId !== newSelectedToken.chainId)
) {
this.selectedToken = newSelectedToken
// 4. Or if the user has no tokens
} else if (!newSelectedToken) {
this.selectedToken = null
this.areDefaultsSet = true
}
}
async #load() {
this.#shouldSkipTransactionQueuedModal = await this.#storage.get(
'shouldSkipTransactionQueuedModal',
false
)
await this.#selectedAccount.initialLoadPromise
}
get shouldSkipTransactionQueuedModal() {
return this.#shouldSkipTransactionQueuedModal
}
set shouldSkipTransactionQueuedModal(value: boolean) {
this.#shouldSkipTransactionQueuedModal = value
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.#storage.set('shouldSkipTransactionQueuedModal', value)
this.emitUpdate()
}
// every time when updating selectedToken update the amount and maxAmount of the form
set selectedToken(token: TokenResult | null) {
// Disallow the update of the selected token if the user has proceeded.
// If we update it, latestBroadcastedToken may not correspond to the token that
// is being sent in the latestBroadcastedAccountOp.
if (this.hasProceeded) return
if (!token || Number(getTokenAmount(token)) === 0) {
this.#selectedToken = null
this.#isMaxAmountSelected = false
this.#resetMaxFeeReservation()
this.#setAmountAndNotifyUI('')
this.#setAmountInFiatAndNotifyUI('')
this.amountFieldMode = 'token'
return
}
const prevSelectedToken = { ...this.selectedToken }
this.#selectedToken = token
if (
prevSelectedToken?.address !== token?.address ||
prevSelectedToken?.chainId !== token?.chainId
) {
this.#isMaxAmountSelected = false
this.#resetMaxFeeReservation()
if (!token.priceIn.length) this.amountFieldMode = 'token'
this.#setAmountAndNotifyUI('')
this.#setAmountInFiatAndNotifyUI('')
}
}
get selectedToken() {
return this.#selectedToken
}
get tokens() {
return this.#tokens
}
get maxAmount(): string {
if (!this.selectedToken || getTokenAmount(this.selectedToken) === 0n) return '0'
return formatUnits(getTokenAmount(this.selectedToken), this.selectedToken.decimals)
}
get maxAmountInFiat(): string {
if (!this.selectedToken || getTokenAmount(this.selectedToken) === 0n) return '0'
const tokenPrice = this.selectedToken?.priceIn.find(
(p) => p.baseCurrency === HARD_CODED_CURRENCY
)?.price
if (!tokenPrice || !Number(this.maxAmount)) return '0'
const maxAmount = getTokenAmount(this.selectedToken)
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(
maxAmount * tokenPriceBigInt,
// Shift the decimal point by the number of decimals in the token price
this.selectedToken.decimals + tokenPriceDecimals
)
}
resetForm(shouldDestroyAccountOp = true) {
this.#isMaxAmountSelected = false
this.amount = ''
this.amountInFiat = ''
this.amountFieldMode = 'token'
this.addressState = { ...DEFAULT_ADDRESS_STATE }
this.#onRecipientAddressChange()
// This MUST be incremented and not reset to zero, because the UI relies on
// the change of this value. If the value was 0 and is reset to 0, the UI
// would not detect a change.
if (this.programmaticUpdateCounter === 0) {
this.programmaticUpdateCounter += 1
} else {
this.programmaticUpdateCounter = 0
}
if (shouldDestroyAccountOp) {
this.destroySignAccountOp()
}
this.emitUpdate()
}
#fetchRecipientAccountStateIfNeeded() {
if (!this.isInitialized) return
const recipientAcc = this.#accounts.accounts.find((a) => a.addr === this.recipientAddress)
if (recipientAcc && this.selectedToken?.chainId) {
const state =
this.#accounts.accountStates[recipientAcc.addr]?.[this.selectedToken.chainId.toString()]
if (!state) {
this.#accounts
.getOrFetchAccountOnChainState(recipientAcc.addr, this.selectedToken.chainId)
.catch((e) => {
console.log('Failed to get the account on chain state:', e)
})
}
}
}
get validationFormMsgs() {
if (!this.isInitialized) return DEFAULT_VALIDATION_FORM_MSGS
const validationFormMsgsNew = DEFAULT_VALIDATION_FORM_MSGS
if (this.#humanizerInfo && this.#selectedAccount.account?.addr) {
// if the recipientAcc is an account in the extension
// & the account state is not fetched for it, fetch it
// so that we could validate the account properly
// example: Safe accounts may not be deployed on certain networks
const recipientAcc = this.#accounts.accounts.find((a) => a.addr === this.recipientAddress)
validationFormMsgsNew.recipientAddress = validateSendTransferAddress(
this.recipientAddress,
this.#selectedAccount.account.addr,
this.isRecipientAddressUnknownAgreed,
this.isRecipientAddressUnknown,
this.isRecipientHumanizerKnownTokenOrSmartContract,
!!this.addressState.resolvedAddress,
this.addressState.isDomainResolving,
this.#networks.networks,
this.#accounts.accountStates,
recipientAcc,
this.selectedToken?.chainId,
this.isRecipientAddressFirstTimeSend,
this.lastSentToRecipientAt,
this.addressPoisoningMatch,
this.recipientDomainAddressChange
)
}
// Validate the amount
if (this.selectedToken) {
validationFormMsgsNew.amount = validateSendTransferAmount(this.amount, this.selectedToken)
}
return validationFormMsgsNew
}
get isFormValid() {
if (!this.isInitialized) return false
// if the amount is set, it's enough in topUp mode
if (this.isTopUp) {
return (
this.selectedToken &&
validateSendTransferAmount(this.amount, this.selectedToken).severity === 'success'
)
}
const areFormFieldsValid = this.validationFormMsgs.amount.severity === 'success'
return areFormFieldsValid && !this.addressState.isDomainResolving
}
get isInitialized() {
return (
!!this.#humanizerInfo &&
!!this.#selectedAccount.account?.addr &&
!!this.#networks.networks.length
)
}
get recipientAddress() {
return getAddressFromAddressState(this.addressState)
}
async update({
humanizerInfo,
selectedToken,
amount,
shouldSetMaxAmount,
addressState,
isRecipientAddressUnknownAgreed,
amountFieldMode
}: TransferUpdate) {
if (humanizerInfo) {
this.#humanizerInfo = humanizerInfo
}
if (amountFieldMode) {
this.amountFieldMode = amountFieldMode
}
if (selectedToken) {
if (this.selectedToken && selectedToken.chainId !== this.selectedToken.chainId) {
// The SignAccountOp controller is already initialized with the previous chainId and account operation.
// When the chainId changes, we need to recreate the controller to correctly estimate for the new chain.
// Here, we destroy it, and at the end of this update method, we initialize it again.
this.destroySignAccountOp()
}
this.selectedToken = selectedToken
this.#fetchRecipientAccountStateIfNeeded()
}
// If we do a regular check the value won't update if it's '' or '0'
if (typeof amount === 'string') {
this.#isMaxAmountSelected = false
this.#resetMaxFeeReservation()
this.#setAmount(amount)
}
if (shouldSetMaxAmount) {
const maxAmountAfterFeeReservation = this.#getMaxAmountAfterFeeReservation()
if (!Number(maxAmountAfterFeeReservation)) return
this.#isMaxAmountSelected = true
this.#resetMaxFeeReservation()
this.amountFieldMode = 'token'
this.#setTokenAmount(maxAmountAfterFeeReservation, true)
}
if (addressState) {
this.addressState = {
...this.addressState,
...addressState
}
if (this.isInitialized) {
this.#onRecipientAddressChange()
}
}
// We can do a regular check here, because the property defines if it should be updated
// and not the actual value
if (isRecipientAddressUnknownAgreed) {
this.isRecipientAddressUnknownAgreed = !this.isRecipientAddressUnknownAgreed
}
await this.#updateRecipientHistoryAndPoisoning()
await this.syncSignAccountOp()
this.emitUpdate()
}
checkIsRecipientAddressUnknown() {
if (!isAddress(this.recipientAddress)) {
this.isRecipientAddressUnknown = false
this.isRecipientAddressUnknownAgreed = false
this.emitUpdate()
return
}
const isAddressInAddressBook = this.#addressBook.contacts.some(
({ address }) => address.toLowerCase() === this.recipientAddress.toLowerCase()
)
this.isRecipientAddressUnknown =
!isAddressInAddressBook &&
this.recipientAddress.toLowerCase() !== this.#selectedAccount.account?.addr.toLowerCase() &&
this.recipientAddress.toLowerCase() !== FEE_COLLECTOR.toLowerCase()
this.isRecipientAddressUnknownAgreed = false
this.emitUpdate()
}
checkIsRecipientAddressViewOnly() {
const recipientAccount = this.#accounts.accounts.find(
({ addr }) => addr.toLowerCase() === this.recipientAddress.toLowerCase()
)
if (recipientAccount) {
const isViewOnly = getIsViewOnly(this.#keystore.keys, recipientAccount.associatedKeys)
this.isRecipientAddressViewOnly = isViewOnly
} else {
this.isRecipientAddressViewOnly = false
}
}
#onRecipientAddressChange() {
if (!isAddress(this.recipientAddress)) {
this.isRecipientAddressUnknown = false
this.isRecipientAddressUnknownAgreed = false
this.isRecipientHumanizerKnownTokenOrSmartContract = false
this.isRecipientAddressFirstTimeSend = false
this.lastSentToRecipientAt = null
this.addressPoisoningMatch = null
this.recipientDomainAddressChange = null
this.isRecipientAddressViewOnly = false
return
}
if (this.#humanizerInfo) {
// @TODO: could fetch address code
this.isRecipientHumanizerKnownTokenOrSmartContract =
!!this.#humanizerInfo.knownAddresses[this.recipientAddress]?.isSC
}
this.checkIsRecipientAddressViewOnly()
this.checkIsRecipientAddressUnknown()
this.#fetchRecipientAccountStateIfNeeded()
}
#setAmountAndNotifyUI(amount: string) {
this.amount = amount
this.programmaticUpdateCounter += 1
}
#setAmountInFiatAndNotifyUI(amountInFiat: string) {
this.amountInFiat = amountInFiat
this.programmaticUpdateCounter += 1
}
#setAmount(fieldValue: string, isProgrammaticUpdate = false) {
if (isProgrammaticUpdate) {
// There is no problem in updating this first as there are no
// emit updates in this method
this.programmaticUpdateCounter += 1
}
if (!fieldValue) {
this.amount = ''
this.amountInFiat = ''
return
}
const tokenPrice = this.selectedToken?.priceIn.find(
(p) => p.baseCurrency === HARD_CODED_CURRENCY
)?.price
if (!tokenPrice) {
this.amount = fieldValue
this.amountInFiat = ''
return
}
if (this.amountFieldMode === 'fiat' && typeof this.selectedToken?.decimals === 'number') {
this.amountInFiat = fieldValue
// Get the number of decimals
const amountInFiatDecimals = 10
const { tokenPriceBigInt, tokenPriceDecimals } = convertTokenPriceToBigInt(tokenPrice)
// Convert the numbers to big int
const sanitizedFiat = getSanitizedAmount(fieldValue, amountInFiatDecimals)
const amountInFiatBigInt = sanitizedFiat
? parseUnits(sanitizedFiat, amountInFiatDecimals)
: 0n
this.amount = 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.amountFieldMode === 'token') {
this.amount = fieldValue
if (!this.selectedToken) return
const formattedAmount = parseUnits(
getSafeAmountFromFieldValue(fieldValue, this.selectedToken.decimals),
this.selectedToken.decimals
)
if (!formattedAmount) return
const { tokenPriceBigInt, tokenPriceDecimals } = convertTokenPriceToBigInt(tokenPrice)
this.amountInFiat = formatUnits(
formattedAmount * tokenPriceBigInt,
// Shift the decimal point by the number of decimals in the token price
this.selectedToken.decimals + tokenPriceDecimals
)
}
}
#setTokenAmount(amount: string, isProgrammaticUpdate = false) {
const amountFieldMode = this.amountFieldMode
this.amountFieldMode = 'token'
this.#setAmount(amount, isProgrammaticUpdate)
this.amountFieldMode = amountFieldMode
}
#getMaxAmountAfterFeeReservation() {
if (!this.selectedToken) return this.maxAmount
const totalTokenAmount = getTokenAmount(this.selectedToken)
const gasFeePayment = this.signAccountOpController?.accountOp.gasFeePayment
if (!this.#shouldReserveFeeFromTransferredToken() || !gasFeePayment) {
return formatUnits(totalTokenAmount, this.selectedToken.decimals)
}
return formatUnits(
getAmountAfterFeeReserve(totalTokenAmount, gasFeePayment.amount),
this.selectedToken.decimals
)
}
#resetMaxFeeReservation() {
this.#maxFeeReservation = null
}
/**
* Get an unique key to know when to change the calculations
*/
#getMaxFeeReservationKey() {
const gasFeePayment = this.signAccountOpController?.accountOp.gasFeePayment
const selectedFeeOption = this.signAccountOpController?.selectedOption
const selectedToken = this.selectedToken
if (!gasFeePayment || !selectedFeeOption || !selectedToken) return null
return [
selectedToken.chainId.toString(),
selectedToken.address.toLowerCase(),
selectedFeeOption.paidBy.toLowerCase(),
selectedFeeOption.token.chainId.toString(),
selectedFeeOption.token.address.toLowerCase(),
selectedFeeOption.token.flags.onGasTank ? 'gas-tank' : 'account',
this.signAccountOpController?.selectedFeeSpeed || '',
gasFeePayment.broadcastOption
].join(':')
}
/**
* The MAX amount you can set was reacting to every small fee estimate change.
* When ARB was both the transfer token and fee token, that created a feedback cycle:
* fee changes amount, amount re-estimates fee, repeat.
* We're changing the MAX same-token fee reservation to keep the highest fee seen for
* the current fee token/payer/speed, so the amount can decrease to remain safe
* but won’t bounce back upward and retrigger the loop.
*/
#getMaxReservedFeeAmount(feeAmount: bigint) {
const key = this.#getMaxFeeReservationKey()
if (!key) return feeAmount
if (
!this.#maxFeeReservation ||
this.#maxFeeReservation.key !== key ||
this.#maxFeeReservation.amount < feeAmount
) {
this.#maxFeeReservation = {
key,
amount: feeAmount
}
}
return this.#maxFeeReservation.amount
}
#shouldReserveFeeFromTransferredToken() {
const gasFeePayment = this.signAccountOpController?.accountOp.gasFeePayment
const selectedFeeOption = this.signAccountOpController?.selectedOption
const selectedToken = this.selectedToken
const accountAddr = this.#selectedAccount.account?.addr.toLowerCase()
if (!accountAddr || !gasFeePayment || !selectedFeeOption || !selectedToken) return false
if (selectedFeeOption.token.flags.onGasTank) return false
if (selectedFeeOption.paidBy.toLowerCase() !== accountAddr) return false
const selectedTokenAddress = selectedToken.address.toLowerCase()
return (
!!accountAddr &&
!!gasFeePayment &&
!!selectedFeeOption &&
selectedFeeOption.paidBy.toLowerCase() === accountAddr &&
selectedFeeOption.token.chainId === selectedToken.chainId &&
selectedFeeOption.token.address.toLowerCase() === selectedTokenAddress &&
gasFeePayment.inToken.toLowerCase() === selectedTokenAddress &&
(!gasFeePayment.feeTokenChainId || gasFeePayment.feeTokenChainId === selectedToken.chainId)
)
}
#syncAmountWithFeeReservation(forceEmit?: boolean) {
if (!this.amount || !this.selectedToken || typeof this.selectedToken.decimals !== 'number')
return false
const totalTokenAmount = getTokenAmount(this.selectedToken)
const shouldReserveFee = this.#shouldReserveFeeFromTransferredToken()
const gasFeePayment = this.signAccountOpController?.accountOp.gasFeePayment
const fee = shouldReserveFee ? gasFeePayment?.amount || 0n : 0n
const reservedFee =
shouldReserveFee && this.#isMaxAmountSelected ? this.#getMaxReservedFeeAmount(fee) : fee
if (!shouldReserveFee) this.#resetMaxFeeReservation()
const currentAmount = this.amount
? parseUnits(
getSafeAmountFromFieldValue(this.amount, this.selectedToken.decimals),
this.selectedToken.decimals
)
: 0n
const desiredAmount = getAmountAfterFeeSync({
currentAmount,
totalAmount: totalTokenAmount,
fee,
reservedFee,
shouldReserveFee,
isMaxAmountSelected: this.#isMaxAmountSelected
})
if (desiredAmount === 0n || currentAmount === desiredAmount) return false
this.#setTokenAmount(formatUnits(desiredAmount, this.selectedToken.decimals), true)
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.syncSignAccountOp()
this.propagateUpdate(forceEmit)
return true
}
/**
* When doing a MAX transfer or a close to MAX transfer out,
* if the selected fee token is the same as the transfer token,
* we automatically adjust the transfer amount so the user
* can successfully broadcast. For that, we put an additional
* warning telling him why this is happening
*/
get amountAdjustmentWarning(): Validation | null {
if (!this.amount || !this.selectedToken || !this.#shouldReserveFeeFromTransferredToken()) {
return null
}
const gasFeePayment = this.signAccountOpController?.accountOp.gasFeePayment
if (!gasFeePayment) return null
const currentAmount = parseUnits(
getSafeAmountFromFieldValue(this.amount, this.selectedToken.decimals),
this.selectedToken.decimals
)
const totalTokenAmount = getTokenAmount(this.selectedToken)
const maxAmountAfterFeeReservation = getAmountAfterFeeReserve(
totalTokenAmount,
gasFeePayment.amount
)
if (
maxAmountAfterFeeReservation > 0n &&
currentAmount > 0n &&
currentAmount + gasFeePayment.amount >= totalTokenAmount
) {
return {
severity: 'warning',
message: 'Amount adjusted to cover blockchain fees'
}
}
return null
}
async #updateRecipientHistoryAndPoisoning() {
// Check if the address has been used previously for transactions
let found = false
let lastTransactionDate = null
let addressPoisoningMatch = null
if (isAddress(this.recipientAddress)) {
const result = await this.#activity.hasAccountOpsSentTo(
this.recipientAddress,
this.#selectedAccount.account?.addr || ''
)
found = result.found
lastTransactionDate = result.lastTransactionDate
addressPoisoningMatch = result.addressPoisoningMatch