-
-
Notifications
You must be signed in to change notification settings - Fork 288
Expand file tree
/
Copy pathRampsController.ts
More file actions
3219 lines (2949 loc) · 102 KB
/
Copy pathRampsController.ts
File metadata and controls
3219 lines (2949 loc) · 102 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 type {
ControllerGetStateAction,
ControllerStateChangeEvent,
StateMetadata,
} from '@metamask/base-controller';
import { BaseController } from '@metamask/base-controller';
import { BrokenCircuitError } from '@metamask/controller-utils';
import type { Messenger } from '@metamask/messenger';
import type { Json } from '@metamask/utils';
import type { Draft } from 'immer';
import { getProvidersServingAsset } from './providerAvailability';
import { getSmartSelectedQuote } from './quoteSelection';
import type { RampsControllerMethodActions } from './RampsController-method-action-types';
import type { RampsErrorCode } from './rampsErrorCodes';
import { RAMPS_ERROR_CODES } from './rampsErrorCodes';
import type {
BuyWidget,
Country,
TokensResponse,
Provider,
State,
RampAction,
PaymentMethod,
PaymentMethodsResponse,
QuotesResponse,
Quote,
RampsToken,
RampsServiceActions,
RampsOrder,
} from './RampsService';
import { RampsOrderStatus } from './RampsService';
import type {
RampsServiceGetGeolocationAction,
RampsServiceGetCountriesAction,
RampsServiceGetTokensAction,
RampsServiceGetProvidersAction,
RampsServiceGetPaymentMethodsAction,
RampsServiceGetQuotesAction,
RampsServiceGetBuyWidgetUrlAction,
RampsServiceGetOrderAction,
RampsServiceGetOrderFromCallbackAction,
} from './RampsService-method-action-types';
import type {
RequestCache as RequestCacheType,
RequestState,
ExecuteRequestOptions,
PendingRequest,
ResourceType,
} from './RequestCache';
import {
DEFAULT_REQUEST_CACHE_TTL,
DEFAULT_REQUEST_CACHE_MAX_SIZE,
createCacheKey,
isCacheExpired,
createLoadingState,
createSuccessState,
createErrorState,
RequestStatus,
} from './RequestCache';
import type {
TransakAccessToken,
TransakUserDetails,
TransakBuyQuote,
TransakKycRequirement,
TransakAdditionalRequirementsResponse,
TransakDepositOrder,
TransakUserLimits,
TransakOttResponse,
TransakQuoteTranslation,
TransakTranslationRequest,
TransakIdProofStatus,
TransakOrderPaymentMethod,
PatchUserRequestBody,
TransakOrder,
} from './TransakService';
import type { TransakServiceActions } from './TransakService';
import type {
TransakServiceSetApiKeyAction,
TransakServiceSetAccessTokenAction,
TransakServiceClearAccessTokenAction,
TransakServiceSendUserOtpAction,
TransakServiceVerifyUserOtpAction,
TransakServiceLogoutAction,
TransakServiceGetUserDetailsAction,
TransakServiceGetBuyQuoteAction,
TransakServiceGetKycRequirementAction,
TransakServiceGetAdditionalRequirementsAction,
TransakServiceCreateOrderAction,
TransakServiceGetOrderAction,
TransakServiceGetUserLimitsAction,
TransakServiceRequestOttAction,
TransakServiceGeneratePaymentWidgetUrlAction,
TransakServiceSubmitPurposeOfUsageFormAction,
TransakServicePatchUserAction,
TransakServiceSubmitSsnDetailsAction,
TransakServiceConfirmPaymentAction,
TransakServiceGetTranslationAction,
TransakServiceGetIdProofStatusAction,
TransakServiceCancelOrderAction,
TransakServiceCancelAllActiveOrdersAction,
TransakServiceGetActiveOrdersAction,
} from './TransakService-method-action-types';
// === GENERAL ===
/**
* The name of the {@link RampsController}, used to namespace the
* controller's actions and events and to namespace the controller's state data
* when composed with other controllers.
*/
export const controllerName = 'RampsController';
/**
* RampsService action types that RampsController calls via the messenger.
* Any host (e.g. mobile) that creates a RampsController messenger must delegate
* these actions from the root messenger so the controller can function.
*/
export const RAMPS_CONTROLLER_REQUIRED_SERVICE_ACTIONS: readonly (
| RampsServiceActions['type']
| TransakServiceActions['type']
)[] = [
'RampsService:getGeolocation',
'RampsService:getCountries',
'RampsService:getTokens',
'RampsService:getProviders',
'RampsService:getPaymentMethods',
'RampsService:getQuotes',
'RampsService:getBuyWidgetUrl',
'RampsService:getOrder',
'RampsService:getOrderFromCallback',
'TransakService:setApiKey',
'TransakService:setAccessToken',
'TransakService:clearAccessToken',
'TransakService:sendUserOtp',
'TransakService:verifyUserOtp',
'TransakService:logout',
'TransakService:getUserDetails',
'TransakService:getBuyQuote',
'TransakService:getKycRequirement',
'TransakService:getAdditionalRequirements',
'TransakService:createOrder',
'TransakService:getOrder',
'TransakService:getUserLimits',
'TransakService:requestOtt',
'TransakService:generatePaymentWidgetUrl',
'TransakService:submitPurposeOfUsageForm',
'TransakService:patchUser',
'TransakService:submitSsnDetails',
'TransakService:confirmPayment',
'TransakService:getTranslation',
'TransakService:getIdProofStatus',
'TransakService:cancelOrder',
'TransakService:cancelAllActiveOrders',
'TransakService:getActiveOrders',
];
/**
* Default TTL for quotes requests (15 seconds).
* Quotes are time-sensitive and should have a shorter cache duration.
*/
const DEFAULT_QUOTES_TTL = 15000;
const CIRCUIT_BREAKER_OPEN_ERROR =
'Execution prevented because the circuit breaker is open';
type ErrorWithMessage = {
message: string;
};
type ErrorWithRampsErrorKey = Error & {
errorKey?: RampsErrorCode;
};
type ErrorWithHttpStatus = Error & {
httpStatus: number;
};
type RampsErrorInfo = {
errorKey: RampsErrorCode | null;
message: string;
};
type NormalizedRampsError = {
errorInfo: RampsErrorInfo;
normalizedError: unknown;
};
function hasStringMessage(error: unknown): error is ErrorWithMessage {
return (
typeof error === 'object' &&
error !== null &&
typeof (error as { message?: unknown }).message === 'string'
);
}
function hasHttpStatus(error: unknown): error is ErrorWithHttpStatus {
return (
error instanceof Error &&
typeof (error as { httpStatus?: unknown }).httpStatus === 'number'
);
}
function getRampsErrorInfo(error: unknown): RampsErrorInfo {
if (error instanceof BrokenCircuitError && hasStringMessage(error)) {
return {
errorKey: RAMPS_ERROR_CODES.CIRCUIT_BREAKER_OPEN,
message: error.message,
};
}
let rawMessage: string | undefined;
if (hasStringMessage(error)) {
rawMessage = error.message;
} else if (typeof error === 'string') {
rawMessage = error;
}
if (rawMessage?.includes(CIRCUIT_BREAKER_OPEN_ERROR)) {
return {
errorKey: RAMPS_ERROR_CODES.CIRCUIT_BREAKER_OPEN,
message: rawMessage,
};
}
return {
errorKey: null,
message: rawMessage ?? 'Unknown error',
};
}
function getNormalizedRampsError(error: unknown): NormalizedRampsError {
const errorInfo = getRampsErrorInfo(error);
return {
errorInfo,
normalizedError: normalizeRampsErrorForRethrow(error, errorInfo),
};
}
function normalizeRampsErrorForRethrow(
error: unknown,
errorInfo: RampsErrorInfo,
): unknown {
if (!errorInfo.errorKey) {
return error;
}
if (error instanceof Error) {
(error as ErrorWithRampsErrorKey).errorKey = errorInfo.errorKey;
return error;
}
return Object.assign(new Error(errorInfo.message), {
errorKey: errorInfo.errorKey,
});
}
// === STATE ===
/**
* Represents the user's selected region with full country and state objects.
*/
export type UserRegion = {
/**
* The country object for the selected region.
*/
country: Country;
/**
* The state object if a state was selected, null if only country was selected.
*/
state: State | null;
/**
* The region code string (e.g., "us-ut" or "fr") used for API calls.
*/
regionCode: string;
};
/**
* Generic type for resource state that bundles data with loading/error states.
*
* @template TData - The type of the resource data
* @template TSelected - The type of the selected item (defaults to null for resources without selection)
*/
export type ResourceState<TData, TSelected = null> = {
/**
* The resource data.
*/
data: TData;
/**
* The currently selected item, or null if none selected.
*/
selected: TSelected;
/**
* Whether the resource is currently being fetched.
*/
isLoading: boolean;
/**
* Error message if the fetch failed, or null.
*/
error: string | null;
/**
* Stable error key for client-side localization, if available.
*/
errorKey?: RampsErrorCode | null;
};
/**
* Describes the transak-specific state managed by the RampsController.
* This state is used by the unified V2 native flow.
*/
export type TransakState = {
isAuthenticated: boolean;
userDetails: ResourceState<TransakUserDetails | null>;
buyQuote: ResourceState<TransakBuyQuote | null>;
kycRequirement: ResourceState<TransakKycRequirement | null>;
};
/**
* Describes the state for all native providers managed by the RampsController.
* Each native provider has its own nested state object.
*/
export type NativeProvidersState = {
transak: TransakState;
};
/**
* Describes the shape of the state object for {@link RampsController}.
*/
export type RampsControllerState = {
/**
* The user's region (full country and state objects).
* Initially set via geolocation fetch, but can be manually changed by the user.
*/
userRegion: UserRegion | null;
/**
* Countries resource state with data, loading, and error.
* Data contains the list of countries available for ramp actions.
*/
countries: ResourceState<Country[]>;
/**
* Providers resource state with data, selected, loading, and error.
* Data contains the list of providers available for the current region.
*/
providers: ResourceState<Provider[], Provider | null>;
/**
* Tokens resource state with data, selected, loading, and error.
* Data contains topTokens and allTokens arrays.
*/
tokens: ResourceState<TokensResponse | null, RampsToken | null>;
/**
* Payment methods resource state with data, selected, loading, and error.
* Data contains payment methods filtered by region, fiat, asset, and provider.
*/
paymentMethods: ResourceState<PaymentMethod[], PaymentMethod | null>;
/**
* Cache of request states, keyed by cache key.
* This stores loading, success, and error states for API requests.
*/
requests: RequestCacheType;
/**
* State for native providers in the unified V2 flow.
* Each provider has its own nested state containing authentication,
* user details, quote, and KYC data.
*/
nativeProviders: NativeProvidersState;
/**
* The controller is the authority for V2 orders — it polls, updates,
* and persists them.
*/
orders: RampsOrder[];
/**
* Whether the currently selected provider was auto-selected by the system
* (no order history, no Transak) rather than chosen by the user or derived
* from order history. When true, the UI should silently switch providers on
* token conflict instead of showing the "Token Not Available" modal.
*/
providerAutoSelected: boolean;
};
/**
* The metadata for each property in {@link RampsControllerState}.
*/
const rampsControllerMetadata = {
userRegion: {
persist: true,
includeInDebugSnapshot: true,
includeInStateLogs: true,
usedInUi: true,
},
countries: {
persist: false,
includeInDebugSnapshot: true,
includeInStateLogs: true,
usedInUi: true,
},
providers: {
persist: false,
includeInDebugSnapshot: true,
includeInStateLogs: true,
usedInUi: true,
},
tokens: {
persist: false,
includeInDebugSnapshot: true,
includeInStateLogs: true,
usedInUi: true,
},
paymentMethods: {
persist: false,
includeInDebugSnapshot: true,
includeInStateLogs: true,
usedInUi: true,
},
requests: {
persist: false,
includeInDebugSnapshot: true,
includeInStateLogs: false,
usedInUi: true,
},
nativeProviders: {
persist: false,
includeInDebugSnapshot: true,
includeInStateLogs: false,
usedInUi: true,
},
orders: {
persist: true,
includeInDebugSnapshot: true,
includeInStateLogs: true,
usedInUi: true,
},
providerAutoSelected: {
persist: true,
includeInDebugSnapshot: true,
includeInStateLogs: true,
usedInUi: true,
},
} satisfies StateMetadata<RampsControllerState>;
/**
* Creates a default resource state object.
*
* @template TData - The type of the resource data.
* @template TSelected - The type of the selected item.
* @param data - The initial data value.
* @param selected - The initial selected value.
* @returns A ResourceState object with default loading and error values.
*/
function createDefaultResourceState<TData, TSelected = null>(
data: TData,
selected: TSelected = null as TSelected,
): ResourceState<TData, TSelected> {
return {
data,
selected,
isLoading: false,
error: null,
};
}
/**
* Constructs the default {@link RampsController} state. This allows
* consumers to provide a partial state object when initializing the controller
* and also helps in constructing complete state objects for this controller in
* tests.
*
* @returns The default {@link RampsController} state.
*/
export function getDefaultRampsControllerState(): RampsControllerState {
return {
userRegion: null,
countries: createDefaultResourceState<Country[]>([]),
providers: createDefaultResourceState<Provider[], Provider | null>(
[],
null,
),
tokens: createDefaultResourceState<
TokensResponse | null,
RampsToken | null
>(null, null),
paymentMethods: createDefaultResourceState<
PaymentMethod[],
PaymentMethod | null
>([], null),
requests: {},
nativeProviders: {
transak: {
isAuthenticated: false,
userDetails: createDefaultResourceState<TransakUserDetails | null>(
null,
),
buyQuote: createDefaultResourceState<TransakBuyQuote | null>(null),
kycRequirement:
createDefaultResourceState<TransakKycRequirement | null>(null),
},
},
orders: [],
providerAutoSelected: false,
};
}
const DEPENDENT_RESOURCE_KEYS = [
'providers',
'tokens',
'paymentMethods',
] as const;
type DependentResourceKey = (typeof DEPENDENT_RESOURCE_KEYS)[number];
const DEPENDENT_RESOURCE_KEYS_SET = new Set<string>(DEPENDENT_RESOURCE_KEYS);
function getResourceState<TResourceType extends ResourceType>(
state: Draft<RampsControllerState>,
resourceType: TResourceType,
): Draft<RampsControllerState[TResourceType]> {
switch (resourceType) {
case 'countries':
return state.countries as Draft<RampsControllerState[TResourceType]>;
case 'providers':
return state.providers as Draft<RampsControllerState[TResourceType]>;
case 'tokens':
return state.tokens as Draft<RampsControllerState[TResourceType]>;
case 'paymentMethods':
return state.paymentMethods as Draft<RampsControllerState[TResourceType]>;
/* istanbul ignore next -- ResourceType is a closed internal union. */
default:
throw new Error(`Unsupported resource type: ${resourceType as string}`);
}
}
function resetResource(
state: Draft<RampsControllerState>,
resourceType: DependentResourceKey,
defaultResource: RampsControllerState[DependentResourceKey],
): void {
const resource = getResourceState(state, resourceType);
resource.data = defaultResource.data;
resource.selected = defaultResource.selected;
resource.isLoading = defaultResource.isLoading;
resource.error = defaultResource.error;
resource.errorKey = defaultResource.errorKey ?? null;
}
/**
* Resets region-dependent resources (userRegion, providers, tokens, paymentMethods).
* Mutates state in place; use from within controller update() for atomic updates.
*
* @param state - The state object to mutate.
* @param options - Options for the reset.
* @param options.clearUserRegionData - When true, sets userRegion to null (e.g. for full cleanup).
*/
function resetDependentResources(
state: Draft<RampsControllerState>,
options?: { clearUserRegionData?: boolean },
): void {
if (options?.clearUserRegionData) {
state.userRegion = null;
}
const defaultState = getDefaultRampsControllerState();
for (const key of DEPENDENT_RESOURCE_KEYS) {
resetResource(state, key, defaultState[key]);
}
state.providerAutoSelected = false;
}
// === MESSENGER ===
/**
* Retrieves the state of the {@link RampsController}.
*/
export type RampsControllerGetStateAction = ControllerGetStateAction<
typeof controllerName,
RampsControllerState
>;
/**
* Actions that {@link RampsControllerMessenger} exposes to other consumers.
*/
export type RampsControllerActions =
| RampsControllerGetStateAction
| RampsControllerMethodActions;
/**
* Actions from other messengers that {@link RampsController} calls.
*/
type AllowedActions =
| RampsServiceGetGeolocationAction
| RampsServiceGetCountriesAction
| RampsServiceGetTokensAction
| RampsServiceGetProvidersAction
| RampsServiceGetPaymentMethodsAction
| RampsServiceGetQuotesAction
| RampsServiceGetBuyWidgetUrlAction
| RampsServiceGetOrderAction
| RampsServiceGetOrderFromCallbackAction
| TransakServiceSetApiKeyAction
| TransakServiceSetAccessTokenAction
| TransakServiceClearAccessTokenAction
| TransakServiceSendUserOtpAction
| TransakServiceVerifyUserOtpAction
| TransakServiceLogoutAction
| TransakServiceGetUserDetailsAction
| TransakServiceGetBuyQuoteAction
| TransakServiceGetKycRequirementAction
| TransakServiceGetAdditionalRequirementsAction
| TransakServiceCreateOrderAction
| TransakServiceGetOrderAction
| TransakServiceGetUserLimitsAction
| TransakServiceRequestOttAction
| TransakServiceGeneratePaymentWidgetUrlAction
| TransakServiceSubmitPurposeOfUsageFormAction
| TransakServicePatchUserAction
| TransakServiceSubmitSsnDetailsAction
| TransakServiceConfirmPaymentAction
| TransakServiceGetTranslationAction
| TransakServiceGetIdProofStatusAction
| TransakServiceCancelOrderAction
| TransakServiceCancelAllActiveOrdersAction
| TransakServiceGetActiveOrdersAction;
/**
* Published when the state of {@link RampsController} changes.
*/
export type RampsControllerStateChangeEvent = ControllerStateChangeEvent<
typeof controllerName,
RampsControllerState
>;
/**
* Published when a V2 order's status transitions.
* Consumed by mobile's init layer for notifications and analytics.
*/
export type RampsControllerOrderStatusChangedEvent = {
type: `${typeof controllerName}:orderStatusChanged`;
payload: [{ order: RampsOrder; previousStatus: RampsOrderStatus }];
};
/**
* Events that {@link RampsControllerMessenger} exposes to other consumers.
*/
export type RampsControllerEvents =
| RampsControllerStateChangeEvent
| RampsControllerOrderStatusChangedEvent;
/**
* Events from other messengers that {@link RampsController} subscribes to.
*/
type AllowedEvents = never;
/**
* The messenger restricted to actions and events accessed by
* {@link RampsController}.
*/
export type RampsControllerMessenger = Messenger<
typeof controllerName,
RampsControllerActions | AllowedActions,
RampsControllerEvents | AllowedEvents
>;
/**
* Configuration options for the RampsController.
*/
/**
* Provider-class scope for fiat quote widening, resolved per `getQuotes` call.
*
* - `off`: native-only auto-selection (default; preserves prior behaviour).
* - `in-app`: also quote in-app WebView aggregator providers and select the
* best in-app quote.
* - `all`: additionally allow external-browser / custom-action providers
* (Phase 2).
*/
export type ProviderScope = 'off' | 'in-app' | 'all';
export type RampsControllerOptions = {
/** The messenger suited for this controller. */
messenger: RampsControllerMessenger;
/** The desired state with which to initialize this controller. */
state?: Partial<RampsControllerState>;
/** Time to live for cached requests in milliseconds. Defaults to 15 minutes. */
requestCacheTTL?: number;
/** Maximum number of entries in the request cache. Defaults to 250. */
requestCacheMaxSize?: number;
/**
* Optional callback returning the current provider-class scope for fiat quote
* widening. Read per `getQuotes` call so a host-side toggle takes effect at
* runtime without reconstructing the controller. Defaults to `off`
* (native-only) when omitted.
*/
getProviderScope?: () => ProviderScope;
/**
* Optional callback returning the default redirect URL to use for the widened
* in-app quote fetch when the caller omits `redirectUrl`. The quotes API only
* embeds a `buyURL`/`buyWidget` (the WebView page a non-native provider needs)
* when a `redirectUrl` is present, so supplying this default lets widened
* in-app aggregator quotes carry a usable widget URL. Only applied on the
* widened path; an explicit caller `redirectUrl` always wins and scope `off`
* never injects. Defaults to a callback returning `undefined` when omitted.
*/
getDefaultRedirectUrl?: () => string | undefined;
};
// === HELPER FUNCTIONS ===
/**
* Finds a country and state from a region code string.
*
* @param regionCode - The region code (e.g., "us-ca" or "us").
* @param countries - Array of countries to search.
* @returns UserRegion object with country and state, or null if not found.
*/
function findRegionFromCode(
regionCode: string,
countries: Country[],
): UserRegion | null {
const normalizedCode = regionCode.toLowerCase().trim();
const parts = normalizedCode.split('-');
const countryCode = parts[0];
const stateCode = parts[1];
const country = countries.find((countryItem) => {
if (countryItem.isoCode?.toLowerCase() === countryCode) {
return true;
}
if (countryItem.id) {
const id = countryItem.id.toLowerCase();
if (id.startsWith('/regions/')) {
const extractedCode = id.replace('/regions/', '').split('/')[0];
return extractedCode === countryCode;
}
return id === countryCode || id.endsWith(`/${countryCode}`);
}
return false;
});
if (!country) {
return null;
}
let state: State | null = null;
if (stateCode && country.states) {
state =
country.states.find((stateItem) => {
if (stateItem.stateId?.toLowerCase() === stateCode) {
return true;
}
if (stateItem.id) {
const stateId = stateItem.id.toLowerCase();
if (
stateId.includes(`-${stateCode}`) ||
stateId.endsWith(`/${stateCode}`)
) {
return true;
}
}
return false;
}) ?? null;
}
return {
country,
state,
regionCode: normalizedCode,
};
}
export function normalizeProviderCode(providerCode: string): string {
return providerCode.replace(/^\/providers\//u, '');
}
/**
* Returns the internal MetaMask order code used for state lookups and polling.
* Prefers the code embedded in the canonical order `id` path over `providerOrderId`,
* which may contain the provider's native order identifier.
*
* @param orderOrId - Order fields or a full order id / order code string.
* @returns The internal order code.
*/
export function getInternalOrderCode(
orderOrId: Pick<RampsOrder, 'id' | 'providerOrderId'> | string,
): string {
if (typeof orderOrId === 'string') {
return orderOrId.includes('/orders/')
? orderOrId.split('/orders/')[1]
: orderOrId;
}
const { id, providerOrderId } = orderOrId;
if (id?.includes('/orders/')) {
return id.split('/orders/')[1];
}
return providerOrderId;
}
// === ORDER POLLING CONSTANTS ===
const TERMINAL_ORDER_STATUSES = new Set<RampsOrderStatus>([
RampsOrderStatus.Completed,
RampsOrderStatus.Failed,
RampsOrderStatus.Cancelled,
RampsOrderStatus.IdExpired,
]);
const PENDING_ORDER_STATUSES = new Set<RampsOrderStatus>([
RampsOrderStatus.Pending,
RampsOrderStatus.Created,
RampsOrderStatus.Unknown,
RampsOrderStatus.Precreated,
]);
const DEFAULT_POLLING_INTERVAL_MS = 30_000;
const MAX_ERROR_COUNT = 5;
type OrderPollingMetadata = {
lastTimeFetched: number;
errorCount: number;
};
// === CONTROLLER DEFINITION ===
const MESSENGER_EXPOSED_METHODS = [
'executeRequest',
'abortRequest',
'getRequestState',
'setUserRegion',
'setSelectedProvider',
'init',
'getCountries',
'getTokens',
'setSelectedToken',
'getProviders',
'getPaymentMethods',
'setSelectedPaymentMethod',
'getQuotes',
'addOrder',
'removeOrder',
'startOrderPolling',
'stopOrderPolling',
'getBuyWidgetData',
'addPrecreatedOrder',
'getOrder',
'getOrderFromCallback',
'transakSetApiKey',
'transakSetAccessToken',
'transakClearAccessToken',
'transakSetAuthenticated',
'transakResetState',
'transakSendUserOtp',
'transakVerifyUserOtp',
'transakLogout',
'transakGetUserDetails',
'transakGetBuyQuote',
'transakGetKycRequirement',
'transakGetAdditionalRequirements',
'transakCreateOrder',
'transakGetOrder',
'transakGetUserLimits',
'transakRequestOtt',
'transakGeneratePaymentWidgetUrl',
'transakSubmitPurposeOfUsageForm',
'transakPatchUser',
'transakSubmitSsnDetails',
'transakConfirmPayment',
'transakGetTranslation',
'transakGetIdProofStatus',
'transakCancelOrder',
'transakCancelAllActiveOrders',
'transakGetActiveOrders',
] as const;
/**
* Manages cryptocurrency on/off ramps functionality.
*/
export class RampsController extends BaseController<
typeof controllerName,
RampsControllerState,
RampsControllerMessenger
> {
/**
* Default TTL for cached requests.
*/
readonly #requestCacheTTL: number;
/**
* Maximum number of entries in the request cache.
*/
readonly #requestCacheMaxSize: number;
/**
* Resolves the current provider-class scope for fiat quote widening. Defaults
* to `() => 'off'` (native-only) when no callback is injected.
*/
readonly #getProviderScope: () => ProviderScope;
/**
* Resolves the default redirect URL for the widened in-app quote fetch when
* the caller omits `redirectUrl`. Defaults to `() => undefined` when no
* callback is injected.
*/
readonly #getDefaultRedirectUrl: () => string | undefined;
/**
* Map of pending requests for deduplication.
* Key is the cache key, value is the pending request with abort controller.
*/
readonly #pendingRequests: Map<string, PendingRequest> = new Map();
/**
* Count of in-flight requests per resource type.
* Used so isLoading is only cleared when the last request for that resource finishes.
*/
readonly #pendingResourceCount: Map<ResourceType, number> = new Map();
/**
* Monotonic generation per resource type used to invalidate stale in-flight
* requests after region/token/provider dependent-resource resets.
*/
readonly #pendingResourceGeneration: Map<ResourceType, number> = new Map();
readonly #orderPollingMeta: Map<string, OrderPollingMetadata> = new Map();
#orderPollingTimer: ReturnType<typeof setInterval> | null = null;
#isPolling = false;
#initPromise: Promise<void> | null = null;
/**
* Clears the pending resource count map. Used only in tests to exercise the
* defensive path when get() returns undefined in the finally block.
*
* @internal
*/
clearPendingResourceCountForTest(): void {
this.#pendingResourceCount.clear();
}
#clearPendingResourceCountForDependentResources(): void {
for (const resourceType of DEPENDENT_RESOURCE_KEYS) {
this.#pendingResourceCount.delete(resourceType);
const generation = this.#pendingResourceGeneration.get(resourceType) ?? 0;
this.#pendingResourceGeneration.set(resourceType, generation + 1);
}
}
#abortDependentRequests(): void {
for (const [cacheKey, pending] of this.#pendingRequests.entries()) {
if (
pending.resourceType &&
DEPENDENT_RESOURCE_KEYS_SET.has(pending.resourceType)
) {
pending.abortController.abort();
this.#pendingRequests.delete(cacheKey);
this.#removeRequestState(cacheKey);
}
}
}
/**
* Constructs a new {@link RampsController}.
*
* @param args - The constructor arguments.
* @param args.messenger - The messenger suited for this controller.
* @param args.state - The desired state with which to initialize this
* controller. Missing properties will be filled in with defaults.
* @param args.requestCacheTTL - Time to live for cached requests in milliseconds.
* @param args.requestCacheMaxSize - Maximum number of entries in the request cache.
* @param args.getProviderScope - Optional callback returning the current
* provider-class scope for fiat quote widening. Defaults to `off`.
* @param args.getDefaultRedirectUrl - Optional callback returning the default
* redirect URL used for the widened in-app quote fetch when the caller omits
* `redirectUrl`. Defaults to a callback returning `undefined`.
*/
constructor({
messenger,
state = {},
requestCacheTTL = DEFAULT_REQUEST_CACHE_TTL,
requestCacheMaxSize = DEFAULT_REQUEST_CACHE_MAX_SIZE,
getProviderScope,
getDefaultRedirectUrl,
}: RampsControllerOptions) {
super({
messenger,
metadata: rampsControllerMetadata,
name: controllerName,
state: {
...getDefaultRampsControllerState(),
...state,
// Always reset requests cache on initialization (non-persisted)
requests: {},
},
});
this.#requestCacheTTL = requestCacheTTL;
this.#requestCacheMaxSize = requestCacheMaxSize;
this.#getProviderScope = getProviderScope ?? ((): ProviderScope => 'off');
this.#getDefaultRedirectUrl =
getDefaultRedirectUrl ?? ((): string | undefined => undefined);