@metamask/ramps-controller 20.0.0 → 20.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/dist/RampsController-method-action-types.cjs.map +1 -1
  3. package/dist/RampsController-method-action-types.d.cts +44 -1
  4. package/dist/RampsController-method-action-types.d.cts.map +1 -1
  5. package/dist/RampsController-method-action-types.d.mts +44 -1
  6. package/dist/RampsController-method-action-types.d.mts.map +1 -1
  7. package/dist/RampsController-method-action-types.mjs.map +1 -1
  8. package/dist/RampsController.cjs +225 -18
  9. package/dist/RampsController.cjs.map +1 -1
  10. package/dist/RampsController.d.cts +76 -7
  11. package/dist/RampsController.d.cts.map +1 -1
  12. package/dist/RampsController.d.mts +76 -7
  13. package/dist/RampsController.d.mts.map +1 -1
  14. package/dist/RampsController.mjs +224 -17
  15. package/dist/RampsController.mjs.map +1 -1
  16. package/dist/RampsService.cjs +18 -4
  17. package/dist/RampsService.cjs.map +1 -1
  18. package/dist/RampsService.d.cts +20 -4
  19. package/dist/RampsService.d.cts.map +1 -1
  20. package/dist/RampsService.d.mts +20 -4
  21. package/dist/RampsService.d.mts.map +1 -1
  22. package/dist/RampsService.mjs +18 -4
  23. package/dist/RampsService.mjs.map +1 -1
  24. package/dist/TransakService.cjs +15 -3
  25. package/dist/TransakService.cjs.map +1 -1
  26. package/dist/TransakService.d.cts +3 -1
  27. package/dist/TransakService.d.cts.map +1 -1
  28. package/dist/TransakService.d.mts +3 -1
  29. package/dist/TransakService.d.mts.map +1 -1
  30. package/dist/TransakService.mjs +15 -3
  31. package/dist/TransakService.mjs.map +1 -1
  32. package/dist/client-identity.cjs +28 -0
  33. package/dist/client-identity.cjs.map +1 -0
  34. package/dist/client-identity.d.cts +24 -0
  35. package/dist/client-identity.d.cts.map +1 -0
  36. package/dist/client-identity.d.mts +24 -0
  37. package/dist/client-identity.d.mts.map +1 -0
  38. package/dist/client-identity.mjs +24 -0
  39. package/dist/client-identity.mjs.map +1 -0
  40. package/dist/index.cjs +9 -1
  41. package/dist/index.cjs.map +1 -1
  42. package/dist/index.d.cts +7 -4
  43. package/dist/index.d.cts.map +1 -1
  44. package/dist/index.d.mts +7 -4
  45. package/dist/index.d.mts.map +1 -1
  46. package/dist/index.mjs +3 -1
  47. package/dist/index.mjs.map +1 -1
  48. package/dist/orderStatus.cjs +34 -0
  49. package/dist/orderStatus.cjs.map +1 -0
  50. package/dist/orderStatus.d.cts +18 -0
  51. package/dist/orderStatus.d.cts.map +1 -0
  52. package/dist/orderStatus.d.mts +18 -0
  53. package/dist/orderStatus.d.mts.map +1 -0
  54. package/dist/orderStatus.mjs +30 -0
  55. package/dist/orderStatus.mjs.map +1 -0
  56. package/dist/paymentMethodMerge.cjs +51 -0
  57. package/dist/paymentMethodMerge.cjs.map +1 -0
  58. package/dist/paymentMethodMerge.d.cts +26 -0
  59. package/dist/paymentMethodMerge.d.cts.map +1 -0
  60. package/dist/paymentMethodMerge.d.mts +26 -0
  61. package/dist/paymentMethodMerge.d.mts.map +1 -0
  62. package/dist/paymentMethodMerge.mjs +46 -0
  63. package/dist/paymentMethodMerge.mjs.map +1 -0
  64. package/dist/providerAvailability.cjs +39 -8
  65. package/dist/providerAvailability.cjs.map +1 -1
  66. package/dist/providerAvailability.d.cts +30 -5
  67. package/dist/providerAvailability.d.cts.map +1 -1
  68. package/dist/providerAvailability.d.mts +30 -5
  69. package/dist/providerAvailability.d.mts.map +1 -1
  70. package/dist/providerAvailability.mjs +37 -7
  71. package/dist/providerAvailability.mjs.map +1 -1
  72. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"RampsController.mjs","sourceRoot":"","sources":["../src/RampsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,mCAAmC;AAMhE,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,E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K,CAAC,CAAC;IACtC,CAAC;IAED,OAAO,uBAAuB,CAAC,KAAK,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { BrokenCircuitError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { Json } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport {\n getHeadlessProviderAllowlist,\n isHeadlessAllProvidersEnabled,\n normalizeHeadlessProviderId,\n} from './featureFlags.js';\nimport {\n getProvidersServingAsset,\n providerServesAsset,\n} from './providerAvailability.js';\nimport type { RampsControllerMethodActions } from './RampsController-method-action-types.js';\nimport type { RampsErrorCode } from './rampsErrorCodes.js';\nimport { RAMPS_ERROR_CODES } from './rampsErrorCodes.js';\nimport type {\n RampsServiceGetDefaultRedirectCallbackUrlAction,\n RampsServiceGetGeolocationAction,\n RampsServiceGetCountriesAction,\n RampsServiceGetTokensAction,\n RampsServiceGetProvidersAction,\n RampsServiceGetPaymentMethodsAction,\n RampsServiceGetQuotesAction,\n RampsServiceGetBuyWidgetUrlAction,\n RampsServiceGetOrderAction,\n RampsServiceGetOrderFromCallbackAction,\n} from './RampsService-method-action-types.js';\nimport type {\n BuyWidget,\n Country,\n TokensResponse,\n Provider,\n State,\n RampAction,\n PaymentMethod,\n PaymentMethodsResponse,\n QuotesResponse,\n Quote,\n QuoteSortBy,\n RampsToken,\n RampsServiceActions,\n RampsOrder,\n} from './RampsService.js';\nimport { RampsOrderStatus } from './RampsService.js';\nimport type {\n RequestCache as RequestCacheType,\n RequestState,\n ExecuteRequestOptions,\n PendingRequest,\n ResourceType,\n} from './RequestCache.js';\nimport {\n DEFAULT_REQUEST_CACHE_TTL,\n DEFAULT_REQUEST_CACHE_MAX_SIZE,\n createCacheKey,\n isCacheExpired,\n createLoadingState,\n createSuccessState,\n createErrorState,\n RequestStatus,\n} from './RequestCache.js';\nimport type {\n TransakServiceSetApiKeyAction,\n TransakServiceSetAccessTokenAction,\n TransakServiceClearAccessTokenAction,\n TransakServiceSendUserOtpAction,\n TransakServiceVerifyUserOtpAction,\n TransakServiceLogoutAction,\n TransakServiceGetUserDetailsAction,\n TransakServiceGetBuyQuoteAction,\n TransakServiceGetKycRequirementAction,\n TransakServiceGetAdditionalRequirementsAction,\n TransakServiceCreateOrderAction,\n TransakServiceGetOrderAction,\n TransakServiceGetUserLimitsAction,\n TransakServiceRequestOttAction,\n TransakServiceGeneratePaymentWidgetUrlAction,\n TransakServiceCreateWidgetUrlAction,\n TransakServiceSubmitPurposeOfUsageFormAction,\n TransakServicePatchUserAction,\n TransakServiceSubmitSsnDetailsAction,\n TransakServiceConfirmPaymentAction,\n TransakServiceGetTranslationAction,\n TransakServiceGetIdProofStatusAction,\n TransakServiceCancelOrderAction,\n TransakServiceCancelAllActiveOrdersAction,\n TransakServiceGetActiveOrdersAction,\n} from './TransakService-method-action-types.js';\nimport type {\n TransakAccessToken,\n TransakUserDetails,\n TransakBuyQuote,\n TransakKycRequirement,\n TransakAdditionalRequirementsResponse,\n TransakDepositOrder,\n TransakUserLimits,\n TransakOttResponse,\n TransakQuoteTranslation,\n TransakTranslationRequest,\n TransakIdProofStatus,\n TransakOrderPaymentMethod,\n PatchUserRequestBody,\n TransakOrder,\n} from './TransakService.js';\nimport type { TransakServiceActions } from './TransakService.js';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link RampsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'RampsController';\n\n/**\n * RampsService action types that RampsController calls via the messenger.\n * Any host (e.g. mobile) that creates a RampsController messenger must delegate\n * these actions from the root messenger so the controller can function.\n */\nexport const RAMPS_CONTROLLER_REQUIRED_SERVICE_ACTIONS: readonly (\n | RampsServiceActions['type']\n | TransakServiceActions['type']\n)[] = [\n 'RampsService:getDefaultRedirectCallbackUrl',\n 'RampsService:getGeolocation',\n 'RampsService:getCountries',\n 'RampsService:getTokens',\n 'RampsService:getProviders',\n 'RampsService:getPaymentMethods',\n 'RampsService:getQuotes',\n 'RampsService:getBuyWidgetUrl',\n 'RampsService:getOrder',\n 'RampsService:getOrderFromCallback',\n 'TransakService:setApiKey',\n 'TransakService:setAccessToken',\n 'TransakService:clearAccessToken',\n 'TransakService:sendUserOtp',\n 'TransakService:verifyUserOtp',\n 'TransakService:logout',\n 'TransakService:getUserDetails',\n 'TransakService:getBuyQuote',\n 'TransakService:getKycRequirement',\n 'TransakService:getAdditionalRequirements',\n 'TransakService:createOrder',\n 'TransakService:getOrder',\n 'TransakService:getUserLimits',\n 'TransakService:requestOtt',\n 'TransakService:generatePaymentWidgetUrl',\n 'TransakService:createWidgetUrl',\n 'TransakService:submitPurposeOfUsageForm',\n 'TransakService:patchUser',\n 'TransakService:submitSsnDetails',\n 'TransakService:confirmPayment',\n 'TransakService:getTranslation',\n 'TransakService:getIdProofStatus',\n 'TransakService:cancelOrder',\n 'TransakService:cancelAllActiveOrders',\n 'TransakService:getActiveOrders',\n];\n\n/**\n * Default TTL for quotes requests (15 seconds).\n * Quotes are time-sensitive and should have a shorter cache duration.\n */\nconst DEFAULT_QUOTES_TTL = 15000;\n\nconst CIRCUIT_BREAKER_OPEN_ERROR =\n 'Execution prevented because the circuit breaker is open';\n\ntype ErrorWithMessage = {\n message: string;\n};\n\ntype ErrorWithRampsErrorKey = Error & {\n errorKey?: RampsErrorCode;\n};\n\ntype ErrorWithHttpStatus = Error & {\n httpStatus: number;\n};\n\ntype RampsErrorInfo = {\n errorKey: RampsErrorCode | null;\n message: string;\n};\n\ntype NormalizedRampsError = {\n errorInfo: RampsErrorInfo;\n normalizedError: unknown;\n};\n\nfunction hasStringMessage(error: unknown): error is ErrorWithMessage {\n return (\n typeof error === 'object' &&\n error !== null &&\n typeof (error as { message?: unknown }).message === 'string'\n );\n}\n\nfunction hasHttpStatus(error: unknown): error is ErrorWithHttpStatus {\n return (\n error instanceof Error &&\n typeof (error as { httpStatus?: unknown }).httpStatus === 'number'\n );\n}\n\nfunction getRampsErrorInfo(error: unknown): RampsErrorInfo {\n if (error instanceof BrokenCircuitError && hasStringMessage(error)) {\n return {\n errorKey: RAMPS_ERROR_CODES.CIRCUIT_BREAKER_OPEN,\n message: error.message,\n };\n }\n\n let rawMessage: string | undefined;\n\n if (hasStringMessage(error)) {\n rawMessage = error.message;\n } else if (typeof error === 'string') {\n rawMessage = error;\n }\n\n if (rawMessage?.includes(CIRCUIT_BREAKER_OPEN_ERROR)) {\n return {\n errorKey: RAMPS_ERROR_CODES.CIRCUIT_BREAKER_OPEN,\n message: rawMessage,\n };\n }\n\n return {\n errorKey: null,\n message: rawMessage ?? 'Unknown error',\n };\n}\n\nfunction getNormalizedRampsError(error: unknown): NormalizedRampsError {\n const errorInfo = getRampsErrorInfo(error);\n\n return {\n errorInfo,\n normalizedError: normalizeRampsErrorForRethrow(error, errorInfo),\n };\n}\n\nfunction normalizeRampsErrorForRethrow(\n error: unknown,\n errorInfo: RampsErrorInfo,\n): unknown {\n if (!errorInfo.errorKey) {\n return error;\n }\n\n if (error instanceof Error) {\n (error as ErrorWithRampsErrorKey).errorKey = errorInfo.errorKey;\n return error;\n }\n\n return Object.assign(new Error(errorInfo.message), {\n errorKey: errorInfo.errorKey,\n });\n}\n\n// === STATE ===\n\n/**\n * Represents the user's selected region with full country and state objects.\n */\nexport type UserRegion = {\n /**\n * The country object for the selected region.\n */\n country: Country;\n /**\n * The state object if a state was selected, null if only country was selected.\n */\n state: State | null;\n /**\n * The region code string (e.g., \"us-ut\" or \"fr\") used for API calls.\n */\n regionCode: string;\n};\n\n/**\n * Generic type for resource state that bundles data with loading/error states.\n *\n * @template TData - The type of the resource data\n * @template TSelected - The type of the selected item (defaults to null for resources without selection)\n */\nexport type ResourceState<TData, TSelected = null> = {\n /**\n * The resource data.\n */\n data: TData;\n /**\n * The currently selected item, or null if none selected.\n */\n selected: TSelected;\n /**\n * Whether the resource is currently being fetched.\n */\n isLoading: boolean;\n /**\n * Error message if the fetch failed, or null.\n */\n error: string | null;\n /**\n * Stable error key for client-side localization, if available.\n */\n errorKey?: RampsErrorCode | null;\n};\n\n/**\n * Describes the transak-specific state managed by the RampsController.\n * This state is used by the unified V2 native flow.\n */\nexport type TransakState = {\n isAuthenticated: boolean;\n userDetails: ResourceState<TransakUserDetails | null>;\n buyQuote: ResourceState<TransakBuyQuote | null>;\n kycRequirement: ResourceState<TransakKycRequirement | null>;\n};\n\n/**\n * Describes the state for all native providers managed by the RampsController.\n * Each native provider has its own nested state object.\n */\nexport type NativeProvidersState = {\n transak: TransakState;\n};\n\n/**\n * Describes the shape of the state object for {@link RampsController}.\n */\nexport type RampsControllerState = {\n /**\n * The user's region (full country and state objects).\n * Initially set via geolocation fetch, but can be manually changed by the user.\n */\n userRegion: UserRegion | null;\n /**\n * Countries resource state with data, loading, and error.\n * Data contains the list of countries available for ramp actions.\n */\n countries: ResourceState<Country[]>;\n /**\n * Providers resource state with data, selected, loading, and error.\n * Data contains the list of providers available for the current region.\n */\n providers: ResourceState<Provider[], Provider | null>;\n /**\n * Tokens resource state with data, selected, loading, and error.\n * Data contains topTokens and allTokens arrays.\n */\n tokens: ResourceState<TokensResponse | null, RampsToken | null>;\n /**\n * Payment methods resource state with data, selected, loading, and error.\n * Data contains payment methods filtered by region, fiat, asset, and provider.\n */\n paymentMethods: ResourceState<PaymentMethod[], PaymentMethod | null>;\n /**\n * Cache of request states, keyed by cache key.\n * This stores loading, success, and error states for API requests.\n */\n requests: RequestCacheType;\n /**\n * State for native providers in the unified V2 flow.\n * Each provider has its own nested state containing authentication,\n * user details, quote, and KYC data.\n */\n nativeProviders: NativeProvidersState;\n /**\n * The controller is the authority for V2 orders — it polls, updates,\n * and persists them.\n */\n orders: RampsOrder[];\n /**\n * Whether the currently selected provider was auto-selected by the system\n * (no order history, no Transak) rather than chosen by the user or derived\n * from order history. When true, the UI should silently switch providers on\n * token conflict instead of showing the \"Token Not Available\" modal.\n */\n providerAutoSelected: boolean;\n};\n\n/**\n * The metadata for each property in {@link RampsControllerState}.\n */\nconst rampsControllerMetadata = {\n userRegion: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n countries: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n providers: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n tokens: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n paymentMethods: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n requests: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: false,\n usedInUi: true,\n },\n nativeProviders: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: false,\n usedInUi: true,\n },\n orders: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n providerAutoSelected: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n} satisfies StateMetadata<RampsControllerState>;\n\n/**\n * Creates a default resource state object.\n *\n * @template TData - The type of the resource data.\n * @template TSelected - The type of the selected item.\n * @param data - The initial data value.\n * @param selected - The initial selected value.\n * @returns A ResourceState object with default loading and error values.\n */\nfunction createDefaultResourceState<TData, TSelected = null>(\n data: TData,\n selected: TSelected = null as TSelected,\n): ResourceState<TData, TSelected> {\n return {\n data,\n selected,\n isLoading: false,\n error: null,\n };\n}\n\n/**\n * Constructs the default {@link RampsController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link RampsController} state.\n */\nexport function getDefaultRampsControllerState(): RampsControllerState {\n return {\n userRegion: null,\n countries: createDefaultResourceState<Country[]>([]),\n providers: createDefaultResourceState<Provider[], Provider | null>(\n [],\n null,\n ),\n tokens: createDefaultResourceState<\n TokensResponse | null,\n RampsToken | null\n >(null, null),\n paymentMethods: createDefaultResourceState<\n PaymentMethod[],\n PaymentMethod | null\n >([], null),\n requests: {},\n nativeProviders: {\n transak: {\n isAuthenticated: false,\n userDetails: createDefaultResourceState<TransakUserDetails | null>(\n null,\n ),\n buyQuote: createDefaultResourceState<TransakBuyQuote | null>(null),\n kycRequirement:\n createDefaultResourceState<TransakKycRequirement | null>(null),\n },\n },\n orders: [],\n providerAutoSelected: false,\n };\n}\n\nconst DEPENDENT_RESOURCE_KEYS = [\n 'providers',\n 'tokens',\n 'paymentMethods',\n] as const;\n\ntype DependentResourceKey = (typeof DEPENDENT_RESOURCE_KEYS)[number];\n\nconst DEPENDENT_RESOURCE_KEYS_SET = new Set<string>(DEPENDENT_RESOURCE_KEYS);\n\nfunction getResourceState<TResourceType extends ResourceType>(\n state: Draft<RampsControllerState>,\n resourceType: TResourceType,\n): Draft<RampsControllerState[TResourceType]> {\n switch (resourceType) {\n case 'countries':\n return state.countries as Draft<RampsControllerState[TResourceType]>;\n case 'providers':\n return state.providers as Draft<RampsControllerState[TResourceType]>;\n case 'tokens':\n return state.tokens as Draft<RampsControllerState[TResourceType]>;\n case 'paymentMethods':\n return state.paymentMethods as Draft<RampsControllerState[TResourceType]>;\n /* istanbul ignore next -- ResourceType is a closed internal union. */\n default:\n throw new Error(`Unsupported resource type: ${resourceType as string}`);\n }\n}\n\nfunction resetResource(\n state: Draft<RampsControllerState>,\n resourceType: DependentResourceKey,\n defaultResource: RampsControllerState[DependentResourceKey],\n): void {\n const resource = getResourceState(state, resourceType);\n resource.data = defaultResource.data;\n resource.selected = defaultResource.selected;\n resource.isLoading = defaultResource.isLoading;\n resource.error = defaultResource.error;\n resource.errorKey = defaultResource.errorKey ?? null;\n}\n\n/**\n * Resets region-dependent resources (userRegion, providers, tokens, paymentMethods).\n * Mutates state in place; use from within controller update() for atomic updates.\n *\n * @param state - The state object to mutate.\n * @param options - Options for the reset.\n * @param options.clearUserRegionData - When true, sets userRegion to null (e.g. for full cleanup).\n */\nfunction resetDependentResources(\n state: Draft<RampsControllerState>,\n options?: { clearUserRegionData?: boolean },\n): void {\n if (options?.clearUserRegionData) {\n state.userRegion = null;\n }\n const defaultState = getDefaultRampsControllerState();\n for (const key of DEPENDENT_RESOURCE_KEYS) {\n resetResource(state, key, defaultState[key]);\n }\n state.providerAutoSelected = false;\n}\n\n// === MESSENGER ===\n\n/**\n * Retrieves the state of the {@link RampsController}.\n */\nexport type RampsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n RampsControllerState\n>;\n\n/**\n * Actions that {@link RampsControllerMessenger} exposes to other consumers.\n */\nexport type RampsControllerActions =\n | RampsControllerGetStateAction\n | RampsControllerMethodActions;\n\n/**\n * Actions from other messengers that {@link RampsController} calls.\n */\ntype AllowedActions =\n | RemoteFeatureFlagControllerGetStateAction\n | RampsServiceGetDefaultRedirectCallbackUrlAction\n | RampsServiceGetGeolocationAction\n | RampsServiceGetCountriesAction\n | RampsServiceGetTokensAction\n | RampsServiceGetProvidersAction\n | RampsServiceGetPaymentMethodsAction\n | RampsServiceGetQuotesAction\n | RampsServiceGetBuyWidgetUrlAction\n | RampsServiceGetOrderAction\n | RampsServiceGetOrderFromCallbackAction\n | TransakServiceSetApiKeyAction\n | TransakServiceSetAccessTokenAction\n | TransakServiceClearAccessTokenAction\n | TransakServiceSendUserOtpAction\n | TransakServiceVerifyUserOtpAction\n | TransakServiceLogoutAction\n | TransakServiceGetUserDetailsAction\n | TransakServiceGetBuyQuoteAction\n | TransakServiceGetKycRequirementAction\n | TransakServiceGetAdditionalRequirementsAction\n | TransakServiceCreateOrderAction\n | TransakServiceGetOrderAction\n | TransakServiceGetUserLimitsAction\n | TransakServiceRequestOttAction\n | TransakServiceGeneratePaymentWidgetUrlAction\n | TransakServiceCreateWidgetUrlAction\n | TransakServiceSubmitPurposeOfUsageFormAction\n | TransakServicePatchUserAction\n | TransakServiceSubmitSsnDetailsAction\n | TransakServiceConfirmPaymentAction\n | TransakServiceGetTranslationAction\n | TransakServiceGetIdProofStatusAction\n | TransakServiceCancelOrderAction\n | TransakServiceCancelAllActiveOrdersAction\n | TransakServiceGetActiveOrdersAction;\n\n/**\n * Published when the state of {@link RampsController} changes.\n */\nexport type RampsControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n RampsControllerState\n>;\n\n/**\n * Published when a V2 order's status transitions.\n * Consumed by mobile's init layer for notifications and analytics.\n */\nexport type RampsControllerOrderStatusChangedEvent = {\n type: `${typeof controllerName}:orderStatusChanged`;\n payload: [{ order: RampsOrder; previousStatus: RampsOrderStatus }];\n};\n\n/**\n * Events that {@link RampsControllerMessenger} exposes to other consumers.\n */\nexport type RampsControllerEvents =\n | RampsControllerStateChangeEvent\n | RampsControllerOrderStatusChangedEvent;\n\n/**\n * Events from other messengers that {@link RampsController} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link RampsController}.\n */\nexport type RampsControllerMessenger = Messenger<\n typeof controllerName,\n RampsControllerActions | AllowedActions,\n RampsControllerEvents | AllowedEvents\n>;\n\n/**\n * Configuration options for the RampsController.\n */\nexport type RampsControllerOptions = {\n /** The messenger suited for this controller. */\n messenger: RampsControllerMessenger;\n /** The desired state with which to initialize this controller. */\n state?: Partial<RampsControllerState>;\n /** Time to live for cached requests in milliseconds. Defaults to 15 minutes. */\n requestCacheTTL?: number;\n /** Maximum number of entries in the request cache. Defaults to 250. */\n requestCacheMaxSize?: number;\n};\n\n// === HELPER FUNCTIONS ===\n\n/**\n * Finds a country and state from a region code string.\n *\n * @param regionCode - The region code (e.g., \"us-ca\" or \"us\").\n * @param countries - Array of countries to search.\n * @returns UserRegion object with country and state, or null if not found.\n */\nfunction findRegionFromCode(\n regionCode: string,\n countries: Country[],\n): UserRegion | null {\n const normalizedCode = regionCode.toLowerCase().trim();\n const parts = normalizedCode.split('-');\n const countryCode = parts[0];\n const stateCode = parts[1];\n\n const country = countries.find((countryItem) => {\n if (countryItem.isoCode?.toLowerCase() === countryCode) {\n return true;\n }\n if (countryItem.id) {\n const id = countryItem.id.toLowerCase();\n if (id.startsWith('/regions/')) {\n const extractedCode = id.replace('/regions/', '').split('/')[0];\n return extractedCode === countryCode;\n }\n return id === countryCode || id.endsWith(`/${countryCode}`);\n }\n return false;\n });\n\n if (!country) {\n return null;\n }\n\n let state: State | null = null;\n if (stateCode && country.states) {\n state =\n country.states.find((stateItem) => {\n if (stateItem.stateId?.toLowerCase() === stateCode) {\n return true;\n }\n if (stateItem.id) {\n const stateId = stateItem.id.toLowerCase();\n if (\n stateId.includes(`-${stateCode}`) ||\n stateId.endsWith(`/${stateCode}`)\n ) {\n return true;\n }\n }\n return false;\n }) ?? null;\n }\n\n return {\n country,\n state,\n regionCode: normalizedCode,\n };\n}\n\n/**\n * Returns the internal MetaMask order code used for state lookups and polling.\n * Prefers the code embedded in the canonical order `id` path over `providerOrderId`,\n * which may contain the provider's native order identifier.\n *\n * @param orderOrId - Order fields or a full order id / order code string.\n * @returns The internal order code.\n */\nexport function getInternalOrderCode(\n orderOrId: Pick<RampsOrder, 'id' | 'providerOrderId'> | string,\n): string {\n if (typeof orderOrId === 'string') {\n return orderOrId.includes('/orders/')\n ? orderOrId.split('/orders/')[1]\n : orderOrId;\n }\n\n const { id, providerOrderId } = orderOrId;\n if (id?.includes('/orders/')) {\n return id.split('/orders/')[1];\n }\n\n return providerOrderId;\n}\n\n// === ORDER POLLING CONSTANTS ===\n\nconst TERMINAL_ORDER_STATUSES = new Set<RampsOrderStatus>([\n RampsOrderStatus.Completed,\n RampsOrderStatus.Failed,\n RampsOrderStatus.Cancelled,\n RampsOrderStatus.IdExpired,\n]);\n\nconst PENDING_ORDER_STATUSES = new Set<RampsOrderStatus>([\n RampsOrderStatus.Pending,\n RampsOrderStatus.Created,\n RampsOrderStatus.Unknown,\n RampsOrderStatus.Precreated,\n]);\n\nconst DEFAULT_POLLING_INTERVAL_MS = 30_000;\nconst MAX_ERROR_COUNT = 5;\n\ntype OrderPollingMetadata = {\n lastTimeFetched: number;\n errorCount: number;\n};\n\n// === CONTROLLER DEFINITION ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'executeRequest',\n 'abortRequest',\n 'getRequestState',\n 'setUserRegion',\n 'setSelectedProvider',\n 'setSelectedProviderForAsset',\n 'init',\n 'getCountries',\n 'getTokens',\n 'setSelectedToken',\n 'getProviders',\n 'getPaymentMethods',\n 'setSelectedPaymentMethod',\n 'getQuotes',\n 'addOrder',\n 'removeOrder',\n 'startOrderPolling',\n 'stopOrderPolling',\n 'getBuyWidgetData',\n 'addPrecreatedOrder',\n 'getOrder',\n 'getOrderFromCallback',\n 'transakSetApiKey',\n 'transakSetAccessToken',\n 'transakClearAccessToken',\n 'transakSetAuthenticated',\n 'transakResetState',\n 'transakSendUserOtp',\n 'transakVerifyUserOtp',\n 'transakLogout',\n 'transakGetUserDetails',\n 'transakGetBuyQuote',\n 'transakGetKycRequirement',\n 'transakGetAdditionalRequirements',\n 'transakCreateOrder',\n 'transakGetOrder',\n 'transakGetUserLimits',\n 'transakRequestOtt',\n 'transakGeneratePaymentWidgetUrl',\n 'transakCreateWidgetUrl',\n 'transakSubmitPurposeOfUsageForm',\n 'transakPatchUser',\n 'transakSubmitSsnDetails',\n 'transakConfirmPayment',\n 'transakGetTranslation',\n 'transakGetIdProofStatus',\n 'transakCancelOrder',\n 'transakCancelAllActiveOrders',\n 'transakGetActiveOrders',\n] as const;\n\n/**\n * Manages cryptocurrency on/off ramps functionality.\n */\nexport class RampsController extends BaseController<\n typeof controllerName,\n RampsControllerState,\n RampsControllerMessenger\n> {\n /**\n * Default TTL for cached requests.\n */\n readonly #requestCacheTTL: number;\n\n /**\n * Maximum number of entries in the request cache.\n */\n readonly #requestCacheMaxSize: number;\n\n /**\n * Map of pending requests for deduplication.\n * Key is the cache key, value is the pending request with abort controller.\n */\n readonly #pendingRequests: Map<string, PendingRequest> = new Map();\n\n /**\n * Count of in-flight requests per resource type.\n * Used so isLoading is only cleared when the last request for that resource finishes.\n */\n readonly #pendingResourceCount: Map<ResourceType, number> = new Map();\n\n /**\n * Monotonic generation per resource type used to invalidate stale in-flight\n * requests after region/token/provider dependent-resource resets.\n */\n readonly #pendingResourceGeneration: Map<ResourceType, number> = new Map();\n\n readonly #orderPollingMeta: Map<string, OrderPollingMetadata> = new Map();\n\n #orderPollingTimer: ReturnType<typeof setInterval> | null = null;\n\n #isPolling = false;\n\n #initPromise: Promise<void> | null = null;\n\n /**\n * Clears the pending resource count map. Used only in tests to exercise the\n * defensive path when get() returns undefined in the finally block.\n *\n * @internal\n */\n clearPendingResourceCountForTest(): void {\n this.#pendingResourceCount.clear();\n }\n\n #clearPendingResourceCountForDependentResources(): void {\n for (const resourceType of DEPENDENT_RESOURCE_KEYS) {\n this.#pendingResourceCount.delete(resourceType);\n const generation = this.#pendingResourceGeneration.get(resourceType) ?? 0;\n this.#pendingResourceGeneration.set(resourceType, generation + 1);\n }\n }\n\n #abortDependentRequests(): void {\n for (const [cacheKey, pending] of this.#pendingRequests.entries()) {\n if (\n pending.resourceType &&\n DEPENDENT_RESOURCE_KEYS_SET.has(pending.resourceType)\n ) {\n pending.abortController.abort();\n this.#pendingRequests.delete(cacheKey);\n this.#removeRequestState(cacheKey);\n }\n }\n }\n\n /**\n * Constructs a new {@link RampsController}.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this controller.\n * @param args.state - The desired state with which to initialize this\n * controller. Missing properties will be filled in with defaults.\n * @param args.requestCacheTTL - Time to live for cached requests in milliseconds.\n * @param args.requestCacheMaxSize - Maximum number of entries in the request cache.\n */\n constructor({\n messenger,\n state = {},\n requestCacheTTL = DEFAULT_REQUEST_CACHE_TTL,\n requestCacheMaxSize = DEFAULT_REQUEST_CACHE_MAX_SIZE,\n }: RampsControllerOptions) {\n super({\n messenger,\n metadata: rampsControllerMetadata,\n name: controllerName,\n state: {\n ...getDefaultRampsControllerState(),\n ...state,\n // Always reset requests cache on initialization (non-persisted)\n requests: {},\n },\n });\n\n this.#requestCacheTTL = requestCacheTTL;\n this.#requestCacheMaxSize = requestCacheMaxSize;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Resolves the Headless Buy all-providers feature flag: whether widening is\n * enabled, and the provider-id allowlist the widened pick is restricted to\n * (if the flag's object payload carries one).\n *\n * Reads `RemoteFeatureFlagController` state through the messenger on every\n * call, so a remote flag fetch or a local dev override takes effect at\n * runtime without reconstructing the controller. The single read keeps the\n * enabled bit and the allowlist consistent even if the flag changes while a\n * quote request is in flight. Key lookup, local-override merging, and value\n * coercion live in the shared `isHeadlessAllProvidersEnabled` /\n * `getHeadlessProviderAllowlist` helpers so UI consumers resolve the flag\n * identically. Fails closed: when `RemoteFeatureFlagController:getState` is\n * not wired up, quoting stays native-only.\n *\n * @returns The enabled bit and the optional provider-id allowlist.\n */\n #resolveAllProvidersFlag(): {\n enabled: boolean;\n allowlist?: string[];\n } {\n try {\n const remoteFeatureFlagState = this.messenger.call(\n 'RemoteFeatureFlagController:getState',\n );\n return {\n enabled: isHeadlessAllProvidersEnabled(remoteFeatureFlagState),\n allowlist: getHeadlessProviderAllowlist(remoteFeatureFlagState),\n };\n } catch {\n return { enabled: false };\n }\n }\n\n /**\n * Executes a request with caching, deduplication, and at most one in-flight\n * request per resource type.\n *\n * 1. **Same cache key in flight** – If a request with this cache key is\n * already pending, returns that promise (deduplication; no second request).\n *\n * 2. **Cache hit** – If valid, non-expired data exists in state.requests for\n * this key and forceRefresh is not set, returns that data without fetching.\n *\n * 3. **New request** – Creates an AbortController and fires the fetcher.\n * If options.resourceType is set, tags the pending request with that\n * resource type (so #abortDependentRequests can cancel it on region\n * change or cleanup) and ref-counts resource-level loading state.\n * On success or error, updates request state and resource error;\n * in finally, clears resource loading only if this request was not\n * aborted.\n *\n * @param cacheKey - Unique identifier for this request (e.g. from createCacheKey).\n * @param fetcher - Async function that performs the fetch. Receives an AbortSignal\n * that is aborted when this request is superseded by another for the same resource.\n * @param options - Optional forceRefresh, ttl, and resourceType for loading/error state.\n * @returns The result of the request (from cache, joined promise, or fetcher).\n */\n async executeRequest<TResult>(\n cacheKey: string,\n fetcher: (signal: AbortSignal) => Promise<TResult>,\n options?: ExecuteRequestOptions,\n ): Promise<TResult> {\n // Get TTL for verifying cache expiration\n const ttl = options?.ttl ?? this.#requestCacheTTL;\n\n // DEDUPLICATION:\n // Check if a request is already in flight for this cache key\n // If so, return the original promise for that request\n const pending = this.#pendingRequests.get(cacheKey);\n if (pending) {\n return pending.promise as Promise<TResult>;\n }\n\n // CACHE HIT:\n // If cache is not expired, return the cached data\n if (!options?.forceRefresh) {\n const cached = this.state.requests[cacheKey];\n if (cached && !isCacheExpired(cached, ttl)) {\n return cached.data as TResult;\n }\n }\n\n // Create a new abort controller for this request\n // Record the time the request was started\n const abortController = new AbortController();\n const lastFetchedAt = Date.now();\n const { resourceType } = options ?? {};\n const resourceGeneration = resourceType\n ? (this.#pendingResourceGeneration.get(resourceType) ?? 0)\n : undefined;\n\n // Update state to loading\n this.#updateRequestState(cacheKey, createLoadingState());\n\n // Set resource-level loading state (only on cache miss). Ref-count so concurrent\n // requests for the same resource type (different cache keys) keep isLoading true.\n if (resourceType) {\n const count = this.#pendingResourceCount.get(resourceType) ?? 0;\n this.#pendingResourceCount.set(resourceType, count + 1);\n if (count === 0) {\n this.#setResourceLoading(resourceType, true);\n }\n }\n\n // Create the fetch promise\n const promise = (async (): Promise<TResult> => {\n try {\n const data = await fetcher(abortController.signal);\n\n if (abortController.signal.aborted) {\n throw new Error('Request was aborted');\n }\n\n this.#updateRequestState(\n cacheKey,\n createSuccessState(data as Json, lastFetchedAt),\n );\n\n if (resourceType) {\n const isCurrent =\n !options?.isResultCurrent || options.isResultCurrent();\n if (isCurrent) {\n this.#setResourceError(resourceType, null);\n }\n }\n return data;\n } catch (error) {\n if (abortController.signal.aborted) {\n throw error;\n }\n\n const { errorInfo, normalizedError } = getNormalizedRampsError(error);\n this.#updateRequestState(\n cacheKey,\n createErrorState(\n errorInfo.message,\n lastFetchedAt,\n errorInfo.errorKey,\n ),\n );\n if (resourceType) {\n const isCurrent =\n !options?.isResultCurrent || options.isResultCurrent();\n if (isCurrent) {\n this.#setResourceError(resourceType, errorInfo);\n }\n }\n throw normalizedError;\n } finally {\n if (\n this.#pendingRequests.get(cacheKey)?.abortController ===\n abortController\n ) {\n this.#pendingRequests.delete(cacheKey);\n }\n\n // Clear resource-level loading state only when no requests for this resource remain\n if (resourceType && !abortController.signal.aborted) {\n const currentGeneration =\n this.#pendingResourceGeneration.get(resourceType) ?? 0;\n if (currentGeneration === resourceGeneration) {\n const count = this.#pendingResourceCount.get(resourceType) ?? 0;\n const next = Math.max(0, count - 1);\n if (next === 0) {\n this.#pendingResourceCount.delete(resourceType);\n this.#setResourceLoading(resourceType, false);\n } else {\n this.#pendingResourceCount.set(resourceType, next);\n }\n }\n }\n }\n })();\n\n this.#pendingRequests.set(cacheKey, {\n promise,\n abortController,\n resourceType,\n });\n\n return promise;\n }\n\n /**\n * Aborts a pending request if one exists.\n *\n * @param cacheKey - The cache key of the request to abort.\n * @returns True if a request was aborted.\n */\n abortRequest(cacheKey: string): boolean {\n const pending = this.#pendingRequests.get(cacheKey);\n if (pending) {\n pending.abortController.abort();\n this.#pendingRequests.delete(cacheKey);\n this.#removeRequestState(cacheKey);\n return true;\n }\n return false;\n }\n\n /**\n * Mutates state.requests inside update(); cast is centralized here.\n *\n * @param fn - Callback that mutates the requests record.\n */\n #mutateRequests(\n fn: (requests: Record<string, RequestState | undefined>) => void,\n ): void {\n this.update((state) => {\n const requests = state.requests as unknown as Record<\n string,\n RequestState | undefined\n >;\n fn(requests);\n });\n }\n\n #removeRequestState(cacheKey: string): void {\n this.#mutateRequests((requests) => {\n delete requests[cacheKey];\n });\n }\n\n #cleanupState(): void {\n this.#abortDependentRequests();\n this.#clearPendingResourceCountForDependentResources();\n this.update((state) =>\n resetDependentResources(state, { clearUserRegionData: true }),\n );\n }\n\n #requireRegion(): string {\n const regionCode = this.state.userRegion?.regionCode;\n if (!regionCode) {\n throw new Error(\n 'Region is required. Cannot proceed without valid region information.',\n );\n }\n return regionCode;\n }\n\n #isRegionCurrent(normalizedRegion: string): boolean {\n const current = this.state.userRegion?.regionCode;\n return current === undefined || current === normalizedRegion;\n }\n\n #isTokenCurrent(normalizedAssetId: string): boolean {\n const current = this.state.tokens.selected?.assetId ?? '';\n return current === normalizedAssetId;\n }\n\n #isProviderCurrent(normalizedProviderId: string): boolean {\n const current = this.state.providers.selected?.id ?? '';\n return current === normalizedProviderId;\n }\n\n /**\n * Updates a single field (isLoading or error) on a resource state.\n * All resources share the same ResourceState structure, so we use\n * dynamic property access to avoid duplicating switch statements.\n *\n * @param resourceType - The type of resource.\n * @param field - The field to update ('isLoading' or 'error').\n * @param value - The value to set.\n */\n #updateResourceField(\n resourceType: ResourceType,\n field: 'isLoading' | 'error' | 'errorKey',\n value: boolean | string | RampsErrorCode | null,\n ): void {\n this.update((state) => {\n const resource = getResourceState(state, resourceType);\n (resource as Record<string, unknown>)[field] = value;\n });\n }\n\n /**\n * Sets the loading state for a resource type.\n *\n * @param resourceType - The type of resource.\n * @param loading - Whether the resource is loading.\n */\n #setResourceLoading(resourceType: ResourceType, loading: boolean): void {\n this.#updateResourceField(resourceType, 'isLoading', loading);\n }\n\n /**\n * Sets the error state for a resource type.\n *\n * @param resourceType - The type of resource.\n * @param errorInfo - The error info, or null to clear.\n */\n #setResourceError(\n resourceType: ResourceType,\n errorInfo: RampsErrorInfo | null,\n ): void {\n this.update((state) => {\n const resource = getResourceState(state, resourceType);\n resource.error = errorInfo?.message ?? null;\n resource.errorKey = errorInfo?.errorKey ?? null;\n });\n }\n\n /**\n * Gets the state of a specific cached request.\n *\n * @param cacheKey - The cache key to look up.\n * @returns The request state, or undefined if not cached.\n */\n getRequestState(cacheKey: string): RequestState | undefined {\n return this.state.requests[cacheKey];\n }\n\n /**\n * Updates the state for a specific request.\n *\n * @param cacheKey - The cache key.\n * @param requestState - The new state for the request.\n */\n #updateRequestState(cacheKey: string, requestState: RequestState): void {\n const maxSize = this.#requestCacheMaxSize;\n const ttl = this.#requestCacheTTL;\n this.#mutateRequests((requests) => {\n requests[cacheKey] = requestState;\n const keys = Object.keys(requests);\n for (const key of keys) {\n const entry = requests[key];\n if (\n entry?.status === RequestStatus.SUCCESS &&\n isCacheExpired(entry, ttl)\n ) {\n delete requests[key];\n }\n }\n const remainingKeys = Object.keys(requests);\n if (remainingKeys.length > maxSize) {\n const sortedKeys = remainingKeys.sort((a, b) => {\n const aTime = requests[a]?.timestamp ?? 0;\n const bTime = requests[b]?.timestamp ?? 0;\n return aTime - bTime;\n });\n const entriesToRemove = remainingKeys.length - maxSize;\n for (let i = 0; i < entriesToRemove; i++) {\n const keyToRemove = sortedKeys[i];\n if (keyToRemove) {\n delete requests[keyToRemove];\n }\n }\n }\n });\n }\n\n /**\n * Sets the user's region manually (without fetching geolocation).\n * This allows users to override the detected region.\n *\n * @param region - The region code to set (e.g., \"US-CA\").\n * @param options - Options for cache behavior.\n * @returns The user region object.\n */\n async setUserRegion(\n region: string,\n options?: ExecuteRequestOptions,\n ): Promise<UserRegion> {\n const normalizedRegion = region.toLowerCase().trim();\n\n try {\n const countriesData = this.state.countries.data;\n if (!countriesData || countriesData.length === 0) {\n this.#cleanupState();\n throw new Error(\n 'No countries found. Cannot set user region without valid country information.',\n );\n }\n\n const userRegion = findRegionFromCode(normalizedRegion, countriesData);\n\n if (!userRegion) {\n this.#cleanupState();\n throw new Error(\n `Region \"${normalizedRegion}\" not found in countries data. Cannot set user region without valid country information.`,\n );\n }\n\n const regionChanged =\n Boolean(options?.forceRefresh) ||\n normalizedRegion !== this.state.userRegion?.regionCode;\n\n if (regionChanged) {\n // Note: we intentionally do NOT abort in-flight requests here.\n // Aborting causes data loss during rapid region switching (e.g.\n // user taps France → Finland → France quickly). Instead we let\n // old requests complete naturally; isResultCurrent guards in\n // getProviders/getPaymentMethods discard stale results.\n this.#clearPendingResourceCountForDependentResources();\n }\n this.update((state) => {\n if (regionChanged) {\n resetDependentResources(state);\n }\n state.userRegion = userRegion;\n });\n\n return userRegion;\n } catch (error) {\n this.#cleanupState();\n throw error;\n }\n }\n\n /**\n * Sets the user's selected provider.\n *\n * Accepts either a Provider object (stored directly) or a provider ID\n * string (looked up from state). The object form is preferred when the\n * caller already has the full data (e.g. from React Query cache).\n *\n * @param providerOrId - A Provider object, a provider ID string (e.g., \"/providers/moonpay\"), or null to clear.\n * @param options - Optional settings for the selection.\n * @param options.autoSelected - When true, marks the provider as system-guessed\n * (soft selection). The UI will silently auto-switch on token conflict instead\n * of showing the \"Token Not Available\" modal. Defaults to false.\n */\n setSelectedProvider(\n providerOrId: string | Provider | null,\n options?: { autoSelected?: boolean },\n ): void {\n if (providerOrId === null) {\n this.update((state) => {\n state.providers.selected = null;\n state.providerAutoSelected = false;\n });\n return;\n }\n\n this.#requireRegion();\n\n // If a full Provider object is passed, store it directly (avoids\n // depending on state.providers.data being populated).\n if (typeof providerOrId !== 'string') {\n this.update((state) => {\n state.providers.selected = providerOrId;\n state.providerAutoSelected = options?.autoSelected ?? false;\n });\n return;\n }\n\n // ID string: look up from state\n const providers = this.state.providers.data;\n const provider = providers?.find((prov) => prov.id === providerOrId);\n\n if (provider) {\n this.update((state) => {\n state.providers.selected = provider;\n state.providerAutoSelected = options?.autoSelected ?? false;\n });\n }\n }\n\n /**\n * Switches to the first provider in state that serves the given asset,\n * when the currently selected provider does not.\n *\n * This is the controller-level equivalent of UB2's BuildQuote tier-1\n * silent-switch effect and MMPay's `useEnsureCompatibleProvider` hook: it\n * keeps provider-asset compatibility logic in one place rather than\n * duplicating `providerServesAsset` + find-and-switch across multiple UI\n * layers.\n *\n * The compatibility check prefers the current provider's entry in\n * `providers.data` over the `providers.selected` copy, which can be stale\n * once a fresh providers list arrives.\n *\n * No-op when:\n * - `providers.data` is empty (providers not yet loaded)\n * - the currently selected provider already serves the asset\n * - no provider in the list serves the asset (no safe fallback)\n *\n * @param assetId - CAIP-19 asset id of the deposit asset.\n * @param options - Optional settings forwarded to `setSelectedProvider`.\n * @param options.autoSelected - When true, marks the new selection as\n * system-guessed (soft selection). Defaults to true.\n * @returns `true` if the selected provider was changed, `false` otherwise.\n */\n setSelectedProviderForAsset(\n assetId: string,\n options?: { autoSelected?: boolean },\n ): boolean {\n const providers = this.state.providers.data;\n if (!providers?.length) {\n return false;\n }\n\n const selectedId = this.state.providers.selected?.id;\n const currentProvider =\n providers.find((provider) => provider.id === selectedId) ??\n this.state.providers.selected;\n if (currentProvider && providerServesAsset(currentProvider, assetId)) {\n return false;\n }\n\n const compatible = providers.find(\n (provider) =>\n provider.id !== selectedId && providerServesAsset(provider, assetId),\n );\n if (!compatible) {\n return false;\n }\n\n this.setSelectedProvider(compatible, {\n autoSelected: true,\n ...options,\n });\n return true;\n }\n\n /**\n * Initializes the controller by fetching the user's region from geolocation.\n * This should be called once at app startup to set up the initial region.\n *\n * Idempotent: subsequent calls return the same promise unless forceRefresh is set.\n * Force-refetches the countries catalog on startup (bypassing the in-session\n * request cache) so region preset amounts stay current. The catalog is not\n * persisted, so a cold start always re-fetches it regardless. Skips\n * geolocation when userRegion already exists.\n *\n * @param options - Options for cache behavior. forceRefresh bypasses idempotency and re-runs the full flow.\n * @returns Promise that resolves when initialization is complete.\n */\n async init(options?: ExecuteRequestOptions): Promise<void> {\n if (!options?.forceRefresh && this.#initPromise !== null) {\n return this.#initPromise;\n }\n\n if (options?.forceRefresh) {\n this.#initPromise = null;\n }\n\n const initPromise = this.#runInit(options).then(\n () => undefined,\n (error) => {\n if (this.#initPromise === initPromise) {\n this.#initPromise = null;\n }\n throw error;\n },\n );\n this.#initPromise = initPromise;\n return initPromise;\n }\n\n async #runInit(options?: ExecuteRequestOptions): Promise<void> {\n // Force-refetch the catalog on startup so region preset amounts stay\n // current, bypassing the in-session request cache. The catalog is not\n // persisted, so a cold start always re-fetches it regardless.\n await this.getCountries({ ...options, forceRefresh: true });\n\n // Always prefer the user's persisted region. Geolocation is only used to\n // seed the initial value; once the user (or a prior init) has set a region\n // we must respect that choice — even on forceRefresh.\n const persistedRegionCode = this.state.userRegion?.regionCode;\n const regionCode =\n persistedRegionCode ??\n (await this.messenger.call('RampsService:getGeolocation'));\n\n if (!regionCode) {\n throw new Error(\n 'Failed to fetch geolocation. Cannot initialize controller without valid region information.',\n );\n }\n\n // For an already-persisted region, getCountries() has already re-synced it\n // from the fresh catalog (see #syncUserRegionFromCountriesCatalog). Calling\n // setUserRegion here would re-validate against that catalog and, if it is\n // momentarily empty or no longer lists the region (e.g. a transient/partial\n // catalog response or a region with no current provider coverage), throw and\n // wipe the persisted region via #cleanupState. Preserve the existing region\n // instead; only resolve a brand-new region (from geolocation) strictly.\n if (persistedRegionCode) {\n return;\n }\n\n await this.setUserRegion(regionCode, options);\n }\n\n /**\n * Re-applies `userRegion` from the current countries catalog so preset\n * amounts and support flags stay in sync after a catalog refresh.\n */\n #syncUserRegionFromCountriesCatalog(): void {\n const regionCode = this.state.userRegion?.regionCode;\n if (!regionCode) {\n return;\n }\n\n const countriesData = this.state.countries.data;\n if (!countriesData.length) {\n return;\n }\n\n const userRegion = findRegionFromCode(regionCode, countriesData);\n if (!userRegion) {\n return;\n }\n\n this.update((state) => {\n state.userRegion = userRegion;\n });\n }\n\n /**\n * Fetches the list of supported countries.\n * The API returns countries with support information for both buy and sell actions.\n * The countries are saved in the controller state once fetched.\n *\n * @param options - Options for cache behavior.\n * @returns An array of countries.\n */\n async getCountries(options?: ExecuteRequestOptions): Promise<Country[]> {\n const cacheKey = createCacheKey('getCountries', []);\n\n const countries = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call('RampsService:getCountries');\n },\n { ...options, resourceType: 'countries' },\n );\n\n this.update((state) => {\n state.countries.data = Array.isArray(countries) ? [...countries] : [];\n });\n\n this.#syncUserRegionFromCountriesCatalog();\n\n return countries;\n }\n\n /**\n * Fetches the list of available tokens for a given region and action.\n * The tokens are saved in the controller state once fetched.\n *\n * @param region - The region code (e.g., \"us\", \"fr\", \"us-ny\"). If not provided, uses the user's region from controller state.\n * @param action - The ramp action type ('buy' or 'sell').\n * @param options - Options for cache behavior and query filters.\n * @param options.provider - Provider ID(s) to filter by.\n * @returns The tokens response containing topTokens and allTokens.\n */\n async getTokens(\n region?: string,\n action: RampAction = 'buy',\n options?: ExecuteRequestOptions & {\n provider?: string | string[];\n },\n ): Promise<TokensResponse> {\n const regionToUse = region ?? this.#requireRegion();\n\n const normalizedRegion = regionToUse.toLowerCase().trim();\n const cacheKey = createCacheKey('getTokens', [\n normalizedRegion,\n action,\n options?.provider,\n ]);\n\n const tokens = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call(\n 'RampsService:getTokens',\n normalizedRegion,\n action,\n {\n provider: options?.provider,\n },\n );\n },\n {\n ...options,\n resourceType: 'tokens',\n isResultCurrent: () => this.#isRegionCurrent(normalizedRegion),\n },\n );\n\n this.update((state) => {\n const userRegionCode = state.userRegion?.regionCode;\n\n if (userRegionCode === undefined || userRegionCode === normalizedRegion) {\n state.tokens.data = tokens;\n }\n });\n\n return tokens;\n }\n\n /**\n * Sets the user's selected token by asset ID.\n * Looks up the token from the current tokens in state and automatically\n * fetches payment methods for that token.\n *\n * @param assetId - The asset identifier in CAIP-19 format (e.g., \"eip155:1/erc20:0x...\"), or undefined to clear.\n * @throws If region is not set, tokens are not loaded, or token is not found.\n */\n setSelectedToken(assetId?: string): void {\n if (!assetId) {\n this.update((state) => {\n state.tokens.selected = null;\n });\n return;\n }\n\n this.#requireRegion();\n const tokens = this.state.tokens.data;\n if (!tokens) {\n throw new Error(\n 'Tokens not loaded. Cannot set selected token before tokens are fetched.',\n );\n }\n\n const token =\n tokens.allTokens.find((tok) => tok.assetId === assetId) ??\n tokens.topTokens.find((tok) => tok.assetId === assetId);\n\n if (!token) {\n throw new Error(\n `Token with asset ID \"${assetId}\" not found in available tokens.`,\n );\n }\n\n this.update((state) => {\n state.tokens.selected = token;\n });\n }\n\n /**\n * Fetches the list of providers for a given region.\n * The providers are saved in the controller state once fetched.\n *\n * @param region - The region code (e.g., \"us\", \"fr\", \"us-ny\"). If not provided, uses the user's region from controller state.\n * @param options - Options for cache behavior and query filters.\n * @param options.provider - Provider ID(s) to filter by.\n * @param options.crypto - Crypto currency ID(s) to filter by.\n * @param options.payments - Payment method ID(s) to filter by.\n * @returns The providers response containing providers array.\n */\n async getProviders(\n region?: string,\n options?: ExecuteRequestOptions & {\n provider?: string | string[];\n crypto?: string | string[];\n payments?: string | string[];\n },\n ): Promise<{ providers: Provider[] }> {\n const regionToUse = region ?? this.#requireRegion();\n\n const normalizedRegion = regionToUse.toLowerCase().trim();\n const cacheKey = createCacheKey('getProviders', [\n normalizedRegion,\n options?.provider,\n options?.crypto,\n options?.payments,\n ]);\n\n const { providers } = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call(\n 'RampsService:getProviders',\n normalizedRegion,\n {\n provider: options?.provider,\n crypto: options?.crypto,\n payments: options?.payments,\n },\n );\n },\n {\n ...options,\n resourceType: 'providers',\n isResultCurrent: () => this.#isRegionCurrent(normalizedRegion),\n },\n );\n\n this.update((state) => {\n const userRegionCode = state.userRegion?.regionCode;\n\n if (userRegionCode === undefined || userRegionCode === normalizedRegion) {\n state.providers.data = providers;\n }\n });\n\n return { providers };\n }\n\n /**\n * Fetches the list of payment methods for a given context.\n * The payment methods are saved in the controller state once fetched.\n *\n * @param region - User's region code (e.g. \"fr\", \"us-ny\").\n * @param options - Query parameters for filtering payment methods.\n * @param options.assetId - CAIP-19 cryptocurrency identifier.\n * @param options.provider - Provider ID path.\n * @returns The payment methods response containing payments array.\n */\n async getPaymentMethods(\n region?: string,\n options?: ExecuteRequestOptions & {\n assetId?: string;\n provider?: string;\n },\n ): Promise<PaymentMethodsResponse> {\n const regionCode = region ?? this.#requireRegion();\n const assetIdToUse =\n options?.assetId ?? this.state.tokens.selected?.assetId ?? '';\n const providerToUse =\n options?.provider ?? this.state.providers.selected?.id ?? '';\n\n const normalizedRegion = regionCode.toLowerCase().trim();\n const cacheKey = createCacheKey('getPaymentMethods', [\n normalizedRegion,\n assetIdToUse,\n providerToUse,\n ]);\n\n const response = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call('RampsService:getPaymentMethods', {\n region: normalizedRegion,\n assetId: assetIdToUse,\n provider: providerToUse,\n });\n },\n {\n ...options,\n resourceType: 'paymentMethods',\n isResultCurrent: () => {\n const regionMatch = this.#isRegionCurrent(normalizedRegion);\n const tokenMatch = this.#isTokenCurrent(assetIdToUse);\n const providerMatch = this.#isProviderCurrent(providerToUse);\n return regionMatch && tokenMatch && providerMatch;\n },\n },\n );\n\n this.update((state) => {\n const currentAssetId = state.tokens.selected?.assetId ?? '';\n const currentProviderId = state.providers.selected?.id ?? '';\n\n const tokenSelectionUnchanged = assetIdToUse === currentAssetId;\n const providerSelectionUnchanged = providerToUse === currentProviderId;\n\n // this is a race condition check to ensure that the selected token and provider in state are the same as the tokens we're requesting for\n // ex: if the user rapidly changes the token or provider, the in-flight payment methods might not be valid\n // so this check will ensure that the payment methods are still valid for the token and provider that were requested\n if (tokenSelectionUnchanged && providerSelectionUnchanged) {\n state.paymentMethods.data = response.payments;\n\n // this will auto-select the first payment method if the selected payment method is not in the new payment methods\n const currentSelectionStillValid = response.payments.some(\n (pm: PaymentMethod) => pm.id === state.paymentMethods.selected?.id,\n );\n if (!currentSelectionStillValid) {\n state.paymentMethods.selected = response.payments[0] ?? null;\n }\n }\n });\n\n return response;\n }\n\n /**\n * Sets the user's selected payment method.\n *\n * Accepts either a payment method ID (looked up from state) or a full\n * PaymentMethod object (stored directly). The object form is preferred\n * when the caller already has the full data (e.g. from React Query cache),\n * as it avoids depending on controller state being populated.\n *\n * @param paymentMethodOrId - A PaymentMethod object, a payment method ID string, or undefined/null to clear.\n */\n setSelectedPaymentMethod(\n paymentMethodOrId?: string | PaymentMethod | null,\n ): void {\n if (!paymentMethodOrId) {\n this.update((state) => {\n state.paymentMethods.selected = null;\n });\n return;\n }\n\n // If a full object is passed, store it directly\n if (typeof paymentMethodOrId !== 'string') {\n this.update((state) => {\n state.paymentMethods.selected = paymentMethodOrId;\n });\n return;\n }\n\n // ID string: look up from state\n const paymentMethodId = paymentMethodOrId;\n const paymentMethods = this.state.paymentMethods.data;\n const paymentMethod = paymentMethods?.find(\n (pm) => pm.id === paymentMethodId,\n );\n\n this.update((state) => {\n state.paymentMethods.selected = paymentMethod ?? null;\n });\n }\n\n /**\n * Fetches quotes from all providers for a given set of parameters.\n * Uses the controller's request cache; callers manage the response in local state.\n *\n * @param options - The parameters for fetching quotes.\n * @param options.region - User's region code. If not provided, uses userRegion from state.\n * @param options.fiat - Fiat currency code. If not provided, uses userRegion currency.\n * @param options.assetId - CAIP-19 cryptocurrency identifier.\n * @param options.amount - The amount (in fiat for buy, crypto for sell).\n * @param options.walletAddress - The destination wallet address.\n * @param options.paymentMethods - Array of payment method IDs. If not provided, uses paymentMethods from state.\n * @param options.providers - Optional provider IDs to filter quotes.\n * @param options.autoSelectProvider - When true and `providers` is omitted,\n * resolves a provider that supports `assetId` for this request only (no\n * state mutation). Ignored when `providers` is passed.\n * @param options.preferredProviderIds - Optional provider IDs to prefer\n * during auto-selection, in priority order (e.g. derived by the caller\n * from completed-order history). Only used when `autoSelectProvider` is\n * true and `providers` is omitted.\n * @param options.restrictToKnownOrNativeProviders - Headless-buy v0 gating. When\n * true, auto-selection resolves only a native provider, and an explicitly\n * passed `providers` list is filtered to those supporting the region and\n * asset. If nothing qualifies, `getQuotes` returns an empty response\n * instead of quoting other providers.\n * @param options.redirectUrl - Optional redirect URL after order completion.\n * @param options.action - The ramp action type. Defaults to 'buy'.\n * @param options.forceRefresh - Whether to bypass cache.\n * @param options.ttl - Custom TTL for this request.\n * @returns The quotes response containing success, sorted, error, and customActions.\n */\n async getQuotes(options: {\n region?: string;\n fiat?: string;\n assetId?: string;\n amount: number;\n walletAddress: string;\n paymentMethods?: string[];\n providers?: string[];\n autoSelectProvider?: boolean;\n preferredProviderIds?: string[];\n restrictToKnownOrNativeProviders?: boolean;\n redirectUrl?: string;\n action?: RampAction;\n forceRefresh?: boolean;\n ttl?: number;\n }): Promise<QuotesResponse> {\n const regionToUse = options.region ?? this.#requireRegion();\n const fiatToUse = options.fiat ?? this.state.userRegion?.country?.currency;\n const paymentMethodsToUse =\n options.paymentMethods ??\n this.state.paymentMethods.data.map((pm: PaymentMethod) => pm.id);\n const action = options.action ?? 'buy';\n const assetIdToUse = options.assetId ?? this.state.tokens.selected?.assetId;\n\n if (!fiatToUse) {\n throw new Error(\n 'Fiat currency is required. Either provide a fiat parameter or ensure userRegion is set in controller state.',\n );\n }\n\n const normalizedAssetIdForValidation = (assetIdToUse ?? '').trim();\n if (normalizedAssetIdForValidation === '') {\n throw new Error('assetId is required.');\n }\n\n // When the all-providers feature flag is enabled, widen the native-only\n // auto-selection path to every supporting provider and pick the best\n // quote from the results. Only the auto-select/restrict path that MM Pay's\n // `getRampsQuote` uses is affected; explicit-`providers` callers and the\n // plain all-provider path are untouched (and never read the flag).\n const wantsAutoSelection =\n !options.providers &&\n (options.autoSelectProvider === true ||\n options.restrictToKnownOrNativeProviders === true);\n // Single flag read per call: the enabled bit and the allowlist come from\n // the same `RemoteFeatureFlagController` state snapshot, so a flag edit\n // during the awaited quote fetch cannot produce a mixed read.\n const { enabled: allProvidersEnabled, allowlist: providerAllowlist } =\n wantsAutoSelection\n ? this.#resolveAllProvidersFlag()\n : { enabled: false, allowlist: undefined };\n const widenToAllProviders = wantsAutoSelection && allProvidersEnabled;\n\n let providersToUse: string[];\n let widenedProviderCatalog: Provider[] = this.state.providers.data;\n if (options.providers) {\n providersToUse = options.restrictToKnownOrNativeProviders\n ? await this.#filterProviderIdsBySupport({\n providerIds: options.providers,\n assetId: normalizedAssetIdForValidation,\n region: regionToUse,\n })\n : options.providers;\n } else if (widenToAllProviders) {\n // `#getSupportingProvidersForRegion` also hydrates the provider catalog\n // when controller state is empty, so all-provider quoting cannot silently\n // return zero providers here.\n const { supporting } = await this.#getSupportingProvidersForRegion({\n assetId: normalizedAssetIdForValidation,\n region: regionToUse,\n });\n widenedProviderCatalog = supporting;\n providersToUse = supporting.map((provider) => provider.id);\n } else if (\n options.autoSelectProvider ||\n options.restrictToKnownOrNativeProviders\n ) {\n // The restriction flag implies resolution: it must narrow the provider\n // set even when `autoSelectProvider` was not explicitly passed, otherwise\n // it would be silently ignored and every provider quoted.\n providersToUse = await this.#resolveProviderIdsForQuote({\n assetId: normalizedAssetIdForValidation,\n region: regionToUse,\n preferredProviderIds: options.preferredProviderIds,\n restrictToKnownOrNative: options.restrictToKnownOrNativeProviders,\n });\n } else {\n providersToUse = this.state.providers.data.map(\n (provider: Provider) => provider.id,\n );\n }\n\n if (\n !paymentMethodsToUse ||\n paymentMethodsToUse.length === 0 ||\n paymentMethodsToUse.some((pm) => pm.trim() === '')\n ) {\n throw new Error(\n 'Payment methods are required. Either provide paymentMethods parameter or ensure paymentMethods are set in controller state.',\n );\n }\n\n if (options.amount <= 0 || !Number.isFinite(options.amount)) {\n throw new Error('Amount must be a positive finite number.');\n }\n\n if (!options.walletAddress || options.walletAddress.trim() === '') {\n throw new Error('walletAddress is required.');\n }\n\n // Under headless-buy gating, an empty resolved provider list means no\n // eligible (native/supporting) provider exists. Return an empty response\n // rather than passing `[]` to the service, which omits the provider filter\n // and would quote every provider. This also guards the widened path:\n // a caller may trigger widening with `autoSelectProvider` alone (no\n // `restrictToKnownOrNativeProviders`), and an empty supporting set must not\n // fall through to unfiltered quotes from providers that do not support the\n // asset.\n if (\n (options.restrictToKnownOrNativeProviders || widenToAllProviders) &&\n providersToUse.length === 0\n ) {\n return { success: [], sorted: [], error: [], customActions: [] };\n }\n\n const normalizedRegion = regionToUse.toLowerCase().trim();\n const normalizedFiat = fiatToUse.toLowerCase().trim();\n const normalizedAssetId = normalizedAssetIdForValidation;\n const normalizedWalletAddress = options.walletAddress.trim();\n\n // The quotes API only embeds a `buyURL`/`buyWidget` when a `redirectUrl` is\n // present, so on the widened path (where MM Pay omits one) ask the service\n // for the callback URL of the environment it is configured with, so\n // aggregator quotes carry a usable widget URL that always matches the\n // environment the quotes came from. An explicit caller `redirectUrl`\n // always wins, and the native-only path (flag off) never injects, so\n // neither reaches the service.\n const effectiveRedirectUrl =\n options.redirectUrl ??\n (widenToAllProviders\n ? this.messenger.call('RampsService:getDefaultRedirectCallbackUrl')\n : undefined);\n\n const cacheKey = createCacheKey('getQuotes', [\n normalizedRegion,\n normalizedFiat,\n normalizedAssetId,\n options.amount,\n normalizedWalletAddress,\n [...paymentMethodsToUse].sort().join(','),\n [...providersToUse].sort().join(','),\n effectiveRedirectUrl,\n action,\n ]);\n\n const params = {\n region: normalizedRegion,\n fiat: normalizedFiat,\n assetId: normalizedAssetId,\n amount: options.amount,\n walletAddress: normalizedWalletAddress,\n paymentMethods: paymentMethodsToUse,\n providers: providersToUse,\n redirectUrl: effectiveRedirectUrl,\n action,\n };\n\n const response = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call('RampsService:getQuotes', params);\n },\n {\n forceRefresh: options.forceRefresh,\n ttl: options.ttl ?? DEFAULT_QUOTES_TTL,\n },\n );\n\n if (!widenToAllProviders) {\n return response;\n }\n\n // Reduce the widened multi-provider result to the single best quote\n // and place it at `success[0]`, since single-pick consumers\n // (`getRampsQuote` -> `success?.[0]`) rely on index 0 while `success[]`\n // order is server-defined rather than ranked.\n const selectedQuote = this.#pickWidenedQuote(response, {\n amount: options.amount,\n fiat: normalizedFiat,\n providers: widenedProviderCatalog,\n allowlist: providerAllowlist,\n });\n\n if (!selectedQuote) {\n // No quote fits the published provider limits: surface \"no quote\"\n // rather than handing the single-pick consumer an out-of-limits quote.\n return {\n success: [],\n sorted: response.sorted,\n error: response.error,\n customActions: response.customActions,\n };\n }\n\n return {\n ...response,\n success: [\n selectedQuote,\n ...response.success.filter((quote) => quote !== selectedQuote),\n ],\n };\n }\n\n /**\n * Selects the best quote from a widened multi-provider response.\n *\n * Every provider class is eligible (native, in-app WebView aggregator, and\n * external-browser / custom-action). When the feature flag payload carries a\n * provider allowlist, candidates from unlisted providers are dropped first.\n * Enforces per-provider fiat limits up front, then orders by reliability and\n * falls back to price using the server-provided `sorted` order. Returns\n * `undefined` when no quote survives.\n *\n * @param response - The multi-provider quotes response.\n * @param options - Selection inputs.\n * @param options.amount - Fiat amount, for the limit-fit check.\n * @param options.fiat - Lowercased fiat short code, for the limit lookup.\n * @param options.providers - Provider catalog for the limit lookup.\n * @param options.allowlist - Optional provider ids (either `/providers/x`\n * or bare form) the pick is restricted to.\n * @returns The selected quote, or `undefined` when none is usable.\n */\n #pickWidenedQuote(\n response: QuotesResponse,\n {\n amount,\n fiat,\n providers,\n allowlist,\n }: {\n amount: number;\n fiat: string;\n providers: Provider[];\n allowlist?: string[];\n },\n ): Quote | undefined {\n const providerByCode = new Map(\n providers.map((provider) => [provider.id, provider]),\n );\n\n const allowedProviderIds =\n allowlist && allowlist.length > 0\n ? new Set(allowlist.map(normalizeHeadlessProviderId))\n : undefined;\n const isAllowedProvider = (quote: Quote): boolean =>\n !allowedProviderIds ||\n allowedProviderIds.has(normalizeHeadlessProviderId(quote.provider));\n\n const fitsProviderLimits = (quote: Quote): boolean => {\n const provider = providerByCode.get(quote.provider);\n const limit = provider?.limits?.fiat?.[fiat]?.[quote.quote.paymentMethod];\n if (!limit) {\n // No published limits for this provider/payment method: treat as\n // eligible and let the provider enforce limits at checkout.\n return true;\n }\n return amount >= limit.minAmount && amount <= limit.maxAmount;\n };\n\n const candidates = response.success.filter(\n (quote) => isAllowedProvider(quote) && fitsProviderLimits(quote),\n );\n if (candidates.length === 0) {\n return undefined;\n }\n\n const candidateByCode = new Map(\n candidates.map((quote) => [quote.provider, quote]),\n );\n\n const pickBySortOrder = (sortBy: QuoteSortBy): Quote | undefined => {\n const order = response.sorted.find(\n (entry) => entry.sortBy === sortBy,\n )?.ids;\n if (!order) {\n return undefined;\n }\n for (const providerId of order) {\n const match = candidateByCode.get(providerId);\n if (match) {\n return match;\n }\n }\n return undefined;\n };\n\n // Reliability first, then price, then the first surviving candidate.\n return (\n pickBySortOrder('reliability') ??\n pickBySortOrder('price') ??\n candidates[0]\n );\n }\n\n /**\n * Returns the region's providers that support the given asset, plus the full\n * region provider list. Uses cached providers only when the request targets\n * the current region; otherwise fetches for the requested region, since\n * `getProviders` does not persist results for a non-current region. Does not\n * mutate state.\n *\n * @param options - The options.\n * @param options.assetId - CAIP-19 asset type identifier to resolve for.\n * @param options.region - Region to resolve providers for.\n * @returns The supporting providers and the full region provider list.\n */\n async #getSupportingProvidersForRegion({\n assetId,\n region,\n }: {\n assetId: string;\n region: string;\n }): Promise<{ supporting: Provider[]; all: Provider[] }> {\n const normalizedRegion = region.toLowerCase().trim();\n\n let providers: Provider[];\n if (\n this.#isRegionCurrent(normalizedRegion) &&\n this.state.providers.data.length > 0\n ) {\n providers = this.state.providers.data;\n } else {\n ({ providers } = await this.getProviders(normalizedRegion));\n }\n\n // Case-insensitive CAIP-19 matching is shared with headless-buy consumers\n // via `getProvidersServingAsset`, so the controller and the UI region gate\n // cannot disagree about which providers serve the asset.\n const supporting = getProvidersServingAsset(providers, assetId);\n\n return { supporting, all: providers };\n }\n\n /**\n * Filters an explicitly-requested provider ID list down to those that support\n * the asset in the region. Used for headless-buy gating so an explicitly\n * passed provider that cannot serve the region/asset yields no providers\n * rather than being trusted blindly.\n *\n * @param options - The options.\n * @param options.providerIds - Explicitly requested provider IDs.\n * @param options.assetId - CAIP-19 asset type identifier to resolve for.\n * @param options.region - Region to resolve providers for.\n * @returns The subset of `providerIds` supporting the asset in the region.\n */\n async #filterProviderIdsBySupport({\n providerIds,\n assetId,\n region,\n }: {\n providerIds: string[];\n assetId: string;\n region: string;\n }): Promise<string[]> {\n const { supporting } = await this.#getSupportingProvidersForRegion({\n assetId,\n region,\n });\n const supportingIds = new Set(supporting.map((provider) => provider.id));\n return providerIds.filter((id) => supportingIds.has(id));\n }\n\n /**\n * Resolves the provider IDs to use for a single quote request, scoped to the\n * given asset and region. Does not mutate `providers.selected` or any other\n * state.\n *\n * Resolves against the region's supporting providers using this precedence:\n * 1. The currently selected provider, if it is in the supporting set.\n * 2. The first preferred provider that supports the asset, where the\n * preference is taken from `preferredProviderIds` when supplied, otherwise\n * derived from the user's completed-order history (most recent first).\n * This takes priority over Transak Native to preserve an existing KYC\n * relationship.\n * 3. A native provider (e.g. Transak Native).\n * 4. The first supporting provider — unless `restrictToKnownOrNative` is set, in\n * which case no further provider is introduced and nothing is returned.\n *\n * When `restrictToKnownOrNative` is unset and no provider supports the asset, falls\n * back to all known provider IDs so the request behaves as if no\n * auto-selection occurred.\n *\n * @param options - The options.\n * @param options.assetId - CAIP-19 asset type identifier to resolve for.\n * @param options.region - Region to resolve providers for.\n * @param options.preferredProviderIds - Provider IDs to prefer, in order.\n * @param options.restrictToKnownOrNative - When true, resolve only a native provider\n * (or no providers when none supports the asset).\n * @returns Provider IDs for this request only.\n */\n async #resolveProviderIdsForQuote({\n assetId,\n region,\n preferredProviderIds,\n restrictToKnownOrNative,\n }: {\n assetId: string;\n region: string;\n preferredProviderIds?: string[];\n restrictToKnownOrNative?: boolean;\n }): Promise<string[]> {\n const { supporting, all } = await this.#getSupportingProvidersForRegion({\n assetId,\n region,\n });\n\n // When not restricted and nothing supports the asset, behave as if no\n // auto-selection occurred (quote against all known providers).\n if (!restrictToKnownOrNative && supporting.length === 0) {\n return all.map((provider) => provider.id);\n }\n\n // 1. The currently selected provider, if it supports the asset.\n const { selected } = this.state.providers;\n if (\n selected &&\n supporting.some((provider) => provider.id === selected.id)\n ) {\n return [selected.id];\n }\n\n // 2. A provider the user has transacted with before — from\n // `preferredProviderIds` when supplied, otherwise completed-order\n // history. Takes priority over Transak Native to preserve an existing\n // KYC relationship and avoid churn.\n const preferred =\n preferredProviderIds ?? this.#getPreferredProviderIdsFromOrders();\n\n for (const preferredId of preferred) {\n const match = supporting.find((provider) => provider.id === preferredId);\n if (match) {\n return [match.id];\n }\n }\n\n // 3. A native provider (e.g. Transak Native).\n const nativeProvider = supporting.find(\n (provider) => provider.type === 'native',\n );\n if (nativeProvider) {\n return [nativeProvider.id];\n }\n\n // 4. Fallback. Under headless gating, introduce no other provider — return\n // nothing so the caller surfaces an \"unavailable\" state. Otherwise the\n // aggregator and all other providers are treated equally: first wins.\n if (restrictToKnownOrNative) {\n return [];\n }\n return [supporting[0].id];\n }\n\n /**\n * Derives an ordered list of provider IDs from the user's completed-order\n * history, most recently completed first, with duplicates removed.\n *\n * Reads only this controller's own normalized order state, so it carries no\n * dependency on any client-specific order representation.\n *\n * @returns Provider IDs ordered by most recent completed order.\n */\n #getPreferredProviderIdsFromOrders(): string[] {\n const orderedIds: string[] = [];\n\n const completedOrders = this.state.orders\n .filter(\n (order) =>\n order.status === RampsOrderStatus.Completed && order.provider?.id,\n )\n .sort((orderA, orderB) => orderB.createdAt - orderA.createdAt);\n\n for (const order of completedOrders) {\n const id = order.provider?.id;\n if (id && !orderedIds.includes(id)) {\n orderedIds.push(id);\n }\n }\n\n return orderedIds;\n }\n\n // === ORDER MANAGEMENT ===\n\n /**\n * Adds or updates a V2 order in controller state.\n * If an order with the same internal order code already exists, the incoming\n * fields are merged on top of the existing order so that fields not present\n * in the update (e.g. paymentDetails from the Transak API) are preserved.\n *\n * @param order - The RampsOrder to add or update.\n */\n addOrder(order: RampsOrder): void {\n const internalOrderCode = getInternalOrderCode(order);\n const healedOrder = {\n ...order,\n providerOrderId: internalOrderCode,\n };\n\n this.update((state) => {\n const idx = state.orders.findIndex(\n (existing) => getInternalOrderCode(existing) === internalOrderCode,\n );\n if (idx === -1) {\n state.orders.push(healedOrder as Draft<RampsOrder>);\n } else {\n state.orders[idx] = {\n ...state.orders[idx],\n ...healedOrder,\n } as Draft<RampsOrder>;\n }\n });\n }\n\n /**\n * Removes a V2 order from controller state by providerOrderId.\n *\n * @param providerOrderId - The provider order ID to remove.\n */\n removeOrder(providerOrderId: string): void {\n this.update((state) => {\n state.orders = state.orders.filter(\n (order) => order.providerOrderId !== providerOrderId,\n );\n });\n\n this.#orderPollingMeta.delete(providerOrderId);\n }\n\n /**\n * Refreshes a single order via the V2 API and updates it in state.\n * Publishes orderStatusChanged if the status transitioned.\n *\n * @param order - The order to refresh (needs provider and providerOrderId).\n */\n async #refreshOrder(order: RampsOrder): Promise<void> {\n const providerCode = order.provider?.id ?? '';\n if (!providerCode || !order.providerOrderId || !order.walletAddress) {\n return;\n }\n\n const previousStatus = order.status;\n\n try {\n const updatedOrder = await this.getOrder(\n providerCode,\n order.providerOrderId,\n order.walletAddress,\n );\n\n const meta = this.#orderPollingMeta.get(order.providerOrderId) ?? {\n lastTimeFetched: 0,\n errorCount: 0,\n };\n\n if (updatedOrder.status === RampsOrderStatus.Unknown) {\n meta.errorCount = Math.min(meta.errorCount + 1, MAX_ERROR_COUNT);\n } else {\n meta.errorCount = 0;\n }\n\n meta.lastTimeFetched = Date.now();\n this.#orderPollingMeta.set(order.providerOrderId, meta);\n\n if (\n previousStatus !== updatedOrder.status &&\n previousStatus !== undefined\n ) {\n this.messenger.publish('RampsController:orderStatusChanged', {\n order: updatedOrder,\n previousStatus,\n });\n }\n\n if (TERMINAL_ORDER_STATUSES.has(updatedOrder.status)) {\n this.#orderPollingMeta.delete(order.providerOrderId);\n }\n } catch {\n const meta = this.#orderPollingMeta.get(order.providerOrderId) ?? {\n lastTimeFetched: 0,\n errorCount: 0,\n };\n meta.errorCount = Math.min(meta.errorCount + 1, MAX_ERROR_COUNT);\n meta.lastTimeFetched = Date.now();\n this.#orderPollingMeta.set(order.providerOrderId, meta);\n }\n }\n\n /**\n * Starts polling all pending V2 orders at a fixed interval.\n * Each poll cycle iterates orders with non-terminal statuses,\n * respects pollingSecondsMinimum and backoff from error count.\n */\n startOrderPolling(): void {\n if (this.#orderPollingTimer) {\n return;\n }\n\n this.#orderPollingTimer = setInterval(() => {\n this.#pollPendingOrders().catch(() => undefined);\n }, DEFAULT_POLLING_INTERVAL_MS);\n\n this.#pollPendingOrders().catch(() => undefined);\n }\n\n /**\n * Stops order polling and clears the interval.\n */\n stopOrderPolling(): void {\n if (this.#orderPollingTimer) {\n clearInterval(this.#orderPollingTimer);\n this.#orderPollingTimer = null;\n }\n }\n\n async #pollPendingOrders(): Promise<void> {\n if (this.#isPolling) {\n return;\n }\n this.#isPolling = true;\n try {\n const pendingOrders = this.state.orders.filter((order) =>\n PENDING_ORDER_STATUSES.has(order.status),\n );\n\n const now = Date.now();\n\n await Promise.allSettled(\n pendingOrders.map(async (order) => {\n const meta = this.#orderPollingMeta.get(order.providerOrderId);\n\n if (meta) {\n const backoffMs =\n meta.errorCount > 0\n ? Math.min(\n DEFAULT_POLLING_INTERVAL_MS *\n Math.pow(2, meta.errorCount - 1),\n 5 * 60 * 1000,\n )\n : 0;\n\n const pollingMinMs = (order.pollingSecondsMinimum ?? 0) * 1000;\n const minWait = Math.max(backoffMs, pollingMinMs);\n\n if (now - meta.lastTimeFetched < minWait) {\n return;\n }\n }\n\n await this.#refreshOrder(order);\n }),\n );\n } finally {\n this.#isPolling = false;\n }\n }\n\n /**\n * Cleans up controller resources.\n * Should be called when the controller is no longer needed.\n */\n override destroy(): void {\n this.stopOrderPolling();\n super.destroy();\n }\n\n /**\n * Fetches the widget data from a quote for redirect providers.\n * Makes a request to the buyURL endpoint via the RampsService to get the\n * actual provider widget URL and optional order ID for polling.\n *\n * @param quote - The quote to fetch the widget URL from.\n * @returns Promise resolving to the full BuyWidget (url, browser, orderId), or null if not available (missing buyURL or empty url in response).\n * @throws Rethrows errors from the RampsService (e.g. HttpError, network failures) so clients can react to fetch failures.\n */\n async getBuyWidgetData(quote: Quote): Promise<BuyWidget | null> {\n const buyUrl = quote.quote?.buyURL;\n if (!buyUrl) {\n return null;\n }\n\n const buyWidget = await this.messenger.call(\n 'RampsService:getBuyWidgetUrl',\n buyUrl,\n );\n if (!buyWidget?.url) {\n return null;\n }\n return buyWidget;\n }\n\n /**\n * Registers an order ID for polling until the order is created or resolved.\n * Adds a minimal stub order to controller state; the existing order polling\n * will fetch the full order when the provider has created it.\n *\n * @param params - Object containing order identifiers and wallet info.\n * @param params.orderId - Full order ID (e.g. \"/providers/paypal/orders/abc123\") or order code.\n * @param params.providerCode - Canonical provider code (e.g. \"paypal\", \"transak\").\n * @param params.walletAddress - Wallet address for the order.\n * @param params.chainId - Chain ID for the order (decimal, hex, or CAIP-2). Must be non-empty.\n */\n addPrecreatedOrder(params: {\n orderId: string;\n providerCode: string;\n walletAddress: string;\n chainId: string;\n }): void {\n const { orderId, providerCode, walletAddress, chainId } = params;\n\n const orderCode = getInternalOrderCode(orderId);\n if (!orderCode?.trim()) {\n return;\n }\n if (!chainId.trim()) {\n return;\n }\n const stubOrder: RampsOrder = {\n providerOrderId: orderCode,\n provider: {\n id: providerCode,\n name: '',\n environmentType: '',\n description: '',\n hqAddress: '',\n links: [],\n logos: { light: '', dark: '', height: 0, width: 0 },\n },\n walletAddress,\n status: RampsOrderStatus.Precreated,\n orderType: 'buy',\n createdAt: Date.now(),\n isOnlyLink: false,\n success: false,\n cryptoAmount: 0,\n fiatAmount: 0,\n providerOrderLink: '',\n totalFeesFiat: 0,\n txHash: '',\n network: { chainId, name: '' },\n canBeUpdated: true,\n idHasExpired: false,\n excludeFromPurchases: false,\n timeDescriptionPending: '',\n };\n\n this.addOrder(stubOrder);\n }\n\n /**\n * Fetches an order from the unified V2 API endpoint.\n * Returns a normalized RampsOrder for all provider types (aggregator and native).\n *\n * @param providerCode - The provider code (e.g., \"transak\", \"transak-native\", \"moonpay\").\n * @param orderCode - The order identifier.\n * @param wallet - The wallet address associated with the order.\n * @returns The unified order data.\n */\n async getOrder(\n providerCode: string,\n orderCode: string,\n wallet: string,\n ): Promise<RampsOrder> {\n const order = await this.messenger.call(\n 'RampsService:getOrder',\n providerCode,\n orderCode,\n wallet,\n );\n\n const healedWalletAddress = order.walletAddress || wallet;\n const internalOrderCode = getInternalOrderCode({\n id: order.id,\n providerOrderId: orderCode,\n });\n const healedOrder = {\n ...order,\n walletAddress: healedWalletAddress,\n providerOrderId: internalOrderCode,\n };\n\n this.update((state) => {\n const idx = state.orders.findIndex(\n (existing: RampsOrder) =>\n getInternalOrderCode(existing) === internalOrderCode,\n );\n if (idx === -1) {\n state.orders.push(healedOrder as Draft<RampsOrder>);\n } else {\n state.orders[idx] = {\n ...state.orders[idx],\n ...healedOrder,\n } as Draft<RampsOrder>;\n }\n });\n\n return healedOrder;\n }\n\n /**\n * Extracts an order from a provider callback URL.\n * Sends the callback URL to the V2 backend for provider-specific parsing,\n * then fetches the full order. This is the V2 equivalent of the aggregator\n * SDK's `getOrderFromCallback`.\n *\n * @param providerCode - The provider code (e.g., \"transak\", \"moonpay\").\n * @param callbackUrl - The full callback URL the provider redirected to.\n * @param wallet - The wallet address associated with the order.\n * @returns The unified order data.\n */\n async getOrderFromCallback(\n providerCode: string,\n callbackUrl: string,\n wallet: string,\n ): Promise<RampsOrder> {\n const order = await this.messenger.call(\n 'RampsService:getOrderFromCallback',\n providerCode,\n callbackUrl,\n wallet,\n );\n\n return order;\n }\n\n // === TRANSAK METHODS ===\n //\n // Auth state is managed at two levels:\n // - TransakService stores the access token (needed for API calls)\n // - RampsController stores isAuthenticated (needed for UI state)\n // Both are kept in sync by the controller methods below.\n\n /**\n * Checks whether an error is a 401 HTTP error (expired/missing token) and,\n * if so, marks the Transak session as unauthenticated so the UI stays in\n * sync with the cleared token inside TransakService.\n *\n * @param error - The caught error to inspect.\n */\n #syncTransakAuthOnError(error: unknown): void {\n if (hasHttpStatus(error) && error.httpStatus === 401) {\n this.transakSetAuthenticated(false);\n }\n }\n\n #getNormalizedTransakError(\n error: unknown,\n options: { syncAuth?: boolean } = {},\n ): NormalizedRampsError {\n if (options.syncAuth) {\n this.#syncTransakAuthOnError(error);\n }\n\n return getNormalizedRampsError(error);\n }\n\n /**\n * Sets the Transak API key used for all Transak API requests.\n *\n * @param apiKey - The Transak API key.\n */\n transakSetApiKey(apiKey: string): void {\n this.messenger.call('TransakService:setApiKey', apiKey);\n }\n\n /**\n * Sets the Transak access token and marks the user as authenticated.\n *\n * @param token - The access token received from Transak auth.\n */\n transakSetAccessToken(token: TransakAccessToken): void {\n this.messenger.call('TransakService:setAccessToken', token);\n this.transakSetAuthenticated(true);\n }\n\n /**\n * Clears the Transak access token and marks the user as unauthenticated.\n */\n transakClearAccessToken(): void {\n this.messenger.call('TransakService:clearAccessToken');\n this.transakSetAuthenticated(false);\n }\n\n /**\n * Updates the Transak authentication flag in controller state.\n *\n * @param isAuthenticated - Whether the user is authenticated with Transak.\n */\n transakSetAuthenticated(isAuthenticated: boolean): void {\n this.update((state) => {\n state.nativeProviders.transak.isAuthenticated = isAuthenticated;\n });\n }\n\n /**\n * Resets all Transak state back to defaults (unauthenticated, no data).\n */\n transakResetState(): void {\n this.messenger.call('TransakService:clearAccessToken');\n this.update((state) => {\n state.nativeProviders.transak =\n getDefaultRampsControllerState().nativeProviders.transak;\n });\n }\n\n /**\n * Sends a one-time password to the user's email for Transak authentication.\n *\n * @param email - The user's email address.\n * @returns The OTP response containing a state token for verification.\n */\n async transakSendUserOtp(email: string): Promise<{\n isTncAccepted: boolean;\n stateToken: string;\n email: string;\n expiresIn: number;\n }> {\n try {\n return await this.messenger.call('TransakService:sendUserOtp', email);\n } catch (error) {\n throw this.#getNormalizedTransakError(error).normalizedError;\n }\n }\n\n /**\n * Verifies a one-time password and authenticates the user with Transak.\n * Updates the controller's authentication state on success.\n *\n * @param email - The user's email address.\n * @param verificationCode - The OTP code entered by the user.\n * @param stateToken - The state token from the sendUserOtp response.\n * @returns The access token for subsequent authenticated requests.\n */\n async transakVerifyUserOtp(\n email: string,\n verificationCode: string,\n stateToken: string,\n ): Promise<TransakAccessToken> {\n try {\n const token = await this.messenger.call(\n 'TransakService:verifyUserOtp',\n email,\n verificationCode,\n stateToken,\n );\n this.transakSetAuthenticated(true);\n return token;\n } catch (error) {\n throw this.#getNormalizedTransakError(error).normalizedError;\n }\n }\n\n /**\n * Logs the user out of Transak. Clears authentication state and user details\n * regardless of whether the API call succeeds or fails.\n *\n * @returns A message indicating the logout result.\n */\n async transakLogout(): Promise<string> {\n try {\n return await this.messenger.call('TransakService:logout');\n } catch (error) {\n throw this.#getNormalizedTransakError(error).normalizedError;\n } finally {\n this.transakClearAccessToken();\n this.update((state) => {\n state.nativeProviders.transak.userDetails.data = null;\n });\n }\n }\n\n /**\n * Fetches the authenticated user's details from Transak.\n * Updates the userDetails resource state with loading/success/error states.\n *\n * @returns The user's profile and KYC details.\n */\n async transakGetUserDetails(): Promise<TransakUserDetails> {\n this.update((state) => {\n state.nativeProviders.transak.userDetails.isLoading = true;\n state.nativeProviders.transak.userDetails.error = null;\n delete state.nativeProviders.transak.userDetails.errorKey;\n });\n try {\n const details = await this.messenger.call(\n 'TransakService:getUserDetails',\n );\n this.update((state) => {\n state.nativeProviders.transak.userDetails.data = details;\n state.nativeProviders.transak.userDetails.isLoading = false;\n });\n return details;\n } catch (error) {\n const { errorInfo, normalizedError } = this.#getNormalizedTransakError(\n error,\n {\n syncAuth: true,\n },\n );\n this.update((state) => {\n state.nativeProviders.transak.userDetails.isLoading = false;\n state.nativeProviders.transak.userDetails.error = errorInfo.message;\n state.nativeProviders.transak.userDetails.errorKey = errorInfo.errorKey;\n });\n throw normalizedError;\n }\n }\n\n /**\n * Fetches a buy quote from Transak for the given parameters.\n * Updates the buyQuote resource state with loading/success/error states.\n *\n * @param fiatCurrency - The fiat currency code (e.g., \"USD\").\n * @param cryptoCurrency - The cryptocurrency identifier.\n * @param network - The blockchain network identifier.\n * @param paymentMethod - The payment method identifier.\n * @param fiatAmount - The fiat amount as a string.\n * @returns The buy quote with pricing and fee details.\n */\n async transakGetBuyQuote(\n fiatCurrency: string,\n cryptoCurrency: string,\n network: string,\n paymentMethod: string,\n fiatAmount: string,\n ): Promise<TransakBuyQuote> {\n this.update((state) => {\n state.nativeProviders.transak.buyQuote.isLoading = true;\n state.nativeProviders.transak.buyQuote.error = null;\n delete state.nativeProviders.transak.buyQuote.errorKey;\n });\n try {\n const quote = await this.messenger.call(\n 'TransakService:getBuyQuote',\n fiatCurrency,\n cryptoCurrency,\n network,\n paymentMethod,\n fiatAmount,\n );\n this.update((state) => {\n state.nativeProviders.transak.buyQuote.data = quote;\n state.nativeProviders.transak.buyQuote.isLoading = false;\n });\n return quote;\n } catch (error) {\n const { errorInfo, normalizedError } =\n this.#getNormalizedTransakError(error);\n this.update((state) => {\n state.nativeProviders.transak.buyQuote.isLoading = false;\n state.nativeProviders.transak.buyQuote.error = errorInfo.message;\n state.nativeProviders.transak.buyQuote.errorKey = errorInfo.errorKey;\n });\n throw normalizedError;\n }\n }\n\n /**\n * Fetches the KYC requirement for a given quote.\n * Updates the kycRequirement resource state with loading/success/error states.\n *\n * @param quoteId - The quote ID to check KYC requirements for.\n * @returns The KYC requirement status and whether the user can place an order.\n */\n async transakGetKycRequirement(\n quoteId: string,\n ): Promise<TransakKycRequirement> {\n this.update((state) => {\n state.nativeProviders.transak.kycRequirement.isLoading = true;\n state.nativeProviders.transak.kycRequirement.error = null;\n delete state.nativeProviders.transak.kycRequirement.errorKey;\n });\n try {\n const requirement = await this.messenger.call(\n 'TransakService:getKycRequirement',\n quoteId,\n );\n this.update((state) => {\n state.nativeProviders.transak.kycRequirement.data = requirement;\n state.nativeProviders.transak.kycRequirement.isLoading = false;\n });\n return requirement;\n } catch (error) {\n const { errorInfo, normalizedError } = this.#getNormalizedTransakError(\n error,\n {\n syncAuth: true,\n },\n );\n this.update((state) => {\n state.nativeProviders.transak.kycRequirement.isLoading = false;\n state.nativeProviders.transak.kycRequirement.error = errorInfo.message;\n state.nativeProviders.transak.kycRequirement.errorKey =\n errorInfo.errorKey;\n });\n throw normalizedError;\n }\n }\n\n /**\n * Fetches additional KYC requirements (e.g., ID proof, address proof) for a quote.\n *\n * @param quoteId - The quote ID to check additional requirements for.\n * @returns The list of additional forms required.\n */\n async transakGetAdditionalRequirements(\n quoteId: string,\n ): Promise<TransakAdditionalRequirementsResponse> {\n try {\n return await this.messenger.call(\n 'TransakService:getAdditionalRequirements',\n quoteId,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Creates a new order on Transak. If an existing order conflicts (HTTP 409),\n * active orders are cancelled and the creation is retried.\n *\n * @param quoteId - The quote ID to create an order from.\n * @param walletAddress - The destination wallet address.\n * @param paymentMethodId - The payment method to use.\n * @returns The created deposit order.\n */\n async transakCreateOrder(\n quoteId: string,\n walletAddress: string,\n paymentMethodId: string,\n ): Promise<TransakDepositOrder> {\n try {\n return await this.messenger.call(\n 'TransakService:createOrder',\n quoteId,\n walletAddress,\n paymentMethodId,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Fetches an existing order from Transak by order ID.\n *\n * @param orderId - The order ID (deposit format or raw Transak format).\n * @param wallet - The wallet address associated with the order.\n * @param paymentDetails - Optional payment details to attach to the order.\n * @returns The deposit order details.\n */\n async transakGetOrder(\n orderId: string,\n wallet: string,\n paymentDetails?: TransakOrderPaymentMethod[],\n ): Promise<TransakDepositOrder> {\n try {\n return await this.messenger.call(\n 'TransakService:getOrder',\n orderId,\n wallet,\n paymentDetails,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error).normalizedError;\n }\n }\n\n /**\n * Fetches the user's spending limits for a given currency and payment method.\n *\n * @param fiatCurrency - The fiat currency code.\n * @param paymentMethod - The payment method identifier.\n * @param kycType - The KYC level type.\n * @returns The user's limits, spending, and remaining amounts.\n */\n async transakGetUserLimits(\n fiatCurrency: string,\n paymentMethod: string,\n kycType: string,\n ): Promise<TransakUserLimits> {\n try {\n return await this.messenger.call(\n 'TransakService:getUserLimits',\n fiatCurrency,\n paymentMethod,\n kycType,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Requests a one-time token (OTT) for the Transak payment widget.\n *\n * @returns The OTT response containing the token.\n */\n async transakRequestOtt(): Promise<TransakOttResponse> {\n try {\n return await this.messenger.call('TransakService:requestOtt');\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Generates a URL for the Transak payment widget with pre-filled parameters.\n *\n * @param ottToken - The one-time token for widget authentication.\n * @param quote - The buy quote to pre-fill in the widget.\n * @param walletAddress - The destination wallet address.\n * @param extraParams - Optional additional URL parameters.\n * @returns The fully constructed widget URL string.\n */\n transakGeneratePaymentWidgetUrl(\n ottToken: string,\n quote: TransakBuyQuote,\n walletAddress: string,\n extraParams?: Record<string, string>,\n ): string {\n return this.messenger.call(\n 'TransakService:generatePaymentWidgetUrl',\n ottToken,\n quote,\n walletAddress,\n extraParams,\n );\n }\n\n /**\n * Creates a Transak payment widget URL via the ramps API proxy, which\n * injects the partner API key server-side. Replaces the OTT flow\n * ({@link transakRequestOtt} + {@link transakGeneratePaymentWidgetUrl}).\n *\n * @param quote - The buy quote to pre-fill in the widget.\n * @param walletAddress - The destination wallet address.\n * @param extraParams - Optional additional widget parameters (e.g. theming).\n * @returns The single-use widget URL.\n */\n async transakCreateWidgetUrl(\n quote: TransakBuyQuote,\n walletAddress: string,\n extraParams?: Record<string, string>,\n ): Promise<string> {\n try {\n return await this.messenger.call(\n 'TransakService:createWidgetUrl',\n quote,\n walletAddress,\n extraParams,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Submits the user's purpose of usage form for KYC compliance.\n *\n * @param purpose - Array of purpose strings selected by the user.\n * @returns A promise that resolves when the form is submitted.\n */\n async transakSubmitPurposeOfUsageForm(purpose: string[]): Promise<void> {\n try {\n return await this.messenger.call(\n 'TransakService:submitPurposeOfUsageForm',\n purpose,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Updates the user's personal or address details on Transak.\n *\n * @param data - The user data fields to update.\n * @returns The API response data.\n */\n async transakPatchUser(data: PatchUserRequestBody): Promise<unknown> {\n try {\n return await this.messenger.call('TransakService:patchUser', data);\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Submits the user's SSN for identity verification.\n *\n * @param ssn - The Social Security Number.\n * @param quoteId - The quote ID associated with the order requiring SSN.\n * @returns The API response data.\n */\n async transakSubmitSsnDetails(\n ssn: string,\n quoteId: string,\n ): Promise<unknown> {\n try {\n return await this.messenger.call(\n 'TransakService:submitSsnDetails',\n ssn,\n quoteId,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Confirms payment for an order after the user has completed payment.\n *\n * @param orderId - The order ID to confirm payment for.\n * @param paymentMethodId - The payment method used.\n * @returns Whether the payment confirmation was successful.\n */\n async transakConfirmPayment(\n orderId: string,\n paymentMethodId: string,\n ): Promise<{ success: boolean }> {\n try {\n return await this.messenger.call(\n 'TransakService:confirmPayment',\n orderId,\n paymentMethodId,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Translates generic ramps identifiers to Transak-specific identifiers.\n *\n * @param request - The translation request with optional identifiers to translate.\n * @returns The translated Transak-specific identifiers.\n */\n async transakGetTranslation(\n request: TransakTranslationRequest,\n ): Promise<TransakQuoteTranslation> {\n try {\n return await this.messenger.call(\n 'TransakService:getTranslation',\n request,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error).normalizedError;\n }\n }\n\n /**\n * Checks the status of an ID proof submission for KYC.\n *\n * @param workFlowRunId - The workflow run ID to check status for.\n * @returns The current ID proof status.\n */\n async transakGetIdProofStatus(\n workFlowRunId: string,\n ): Promise<TransakIdProofStatus> {\n try {\n return await this.messenger.call(\n 'TransakService:getIdProofStatus',\n workFlowRunId,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Cancels a specific Transak order.\n *\n * @param depositOrderId - The deposit order ID to cancel.\n * @returns A promise that resolves when the order is cancelled.\n */\n async transakCancelOrder(depositOrderId: string): Promise<void> {\n try {\n return await this.messenger.call(\n 'TransakService:cancelOrder',\n depositOrderId,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Cancels all active Transak orders. Individual cancellation failures\n * are collected and returned rather than thrown.\n *\n * @returns An array of errors from any failed cancellations (empty if all succeeded).\n */\n async transakCancelAllActiveOrders(): Promise<Error[]> {\n try {\n return await this.messenger.call('TransakService:cancelAllActiveOrders');\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Fetches all active Transak orders for the authenticated user.\n *\n * @returns The list of active orders.\n */\n async transakGetActiveOrders(): Promise<TransakOrder[]> {\n try {\n return await this.messenger.call('TransakService:getActiveOrders');\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"RampsController.mjs","sourceRoot":"","sources":["../src/RampsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,mCAAmC;AAMhE,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,EAC7B,2BAA2B,EAC5B,2BAA0B;AAC3B,OAAO,EACL,sBAAsB,EACtB,uBAAuB,EACxB,0BAAyB;AAC1B,OAAO,EACL,uBAAuB,EACvB,iBAAiB,EAClB,iCAAgC;AACjC,OAAO,EACL,wBAAwB,EACxB,qBAAqB,EACrB,mBAAmB,EACpB,mCAAkC;AAGnC,OAAO,EAAE,iBAAiB,EAAE,8BAA6B;AA8BzD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Y,GAAG,CAAC,KAAK,CAAC,qBAAqB,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC;gBAC/D,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;gBAElD,IAAI,GAAG,GAAG,IAAI,CAAC,eAAe,GAAG,OAAO,EAAE,CAAC;oBACzC,OAAO;gBACT,CAAC;YACH,CAAC;YAED,MAAM,uBAAA,IAAI,iEAAc,MAAlB,IAAI,EAAe,KAAK,CAAC,CAAC;QAClC,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,uBAAA,IAAI,8BAAc,KAAK,MAAA,CAAC;IAC1B,CAAC;AACH,CAAC,6FAwLuB,KAAc;IACpC,IAAI,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,UAAU,KAAK,GAAG,EAAE,CAAC;QACrD,IAAI,CAAC,uBAAuB,CAAC,KAAK,CAAC,CAAC;IACtC,CAAC;AACH,CAAC,mGAGC,KAAc,EACd,UAAkC,EAAE;IAEpC,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;QACrB,uBAAA,IAAI,2EAAwB,MAA5B,IAAI,EAAyB,KAAK,CAAC,CAAC;IACtC,CAAC;IAED,OAAO,uBAAuB,CAAC,KAAK,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { BrokenCircuitError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { Json } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport {\n getHeadlessProviderAllowlist,\n isHeadlessAllProvidersEnabled,\n normalizeHeadlessProviderId,\n} from './featureFlags.js';\nimport {\n PENDING_ORDER_STATUSES,\n TERMINAL_ORDER_STATUSES,\n} from './orderStatus.js';\nimport {\n mergePaymentMethodsById,\n pickPaymentMethod,\n} from './paymentMethodMerge.js';\nimport {\n getProvidersServingAsset,\n normalizeRampsAssetId,\n providerServesAsset,\n} from './providerAvailability.js';\nimport type { RampsControllerMethodActions } from './RampsController-method-action-types.js';\nimport type { RampsErrorCode } from './rampsErrorCodes.js';\nimport { RAMPS_ERROR_CODES } from './rampsErrorCodes.js';\nimport type {\n RampsServiceGetDefaultRedirectCallbackUrlAction,\n RampsServiceGetGeolocationAction,\n RampsServiceGetCountriesAction,\n RampsServiceGetTokensAction,\n RampsServiceGetProvidersAction,\n RampsServiceGetPaymentMethodsAction,\n RampsServiceGetQuotesAction,\n RampsServiceGetBuyWidgetUrlAction,\n RampsServiceGetOrderAction,\n RampsServiceGetOrderFromCallbackAction,\n} from './RampsService-method-action-types.js';\nimport type {\n BuyWidget,\n Country,\n TokensResponse,\n Provider,\n State,\n RampAction,\n PaymentMethod,\n PaymentMethodsResponse,\n QuotesResponse,\n Quote,\n QuoteSortBy,\n RampsToken,\n RampsServiceActions,\n RampsOrder,\n ProvidersResponse,\n} from './RampsService.js';\nimport { RampsOrderStatus } from './RampsService.js';\nimport type {\n RequestCache as RequestCacheType,\n RequestState,\n ExecuteRequestOptions,\n PendingRequest,\n ResourceType,\n} from './RequestCache.js';\nimport {\n DEFAULT_REQUEST_CACHE_TTL,\n DEFAULT_REQUEST_CACHE_MAX_SIZE,\n createCacheKey,\n isCacheExpired,\n createLoadingState,\n createSuccessState,\n createErrorState,\n RequestStatus,\n} from './RequestCache.js';\nimport type {\n TransakServiceSetApiKeyAction,\n TransakServiceSetAccessTokenAction,\n TransakServiceClearAccessTokenAction,\n TransakServiceSendUserOtpAction,\n TransakServiceVerifyUserOtpAction,\n TransakServiceLogoutAction,\n TransakServiceGetUserDetailsAction,\n TransakServiceGetBuyQuoteAction,\n TransakServiceGetKycRequirementAction,\n TransakServiceGetAdditionalRequirementsAction,\n TransakServiceCreateOrderAction,\n TransakServiceGetOrderAction,\n TransakServiceGetUserLimitsAction,\n TransakServiceRequestOttAction,\n TransakServiceGeneratePaymentWidgetUrlAction,\n TransakServiceCreateWidgetUrlAction,\n TransakServiceSubmitPurposeOfUsageFormAction,\n TransakServicePatchUserAction,\n TransakServiceSubmitSsnDetailsAction,\n TransakServiceConfirmPaymentAction,\n TransakServiceGetTranslationAction,\n TransakServiceGetIdProofStatusAction,\n TransakServiceCancelOrderAction,\n TransakServiceCancelAllActiveOrdersAction,\n TransakServiceGetActiveOrdersAction,\n} from './TransakService-method-action-types.js';\nimport type {\n TransakAccessToken,\n TransakUserDetails,\n TransakBuyQuote,\n TransakKycRequirement,\n TransakAdditionalRequirementsResponse,\n TransakDepositOrder,\n TransakUserLimits,\n TransakOttResponse,\n TransakQuoteTranslation,\n TransakTranslationRequest,\n TransakIdProofStatus,\n TransakOrderPaymentMethod,\n PatchUserRequestBody,\n TransakOrder,\n} from './TransakService.js';\nimport type { TransakServiceActions } from './TransakService.js';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link RampsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'RampsController';\n\n/**\n * RampsService action types that RampsController calls via the messenger.\n * Any host (e.g. mobile) that creates a RampsController messenger must delegate\n * these actions from the root messenger so the controller can function.\n */\nexport const RAMPS_CONTROLLER_REQUIRED_SERVICE_ACTIONS: readonly (\n | RampsServiceActions['type']\n | TransakServiceActions['type']\n)[] = [\n 'RampsService:getDefaultRedirectCallbackUrl',\n 'RampsService:getGeolocation',\n 'RampsService:getCountries',\n 'RampsService:getTokens',\n 'RampsService:getProviders',\n 'RampsService:getPaymentMethods',\n 'RampsService:getQuotes',\n 'RampsService:getBuyWidgetUrl',\n 'RampsService:getOrder',\n 'RampsService:getOrderFromCallback',\n 'TransakService:setApiKey',\n 'TransakService:setAccessToken',\n 'TransakService:clearAccessToken',\n 'TransakService:sendUserOtp',\n 'TransakService:verifyUserOtp',\n 'TransakService:logout',\n 'TransakService:getUserDetails',\n 'TransakService:getBuyQuote',\n 'TransakService:getKycRequirement',\n 'TransakService:getAdditionalRequirements',\n 'TransakService:createOrder',\n 'TransakService:getOrder',\n 'TransakService:getUserLimits',\n 'TransakService:requestOtt',\n 'TransakService:generatePaymentWidgetUrl',\n 'TransakService:createWidgetUrl',\n 'TransakService:submitPurposeOfUsageForm',\n 'TransakService:patchUser',\n 'TransakService:submitSsnDetails',\n 'TransakService:confirmPayment',\n 'TransakService:getTranslation',\n 'TransakService:getIdProofStatus',\n 'TransakService:cancelOrder',\n 'TransakService:cancelAllActiveOrders',\n 'TransakService:getActiveOrders',\n];\n\n/**\n * Default TTL for quotes requests (15 seconds).\n * Quotes are time-sensitive and should have a shorter cache duration.\n */\nconst DEFAULT_QUOTES_TTL = 15000;\n\nconst CIRCUIT_BREAKER_OPEN_ERROR =\n 'Execution prevented because the circuit breaker is open';\n\ntype ErrorWithMessage = {\n message: string;\n};\n\ntype ErrorWithRampsErrorKey = Error & {\n errorKey?: RampsErrorCode;\n};\n\ntype ErrorWithHttpStatus = Error & {\n httpStatus: number;\n};\n\ntype RampsErrorInfo = {\n errorKey: RampsErrorCode | null;\n message: string;\n};\n\ntype NormalizedRampsError = {\n errorInfo: RampsErrorInfo;\n normalizedError: unknown;\n};\n\nfunction hasStringMessage(error: unknown): error is ErrorWithMessage {\n return (\n typeof error === 'object' &&\n error !== null &&\n typeof (error as { message?: unknown }).message === 'string'\n );\n}\n\nfunction hasHttpStatus(error: unknown): error is ErrorWithHttpStatus {\n return (\n error instanceof Error &&\n typeof (error as { httpStatus?: unknown }).httpStatus === 'number'\n );\n}\n\nfunction getRampsErrorInfo(error: unknown): RampsErrorInfo {\n if (error instanceof BrokenCircuitError && hasStringMessage(error)) {\n return {\n errorKey: RAMPS_ERROR_CODES.CIRCUIT_BREAKER_OPEN,\n message: error.message,\n };\n }\n\n let rawMessage: string | undefined;\n\n if (hasStringMessage(error)) {\n rawMessage = error.message;\n } else if (typeof error === 'string') {\n rawMessage = error;\n }\n\n if (rawMessage?.includes(CIRCUIT_BREAKER_OPEN_ERROR)) {\n return {\n errorKey: RAMPS_ERROR_CODES.CIRCUIT_BREAKER_OPEN,\n message: rawMessage,\n };\n }\n\n return {\n errorKey: null,\n message: rawMessage ?? 'Unknown error',\n };\n}\n\nfunction getNormalizedRampsError(error: unknown): NormalizedRampsError {\n const errorInfo = getRampsErrorInfo(error);\n\n return {\n errorInfo,\n normalizedError: normalizeRampsErrorForRethrow(error, errorInfo),\n };\n}\n\nfunction normalizeRampsErrorForRethrow(\n error: unknown,\n errorInfo: RampsErrorInfo,\n): unknown {\n if (!errorInfo.errorKey) {\n return error;\n }\n\n if (error instanceof Error) {\n (error as ErrorWithRampsErrorKey).errorKey = errorInfo.errorKey;\n return error;\n }\n\n return Object.assign(new Error(errorInfo.message), {\n errorKey: errorInfo.errorKey,\n });\n}\n\n// === STATE ===\n\n/**\n * Represents the user's selected region with full country and state objects.\n */\nexport type UserRegion = {\n /**\n * The country object for the selected region.\n */\n country: Country;\n /**\n * The state object if a state was selected, null if only country was selected.\n */\n state: State | null;\n /**\n * The region code string (e.g., \"us-ut\" or \"fr\") used for API calls.\n */\n regionCode: string;\n};\n\n/**\n * Generic type for resource state that bundles data with loading/error states.\n *\n * @template TData - The type of the resource data\n * @template TSelected - The type of the selected item (defaults to null for resources without selection)\n */\nexport type ResourceState<TData, TSelected = null> = {\n /**\n * The resource data.\n */\n data: TData;\n /**\n * The currently selected item, or null if none selected.\n */\n selected: TSelected;\n /**\n * Whether the resource is currently being fetched.\n */\n isLoading: boolean;\n /**\n * Error message if the fetch failed, or null.\n */\n error: string | null;\n /**\n * Stable error key for client-side localization, if available.\n */\n errorKey?: RampsErrorCode | null;\n};\n\n/**\n * Describes the transak-specific state managed by the RampsController.\n * This state is used by the unified V2 native flow.\n */\nexport type TransakState = {\n isAuthenticated: boolean;\n userDetails: ResourceState<TransakUserDetails | null>;\n buyQuote: ResourceState<TransakBuyQuote | null>;\n kycRequirement: ResourceState<TransakKycRequirement | null>;\n};\n\n/**\n * Describes the state for all native providers managed by the RampsController.\n * Each native provider has its own nested state object.\n */\nexport type NativeProvidersState = {\n transak: TransakState;\n};\n\n/**\n * Response from {@link RampsController.getPaymentMethodsForContext}.\n *\n * Methods are request-eligible for the resolved provider set; they are not a\n * guarantee that every amount will produce a quote (provider fiat limits still\n * apply at quote time).\n */\nexport type PaymentMethodsForContextResponse = {\n /**\n * Deduped payment methods contributed by the resolved provider set.\n */\n methods: PaymentMethod[];\n /**\n * Suggested selection for this request only. Written to controller state only\n * when `updateState` was true on the call.\n */\n selected: PaymentMethod | null;\n /**\n * Provider IDs whose methods were requested (after resolution / allowlist\n * filtering).\n */\n providerIds: string[];\n};\n\n/**\n * Describes the shape of the state object for {@link RampsController}.\n */\nexport type RampsControllerState = {\n /**\n * The user's region (full country and state objects).\n * Initially set via geolocation fetch, but can be manually changed by the user.\n */\n userRegion: UserRegion | null;\n /**\n * Countries resource state with data, loading, and error.\n * Data contains the list of countries available for ramp actions.\n */\n countries: ResourceState<Country[]>;\n /**\n * Providers resource state with data, selected, loading, and error.\n * Data contains the list of providers available for the current region.\n */\n providers: ResourceState<Provider[], Provider | null>;\n /**\n * Tokens resource state with data, selected, loading, and error.\n * Data contains topTokens and allTokens arrays.\n */\n tokens: ResourceState<TokensResponse | null, RampsToken | null>;\n /**\n * Payment methods resource state with data, selected, loading, and error.\n * Data contains payment methods filtered by region, fiat, asset, and provider.\n */\n paymentMethods: ResourceState<PaymentMethod[], PaymentMethod | null>;\n /**\n * Cache of request states, keyed by cache key.\n * This stores loading, success, and error states for API requests.\n */\n requests: RequestCacheType;\n /**\n * State for native providers in the unified V2 flow.\n * Each provider has its own nested state containing authentication,\n * user details, quote, and KYC data.\n */\n nativeProviders: NativeProvidersState;\n /**\n * The controller is the authority for V2 orders — it polls, updates,\n * and persists them.\n */\n orders: RampsOrder[];\n /**\n * Whether the currently selected provider was auto-selected by the system\n * (no order history, no Transak) rather than chosen by the user or derived\n * from order history. When true, the UI should silently switch providers on\n * token conflict instead of showing the \"Token Not Available\" modal.\n */\n providerAutoSelected: boolean;\n};\n\n/**\n * The metadata for each property in {@link RampsControllerState}.\n */\nconst rampsControllerMetadata = {\n userRegion: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n countries: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n providers: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n tokens: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n paymentMethods: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n requests: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: false,\n usedInUi: true,\n },\n nativeProviders: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: false,\n usedInUi: true,\n },\n orders: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n providerAutoSelected: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n} satisfies StateMetadata<RampsControllerState>;\n\n/**\n * Creates a default resource state object.\n *\n * @template TData - The type of the resource data.\n * @template TSelected - The type of the selected item.\n * @param data - The initial data value.\n * @param selected - The initial selected value.\n * @returns A ResourceState object with default loading and error values.\n */\nfunction createDefaultResourceState<TData, TSelected = null>(\n data: TData,\n selected: TSelected = null as TSelected,\n): ResourceState<TData, TSelected> {\n return {\n data,\n selected,\n isLoading: false,\n error: null,\n };\n}\n\n/**\n * Constructs the default {@link RampsController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link RampsController} state.\n */\nexport function getDefaultRampsControllerState(): RampsControllerState {\n return {\n userRegion: null,\n countries: createDefaultResourceState<Country[]>([]),\n providers: createDefaultResourceState<Provider[], Provider | null>(\n [],\n null,\n ),\n tokens: createDefaultResourceState<\n TokensResponse | null,\n RampsToken | null\n >(null, null),\n paymentMethods: createDefaultResourceState<\n PaymentMethod[],\n PaymentMethod | null\n >([], null),\n requests: {},\n nativeProviders: {\n transak: {\n isAuthenticated: false,\n userDetails: createDefaultResourceState<TransakUserDetails | null>(\n null,\n ),\n buyQuote: createDefaultResourceState<TransakBuyQuote | null>(null),\n kycRequirement:\n createDefaultResourceState<TransakKycRequirement | null>(null),\n },\n },\n orders: [],\n providerAutoSelected: false,\n };\n}\n\nconst DEPENDENT_RESOURCE_KEYS = [\n 'providers',\n 'tokens',\n 'paymentMethods',\n] as const;\n\ntype DependentResourceKey = (typeof DEPENDENT_RESOURCE_KEYS)[number];\n\nconst DEPENDENT_RESOURCE_KEYS_SET = new Set<string>(DEPENDENT_RESOURCE_KEYS);\n\nfunction getResourceState<TResourceType extends ResourceType>(\n state: Draft<RampsControllerState>,\n resourceType: TResourceType,\n): Draft<RampsControllerState[TResourceType]> {\n switch (resourceType) {\n case 'countries':\n return state.countries as Draft<RampsControllerState[TResourceType]>;\n case 'providers':\n return state.providers as Draft<RampsControllerState[TResourceType]>;\n case 'tokens':\n return state.tokens as Draft<RampsControllerState[TResourceType]>;\n case 'paymentMethods':\n return state.paymentMethods as Draft<RampsControllerState[TResourceType]>;\n /* istanbul ignore next -- ResourceType is a closed internal union. */\n default:\n throw new Error(`Unsupported resource type: ${resourceType as string}`);\n }\n}\n\nfunction resetResource(\n state: Draft<RampsControllerState>,\n resourceType: DependentResourceKey,\n defaultResource: RampsControllerState[DependentResourceKey],\n): void {\n const resource = getResourceState(state, resourceType);\n resource.data = defaultResource.data;\n resource.selected = defaultResource.selected;\n resource.isLoading = defaultResource.isLoading;\n resource.error = defaultResource.error;\n resource.errorKey = defaultResource.errorKey ?? null;\n}\n\n/**\n * Resets region-dependent resources (userRegion, providers, tokens, paymentMethods).\n * Mutates state in place; use from within controller update() for atomic updates.\n *\n * @param state - The state object to mutate.\n * @param options - Options for the reset.\n * @param options.clearUserRegionData - When true, sets userRegion to null (e.g. for full cleanup).\n */\nfunction resetDependentResources(\n state: Draft<RampsControllerState>,\n options?: { clearUserRegionData?: boolean },\n): void {\n if (options?.clearUserRegionData) {\n state.userRegion = null;\n }\n const defaultState = getDefaultRampsControllerState();\n for (const key of DEPENDENT_RESOURCE_KEYS) {\n resetResource(state, key, defaultState[key]);\n }\n state.providerAutoSelected = false;\n}\n\n// === MESSENGER ===\n\n/**\n * Retrieves the state of the {@link RampsController}.\n */\nexport type RampsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n RampsControllerState\n>;\n\n/**\n * Actions that {@link RampsControllerMessenger} exposes to other consumers.\n */\nexport type RampsControllerActions =\n | RampsControllerGetStateAction\n | RampsControllerMethodActions;\n\n/**\n * Actions from other messengers that {@link RampsController} calls.\n */\ntype AllowedActions =\n | RemoteFeatureFlagControllerGetStateAction\n | RampsServiceGetDefaultRedirectCallbackUrlAction\n | RampsServiceGetGeolocationAction\n | RampsServiceGetCountriesAction\n | RampsServiceGetTokensAction\n | RampsServiceGetProvidersAction\n | RampsServiceGetPaymentMethodsAction\n | RampsServiceGetQuotesAction\n | RampsServiceGetBuyWidgetUrlAction\n | RampsServiceGetOrderAction\n | RampsServiceGetOrderFromCallbackAction\n | TransakServiceSetApiKeyAction\n | TransakServiceSetAccessTokenAction\n | TransakServiceClearAccessTokenAction\n | TransakServiceSendUserOtpAction\n | TransakServiceVerifyUserOtpAction\n | TransakServiceLogoutAction\n | TransakServiceGetUserDetailsAction\n | TransakServiceGetBuyQuoteAction\n | TransakServiceGetKycRequirementAction\n | TransakServiceGetAdditionalRequirementsAction\n | TransakServiceCreateOrderAction\n | TransakServiceGetOrderAction\n | TransakServiceGetUserLimitsAction\n | TransakServiceRequestOttAction\n | TransakServiceGeneratePaymentWidgetUrlAction\n | TransakServiceCreateWidgetUrlAction\n | TransakServiceSubmitPurposeOfUsageFormAction\n | TransakServicePatchUserAction\n | TransakServiceSubmitSsnDetailsAction\n | TransakServiceConfirmPaymentAction\n | TransakServiceGetTranslationAction\n | TransakServiceGetIdProofStatusAction\n | TransakServiceCancelOrderAction\n | TransakServiceCancelAllActiveOrdersAction\n | TransakServiceGetActiveOrdersAction;\n\n/**\n * Published when the state of {@link RampsController} changes.\n */\nexport type RampsControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n RampsControllerState\n>;\n\n/**\n * Published when a V2 order's status transitions.\n * Consumed by mobile's init layer for notifications and analytics.\n */\nexport type RampsControllerOrderStatusChangedEvent = {\n type: `${typeof controllerName}:orderStatusChanged`;\n payload: [{ order: RampsOrder; previousStatus: RampsOrderStatus }];\n};\n\n/**\n * Events that {@link RampsControllerMessenger} exposes to other consumers.\n */\nexport type RampsControllerEvents =\n | RampsControllerStateChangeEvent\n | RampsControllerOrderStatusChangedEvent;\n\n/**\n * Events from other messengers that {@link RampsController} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link RampsController}.\n */\nexport type RampsControllerMessenger = Messenger<\n typeof controllerName,\n RampsControllerActions | AllowedActions,\n RampsControllerEvents | AllowedEvents\n>;\n\n/**\n * Configuration options for the RampsController.\n */\nexport type RampsControllerOptions = {\n /** The messenger suited for this controller. */\n messenger: RampsControllerMessenger;\n /** The desired state with which to initialize this controller. */\n state?: Partial<RampsControllerState>;\n /** Time to live for cached requests in milliseconds. Defaults to 15 minutes. */\n requestCacheTTL?: number;\n /** Maximum number of entries in the request cache. Defaults to 250. */\n requestCacheMaxSize?: number;\n};\n\n// === HELPER FUNCTIONS ===\n\n/**\n * Finds a country and state from a region code string.\n *\n * @param regionCode - The region code (e.g., \"us-ca\" or \"us\").\n * @param countries - Array of countries to search.\n * @returns UserRegion object with country and state, or null if not found.\n */\nfunction findRegionFromCode(\n regionCode: string,\n countries: Country[],\n): UserRegion | null {\n const normalizedCode = regionCode.toLowerCase().trim();\n const parts = normalizedCode.split('-');\n const countryCode = parts[0];\n const stateCode = parts[1];\n\n const country = countries.find((countryItem) => {\n if (countryItem.isoCode?.toLowerCase() === countryCode) {\n return true;\n }\n if (countryItem.id) {\n const id = countryItem.id.toLowerCase();\n if (id.startsWith('/regions/')) {\n const extractedCode = id.replace('/regions/', '').split('/')[0];\n return extractedCode === countryCode;\n }\n return id === countryCode || id.endsWith(`/${countryCode}`);\n }\n return false;\n });\n\n if (!country) {\n return null;\n }\n\n let state: State | null = null;\n if (stateCode && country.states) {\n state =\n country.states.find((stateItem) => {\n if (stateItem.stateId?.toLowerCase() === stateCode) {\n return true;\n }\n if (stateItem.id) {\n const stateId = stateItem.id.toLowerCase();\n if (\n stateId.includes(`-${stateCode}`) ||\n stateId.endsWith(`/${stateCode}`)\n ) {\n return true;\n }\n }\n return false;\n }) ?? null;\n }\n\n return {\n country,\n state,\n regionCode: normalizedCode,\n };\n}\n\n/**\n * Returns the internal MetaMask order code used for state lookups and polling.\n * Prefers the code embedded in the canonical order `id` path over `providerOrderId`,\n * which may contain the provider's native order identifier.\n *\n * @param orderOrId - Order fields or a full order id / order code string.\n * @returns The internal order code.\n */\nexport function getInternalOrderCode(\n orderOrId: Pick<RampsOrder, 'id' | 'providerOrderId'> | string,\n): string {\n if (typeof orderOrId === 'string') {\n return orderOrId.includes('/orders/')\n ? orderOrId.split('/orders/')[1]\n : orderOrId;\n }\n\n const { id, providerOrderId } = orderOrId;\n if (id?.includes('/orders/')) {\n return id.split('/orders/')[1];\n }\n\n return providerOrderId;\n}\n\n// === ORDER POLLING CONSTANTS ===\n\nconst DEFAULT_POLLING_INTERVAL_MS = 30_000;\nconst MAX_ERROR_COUNT = 5;\n\ntype OrderPollingMetadata = {\n lastTimeFetched: number;\n errorCount: number;\n};\n\n// === CONTROLLER DEFINITION ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'executeRequest',\n 'abortRequest',\n 'getRequestState',\n 'setUserRegion',\n 'setSelectedProvider',\n 'setSelectedProviderForAsset',\n 'init',\n 'getCountries',\n 'getTokens',\n 'setSelectedToken',\n 'getProviders',\n 'getPaymentMethods',\n 'getPaymentMethodsForContext',\n 'setSelectedPaymentMethod',\n 'getQuotes',\n 'addOrder',\n 'removeOrder',\n 'startOrderPolling',\n 'stopOrderPolling',\n 'getBuyWidgetData',\n 'addPrecreatedOrder',\n 'getOrder',\n 'getOrderFromCallback',\n 'transakSetApiKey',\n 'transakSetAccessToken',\n 'transakClearAccessToken',\n 'transakSetAuthenticated',\n 'transakResetState',\n 'transakSendUserOtp',\n 'transakVerifyUserOtp',\n 'transakLogout',\n 'transakGetUserDetails',\n 'transakGetBuyQuote',\n 'transakGetKycRequirement',\n 'transakGetAdditionalRequirements',\n 'transakCreateOrder',\n 'transakGetOrder',\n 'transakGetUserLimits',\n 'transakRequestOtt',\n 'transakGeneratePaymentWidgetUrl',\n 'transakCreateWidgetUrl',\n 'transakSubmitPurposeOfUsageForm',\n 'transakPatchUser',\n 'transakSubmitSsnDetails',\n 'transakConfirmPayment',\n 'transakGetTranslation',\n 'transakGetIdProofStatus',\n 'transakCancelOrder',\n 'transakCancelAllActiveOrders',\n 'transakGetActiveOrders',\n] as const;\n\n/**\n * Manages cryptocurrency on/off ramps functionality.\n */\n/**\n * The state fields {@link contextStillMatches} reads, narrowed rather than\n * taking `RampsControllerState`. Callers pass Immer's deep `WritableDraft`, and\n * checking that against the full state type exceeds the type instantiation\n * depth limit on declaration emit (TS2589), even though `tsc --noEmit` accepts\n * it.\n */\ntype ContextGuardState = {\n userRegion: { regionCode?: string } | null;\n tokens: { selected: { assetId: string } | null };\n providers: { selected: { id: string } | null };\n};\n\n/**\n * Whether controller state still describes the context a payment-method\n * request was issued for, so a completed request may write the Buy catalog.\n *\n * Compared at commit time rather than against a snapshot, so an older request\n * that returns after the context moved on is dropped.\n *\n * @param state - Controller state at commit time.\n * @param context - The context the request was issued for.\n * @param context.region - Normalized region code.\n * @param context.assetId - Canonicalized CAIP-19 asset id.\n * @param context.providerId - Trimmed provider id, or an empty string.\n * @returns Whether the write may proceed.\n */\nfunction contextStillMatches(\n state: ContextGuardState,\n context: { region: string; assetId: string; providerId: string },\n): boolean {\n return (\n state.userRegion?.regionCode?.trim().toLowerCase() === context.region &&\n normalizeRampsAssetId(state.tokens.selected?.assetId ?? '') ===\n context.assetId &&\n (state.providers.selected?.id.trim() ?? '') === context.providerId\n );\n}\n\nexport class RampsController extends BaseController<\n typeof controllerName,\n RampsControllerState,\n RampsControllerMessenger\n> {\n /**\n * Default TTL for cached requests.\n */\n readonly #requestCacheTTL: number;\n\n /**\n * Maximum number of entries in the request cache.\n */\n readonly #requestCacheMaxSize: number;\n\n /**\n * Map of pending requests for deduplication.\n * Key is the cache key, value is the pending request with abort controller.\n */\n readonly #pendingRequests: Map<string, PendingRequest> = new Map();\n\n /**\n * Count of in-flight requests per resource type.\n * Used so isLoading is only cleared when the last request for that resource finishes.\n */\n readonly #pendingResourceCount: Map<ResourceType, number> = new Map();\n\n /**\n * Monotonic generation per resource type used to invalidate stale in-flight\n * requests after region/token/provider dependent-resource resets.\n */\n readonly #pendingResourceGeneration: Map<ResourceType, number> = new Map();\n\n readonly #orderPollingMeta: Map<string, OrderPollingMetadata> = new Map();\n\n #orderPollingTimer: ReturnType<typeof setInterval> | null = null;\n\n #isPolling = false;\n\n #initPromise: Promise<void> | null = null;\n\n /**\n * Clears the pending resource count map. Used only in tests to exercise the\n * defensive path when get() returns undefined in the finally block.\n *\n * @internal\n */\n clearPendingResourceCountForTest(): void {\n this.#pendingResourceCount.clear();\n }\n\n #clearPendingResourceCountForDependentResources(): void {\n for (const resourceType of DEPENDENT_RESOURCE_KEYS) {\n this.#pendingResourceCount.delete(resourceType);\n const generation = this.#pendingResourceGeneration.get(resourceType) ?? 0;\n this.#pendingResourceGeneration.set(resourceType, generation + 1);\n }\n }\n\n #abortDependentRequests(): void {\n for (const [cacheKey, pending] of this.#pendingRequests.entries()) {\n if (\n pending.resourceType &&\n DEPENDENT_RESOURCE_KEYS_SET.has(pending.resourceType)\n ) {\n pending.abortController.abort();\n this.#pendingRequests.delete(cacheKey);\n this.#removeRequestState(cacheKey);\n }\n }\n }\n\n /**\n * Constructs a new {@link RampsController}.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this controller.\n * @param args.state - The desired state with which to initialize this\n * controller. Missing properties will be filled in with defaults.\n * @param args.requestCacheTTL - Time to live for cached requests in milliseconds.\n * @param args.requestCacheMaxSize - Maximum number of entries in the request cache.\n */\n constructor({\n messenger,\n state = {},\n requestCacheTTL = DEFAULT_REQUEST_CACHE_TTL,\n requestCacheMaxSize = DEFAULT_REQUEST_CACHE_MAX_SIZE,\n }: RampsControllerOptions) {\n super({\n messenger,\n metadata: rampsControllerMetadata,\n name: controllerName,\n state: {\n ...getDefaultRampsControllerState(),\n ...state,\n // Always reset requests cache on initialization (non-persisted)\n requests: {},\n },\n });\n\n this.#requestCacheTTL = requestCacheTTL;\n this.#requestCacheMaxSize = requestCacheMaxSize;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Resolves the Headless Buy all-providers feature flag: whether widening is\n * enabled, and the provider-id allowlist the widened pick is restricted to\n * (if the flag's object payload carries one).\n *\n * Reads `RemoteFeatureFlagController` state through the messenger on every\n * call, so a remote flag fetch or a local dev override takes effect at\n * runtime without reconstructing the controller. The single read keeps the\n * enabled bit and the allowlist consistent even if the flag changes while a\n * quote request is in flight. Key lookup, local-override merging, and value\n * coercion live in the shared `isHeadlessAllProvidersEnabled` /\n * `getHeadlessProviderAllowlist` helpers so UI consumers resolve the flag\n * identically. Fails closed: when `RemoteFeatureFlagController:getState` is\n * not wired up, quoting stays native-only.\n *\n * @returns The enabled bit and the optional provider-id allowlist.\n */\n #resolveAllProvidersFlag(): {\n enabled: boolean;\n allowlist?: string[];\n } {\n try {\n const remoteFeatureFlagState = this.messenger.call(\n 'RemoteFeatureFlagController:getState',\n );\n return {\n enabled: isHeadlessAllProvidersEnabled(remoteFeatureFlagState),\n allowlist: getHeadlessProviderAllowlist(remoteFeatureFlagState),\n };\n } catch {\n return { enabled: false };\n }\n }\n\n /**\n * Executes a request with caching, deduplication, and at most one in-flight\n * request per resource type.\n *\n * 1. **Same cache key in flight** – If a request with this cache key is\n * already pending, returns that promise (deduplication; no second request).\n *\n * 2. **Cache hit** – If valid, non-expired data exists in state.requests for\n * this key and forceRefresh is not set, returns that data without fetching.\n *\n * 3. **New request** – Creates an AbortController and fires the fetcher.\n * If options.resourceType is set, tags the pending request with that\n * resource type (so #abortDependentRequests can cancel it on region\n * change or cleanup) and ref-counts resource-level loading state.\n * On success or error, updates request state and resource error;\n * in finally, clears resource loading only if this request was not\n * aborted.\n *\n * @param cacheKey - Unique identifier for this request (e.g. from createCacheKey).\n * @param fetcher - Async function that performs the fetch. Receives an AbortSignal\n * that is aborted when this request is superseded by another for the same resource.\n * @param options - Optional forceRefresh, ttl, and resourceType for loading/error state.\n * @returns The result of the request (from cache, joined promise, or fetcher).\n */\n async executeRequest<TResult>(\n cacheKey: string,\n fetcher: (signal: AbortSignal) => Promise<TResult>,\n options?: ExecuteRequestOptions,\n ): Promise<TResult> {\n // Get TTL for verifying cache expiration\n const ttl = options?.ttl ?? this.#requestCacheTTL;\n\n // DEDUPLICATION:\n // Check if a request is already in flight for this cache key\n // If so, return the original promise for that request\n const pending = this.#pendingRequests.get(cacheKey);\n if (pending) {\n return pending.promise as Promise<TResult>;\n }\n\n // CACHE HIT:\n // If cache is not expired, return the cached data\n if (!options?.forceRefresh) {\n const cached = this.state.requests[cacheKey];\n if (cached && !isCacheExpired(cached, ttl)) {\n return cached.data as TResult;\n }\n }\n\n // Create a new abort controller for this request\n // Record the time the request was started\n const abortController = new AbortController();\n const lastFetchedAt = Date.now();\n const { resourceType } = options ?? {};\n const resourceGeneration = resourceType\n ? (this.#pendingResourceGeneration.get(resourceType) ?? 0)\n : undefined;\n\n // Update state to loading\n this.#updateRequestState(cacheKey, createLoadingState());\n\n // Set resource-level loading state (only on cache miss). Ref-count so concurrent\n // requests for the same resource type (different cache keys) keep isLoading true.\n if (resourceType) {\n const count = this.#pendingResourceCount.get(resourceType) ?? 0;\n this.#pendingResourceCount.set(resourceType, count + 1);\n if (count === 0) {\n this.#setResourceLoading(resourceType, true);\n }\n }\n\n // Create the fetch promise\n const promise = (async (): Promise<TResult> => {\n try {\n const data = await fetcher(abortController.signal);\n\n if (abortController.signal.aborted) {\n throw new Error('Request was aborted');\n }\n\n this.#updateRequestState(\n cacheKey,\n createSuccessState(data as Json, lastFetchedAt),\n );\n\n if (resourceType) {\n const isCurrent =\n !options?.isResultCurrent || options.isResultCurrent();\n if (isCurrent) {\n this.#setResourceError(resourceType, null);\n }\n }\n return data;\n } catch (error) {\n if (abortController.signal.aborted) {\n throw error;\n }\n\n const { errorInfo, normalizedError } = getNormalizedRampsError(error);\n this.#updateRequestState(\n cacheKey,\n createErrorState(\n errorInfo.message,\n lastFetchedAt,\n errorInfo.errorKey,\n ),\n );\n if (resourceType) {\n const isCurrent =\n !options?.isResultCurrent || options.isResultCurrent();\n if (isCurrent) {\n this.#setResourceError(resourceType, errorInfo);\n }\n }\n throw normalizedError;\n } finally {\n if (\n this.#pendingRequests.get(cacheKey)?.abortController ===\n abortController\n ) {\n this.#pendingRequests.delete(cacheKey);\n }\n\n // Clear resource-level loading state only when no requests for this resource remain\n if (resourceType && !abortController.signal.aborted) {\n const currentGeneration =\n this.#pendingResourceGeneration.get(resourceType) ?? 0;\n if (currentGeneration === resourceGeneration) {\n const count = this.#pendingResourceCount.get(resourceType) ?? 0;\n const next = Math.max(0, count - 1);\n if (next === 0) {\n this.#pendingResourceCount.delete(resourceType);\n this.#setResourceLoading(resourceType, false);\n } else {\n this.#pendingResourceCount.set(resourceType, next);\n }\n }\n }\n }\n })();\n\n this.#pendingRequests.set(cacheKey, {\n promise,\n abortController,\n resourceType,\n });\n\n return promise;\n }\n\n /**\n * Aborts a pending request if one exists.\n *\n * @param cacheKey - The cache key of the request to abort.\n * @returns True if a request was aborted.\n */\n abortRequest(cacheKey: string): boolean {\n const pending = this.#pendingRequests.get(cacheKey);\n if (pending) {\n pending.abortController.abort();\n this.#pendingRequests.delete(cacheKey);\n this.#removeRequestState(cacheKey);\n return true;\n }\n return false;\n }\n\n /**\n * Mutates state.requests inside update(); cast is centralized here.\n *\n * @param fn - Callback that mutates the requests record.\n */\n #mutateRequests(\n fn: (requests: Record<string, RequestState | undefined>) => void,\n ): void {\n this.update((state) => {\n const requests = state.requests as unknown as Record<\n string,\n RequestState | undefined\n >;\n fn(requests);\n });\n }\n\n #removeRequestState(cacheKey: string): void {\n this.#mutateRequests((requests) => {\n delete requests[cacheKey];\n });\n }\n\n #cleanupState(): void {\n this.#abortDependentRequests();\n this.#clearPendingResourceCountForDependentResources();\n this.update((state) =>\n resetDependentResources(state, { clearUserRegionData: true }),\n );\n }\n\n #requireRegion(): string {\n const regionCode = this.state.userRegion?.regionCode;\n if (!regionCode) {\n throw new Error(\n 'Region is required. Cannot proceed without valid region information.',\n );\n }\n return regionCode;\n }\n\n #isRegionCurrent(normalizedRegion: string): boolean {\n const current = this.state.userRegion?.regionCode;\n return current === undefined || current === normalizedRegion;\n }\n\n #isTokenCurrent(normalizedAssetId: string): boolean {\n const current = this.state.tokens.selected?.assetId ?? '';\n return current === normalizedAssetId;\n }\n\n #isProviderCurrent(normalizedProviderId: string): boolean {\n const current = this.state.providers.selected?.id ?? '';\n return current === normalizedProviderId;\n }\n\n /**\n * Updates a single field (isLoading or error) on a resource state.\n * All resources share the same ResourceState structure, so we use\n * dynamic property access to avoid duplicating switch statements.\n *\n * @param resourceType - The type of resource.\n * @param field - The field to update ('isLoading' or 'error').\n * @param value - The value to set.\n */\n #updateResourceField(\n resourceType: ResourceType,\n field: 'isLoading' | 'error' | 'errorKey',\n value: boolean | string | RampsErrorCode | null,\n ): void {\n this.update((state) => {\n const resource = getResourceState(state, resourceType);\n (resource as Record<string, unknown>)[field] = value;\n });\n }\n\n /**\n * Sets the loading state for a resource type.\n *\n * @param resourceType - The type of resource.\n * @param loading - Whether the resource is loading.\n */\n #setResourceLoading(resourceType: ResourceType, loading: boolean): void {\n this.#updateResourceField(resourceType, 'isLoading', loading);\n }\n\n /**\n * Sets the error state for a resource type.\n *\n * @param resourceType - The type of resource.\n * @param errorInfo - The error info, or null to clear.\n */\n #setResourceError(\n resourceType: ResourceType,\n errorInfo: RampsErrorInfo | null,\n ): void {\n this.update((state) => {\n const resource = getResourceState(state, resourceType);\n resource.error = errorInfo?.message ?? null;\n resource.errorKey = errorInfo?.errorKey ?? null;\n });\n }\n\n /**\n * Gets the state of a specific cached request.\n *\n * @param cacheKey - The cache key to look up.\n * @returns The request state, or undefined if not cached.\n */\n getRequestState(cacheKey: string): RequestState | undefined {\n return this.state.requests[cacheKey];\n }\n\n /**\n * Updates the state for a specific request.\n *\n * @param cacheKey - The cache key.\n * @param requestState - The new state for the request.\n */\n #updateRequestState(cacheKey: string, requestState: RequestState): void {\n const maxSize = this.#requestCacheMaxSize;\n const ttl = this.#requestCacheTTL;\n this.#mutateRequests((requests) => {\n requests[cacheKey] = requestState;\n const keys = Object.keys(requests);\n for (const key of keys) {\n const entry = requests[key];\n if (\n entry?.status === RequestStatus.SUCCESS &&\n isCacheExpired(entry, ttl)\n ) {\n delete requests[key];\n }\n }\n const remainingKeys = Object.keys(requests);\n if (remainingKeys.length > maxSize) {\n const sortedKeys = remainingKeys.sort((a, b) => {\n const aTime = requests[a]?.timestamp ?? 0;\n const bTime = requests[b]?.timestamp ?? 0;\n return aTime - bTime;\n });\n const entriesToRemove = remainingKeys.length - maxSize;\n for (let i = 0; i < entriesToRemove; i++) {\n const keyToRemove = sortedKeys[i];\n if (keyToRemove) {\n delete requests[keyToRemove];\n }\n }\n }\n });\n }\n\n /**\n * Sets the user's region manually (without fetching geolocation).\n * This allows users to override the detected region.\n *\n * @param region - The region code to set (e.g., \"US-CA\").\n * @param options - Options for cache behavior.\n * @returns The user region object.\n */\n async setUserRegion(\n region: string,\n options?: ExecuteRequestOptions,\n ): Promise<UserRegion> {\n const normalizedRegion = region.toLowerCase().trim();\n\n try {\n const countriesData = this.state.countries.data;\n if (!countriesData || countriesData.length === 0) {\n this.#cleanupState();\n throw new Error(\n 'No countries found. Cannot set user region without valid country information.',\n );\n }\n\n const userRegion = findRegionFromCode(normalizedRegion, countriesData);\n\n if (!userRegion) {\n this.#cleanupState();\n throw new Error(\n `Region \"${normalizedRegion}\" not found in countries data. Cannot set user region without valid country information.`,\n );\n }\n\n const regionChanged =\n Boolean(options?.forceRefresh) ||\n normalizedRegion !== this.state.userRegion?.regionCode;\n\n if (regionChanged) {\n // Note: we intentionally do NOT abort in-flight requests here.\n // Aborting causes data loss during rapid region switching (e.g.\n // user taps France → Finland → France quickly). Instead we let\n // old requests complete naturally; isResultCurrent guards in\n // getProviders/getPaymentMethods discard stale results.\n this.#clearPendingResourceCountForDependentResources();\n }\n this.update((state) => {\n if (regionChanged) {\n resetDependentResources(state);\n }\n state.userRegion = userRegion;\n });\n\n return userRegion;\n } catch (error) {\n this.#cleanupState();\n throw error;\n }\n }\n\n /**\n * Sets the user's selected provider.\n *\n * Accepts either a Provider object (stored directly) or a provider ID\n * string (looked up from state). The object form is preferred when the\n * caller already has the full data (e.g. from React Query cache).\n *\n * @param providerOrId - A Provider object, a provider ID string (e.g., \"/providers/moonpay\"), or null to clear.\n * @param options - Optional settings for the selection.\n * @param options.autoSelected - When true, marks the provider as system-guessed\n * (soft selection). The UI will silently auto-switch on token conflict instead\n * of showing the \"Token Not Available\" modal. Defaults to false.\n */\n setSelectedProvider(\n providerOrId: string | Provider | null,\n options?: { autoSelected?: boolean },\n ): void {\n if (providerOrId === null) {\n this.update((state) => {\n state.providers.selected = null;\n state.providerAutoSelected = false;\n });\n return;\n }\n\n this.#requireRegion();\n\n // If a full Provider object is passed, store it directly (avoids\n // depending on state.providers.data being populated).\n if (typeof providerOrId !== 'string') {\n this.update((state) => {\n state.providers.selected = providerOrId;\n state.providerAutoSelected = options?.autoSelected ?? false;\n });\n return;\n }\n\n // ID string: look up from state\n const providers = this.state.providers.data;\n const provider = providers?.find((prov) => prov.id === providerOrId);\n\n if (provider) {\n this.update((state) => {\n state.providers.selected = provider;\n state.providerAutoSelected = options?.autoSelected ?? false;\n });\n }\n }\n\n /**\n * Switches to the first provider in state that serves the given asset,\n * when the currently selected provider does not.\n *\n * This is the controller-level equivalent of UB2's BuildQuote tier-1\n * silent-switch effect and MMPay's `useEnsureCompatibleProvider` hook: it\n * keeps provider-asset compatibility logic in one place rather than\n * duplicating `providerServesAsset` + find-and-switch across multiple UI\n * layers.\n *\n * The compatibility check prefers the current provider's entry in\n * `providers.data` over the `providers.selected` copy, which can be stale\n * once a fresh providers list arrives.\n *\n * No-op when:\n * - `providers.data` is empty (providers not yet loaded)\n * - the currently selected provider already serves the asset\n * - no provider in the list serves the asset (no safe fallback)\n *\n * @param assetId - CAIP-19 asset id of the deposit asset.\n * @param options - Optional settings forwarded to `setSelectedProvider`.\n * @param options.autoSelected - When true, marks the new selection as\n * system-guessed (soft selection). Defaults to true.\n * @returns `true` if the selected provider was changed, `false` otherwise.\n */\n setSelectedProviderForAsset(\n assetId: string,\n options?: { autoSelected?: boolean },\n ): boolean {\n const providers = this.state.providers.data;\n if (!providers?.length) {\n return false;\n }\n\n const selectedId = this.state.providers.selected?.id;\n const currentProvider =\n providers.find((provider) => provider.id === selectedId) ??\n this.state.providers.selected;\n if (currentProvider && providerServesAsset(currentProvider, assetId)) {\n return false;\n }\n\n const compatible = providers.find(\n (provider) =>\n provider.id !== selectedId && providerServesAsset(provider, assetId),\n );\n if (!compatible) {\n return false;\n }\n\n this.setSelectedProvider(compatible, {\n autoSelected: true,\n ...options,\n });\n return true;\n }\n\n /**\n * Initializes the controller by fetching the user's region from geolocation.\n * This should be called once at app startup to set up the initial region.\n *\n * Idempotent: subsequent calls return the same promise unless forceRefresh is set.\n * Force-refetches the countries catalog on startup (bypassing the in-session\n * request cache) so region preset amounts stay current. The catalog is not\n * persisted, so a cold start always re-fetches it regardless. Skips\n * geolocation when userRegion already exists.\n *\n * @param options - Options for cache behavior. forceRefresh bypasses idempotency and re-runs the full flow.\n * @returns Promise that resolves when initialization is complete.\n */\n async init(options?: ExecuteRequestOptions): Promise<void> {\n if (!options?.forceRefresh && this.#initPromise !== null) {\n return this.#initPromise;\n }\n\n if (options?.forceRefresh) {\n this.#initPromise = null;\n }\n\n const initPromise = this.#runInit(options).then(\n () => undefined,\n (error) => {\n if (this.#initPromise === initPromise) {\n this.#initPromise = null;\n }\n throw error;\n },\n );\n this.#initPromise = initPromise;\n return initPromise;\n }\n\n async #runInit(options?: ExecuteRequestOptions): Promise<void> {\n // Force-refetch the catalog on startup so region preset amounts stay\n // current, bypassing the in-session request cache. The catalog is not\n // persisted, so a cold start always re-fetches it regardless.\n await this.getCountries({ ...options, forceRefresh: true });\n\n // Always prefer the user's persisted region. Geolocation is only used to\n // seed the initial value; once the user (or a prior init) has set a region\n // we must respect that choice — even on forceRefresh.\n const persistedRegionCode = this.state.userRegion?.regionCode;\n const regionCode =\n persistedRegionCode ??\n (await this.messenger.call('RampsService:getGeolocation'));\n\n if (!regionCode) {\n throw new Error(\n 'Failed to fetch geolocation. Cannot initialize controller without valid region information.',\n );\n }\n\n // For an already-persisted region, getCountries() has already re-synced it\n // from the fresh catalog (see #syncUserRegionFromCountriesCatalog). Calling\n // setUserRegion here would re-validate against that catalog and, if it is\n // momentarily empty or no longer lists the region (e.g. a transient/partial\n // catalog response or a region with no current provider coverage), throw and\n // wipe the persisted region via #cleanupState. Preserve the existing region\n // instead; only resolve a brand-new region (from geolocation) strictly.\n if (persistedRegionCode) {\n return;\n }\n\n await this.setUserRegion(regionCode, options);\n }\n\n /**\n * Re-applies `userRegion` from the current countries catalog so preset\n * amounts and support flags stay in sync after a catalog refresh.\n */\n #syncUserRegionFromCountriesCatalog(): void {\n const regionCode = this.state.userRegion?.regionCode;\n if (!regionCode) {\n return;\n }\n\n const countriesData = this.state.countries.data;\n if (!countriesData.length) {\n return;\n }\n\n const userRegion = findRegionFromCode(regionCode, countriesData);\n if (!userRegion) {\n return;\n }\n\n this.update((state) => {\n state.userRegion = userRegion;\n });\n }\n\n /**\n * Fetches the list of supported countries.\n * The API returns countries with support information for both buy and sell actions.\n * The countries are saved in the controller state once fetched.\n *\n * @param options - Options for cache behavior.\n * @returns An array of countries.\n */\n async getCountries(options?: ExecuteRequestOptions): Promise<Country[]> {\n const cacheKey = createCacheKey('getCountries', []);\n\n const countries = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call('RampsService:getCountries');\n },\n { ...options, resourceType: 'countries' },\n );\n\n this.update((state) => {\n state.countries.data = Array.isArray(countries) ? [...countries] : [];\n });\n\n this.#syncUserRegionFromCountriesCatalog();\n\n return countries;\n }\n\n /**\n * Fetches the list of available tokens for a given region and action.\n * The tokens are saved in the controller state once fetched.\n *\n * @param region - The region code (e.g., \"us\", \"fr\", \"us-ny\"). If not provided, uses the user's region from controller state.\n * @param action - The ramp action type ('buy' or 'sell').\n * @param options - Options for cache behavior and query filters.\n * @param options.provider - Provider ID(s) to filter by.\n * @returns The tokens response containing topTokens and allTokens.\n */\n async getTokens(\n region?: string,\n action: RampAction = 'buy',\n options?: ExecuteRequestOptions & {\n provider?: string | string[];\n },\n ): Promise<TokensResponse> {\n const regionToUse = region ?? this.#requireRegion();\n\n const normalizedRegion = regionToUse.toLowerCase().trim();\n const cacheKey = createCacheKey('getTokens', [\n normalizedRegion,\n action,\n options?.provider,\n ]);\n\n const tokens = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call(\n 'RampsService:getTokens',\n normalizedRegion,\n action,\n {\n provider: options?.provider,\n },\n );\n },\n {\n ...options,\n resourceType: 'tokens',\n isResultCurrent: () => this.#isRegionCurrent(normalizedRegion),\n },\n );\n\n this.update((state) => {\n const userRegionCode = state.userRegion?.regionCode;\n\n if (userRegionCode === undefined || userRegionCode === normalizedRegion) {\n state.tokens.data = tokens;\n }\n });\n\n return tokens;\n }\n\n /**\n * Sets the user's selected token by asset ID.\n * Looks up the token from the current tokens in state and automatically\n * fetches payment methods for that token.\n *\n * @param assetId - The asset identifier in CAIP-19 format (e.g., \"eip155:1/erc20:0x...\"), or undefined to clear.\n * @throws If region is not set, tokens are not loaded, or token is not found.\n */\n setSelectedToken(assetId?: string): void {\n if (!assetId) {\n this.update((state) => {\n state.tokens.selected = null;\n });\n return;\n }\n\n this.#requireRegion();\n const tokens = this.state.tokens.data;\n if (!tokens) {\n throw new Error(\n 'Tokens not loaded. Cannot set selected token before tokens are fetched.',\n );\n }\n\n const token =\n tokens.allTokens.find((tok) => tok.assetId === assetId) ??\n tokens.topTokens.find((tok) => tok.assetId === assetId);\n\n if (!token) {\n throw new Error(\n `Token with asset ID \"${assetId}\" not found in available tokens.`,\n );\n }\n\n this.update((state) => {\n state.tokens.selected = token;\n });\n }\n\n /**\n * Fetches the list of providers for a given region.\n * The providers are saved in the controller state once fetched.\n *\n * @param region - The region code (e.g., \"us\", \"fr\", \"us-ny\"). If not provided, uses the user's region from controller state.\n * @param options - Options for cache behavior and query filters.\n * @param options.provider - Provider ID(s) to filter by.\n * @param options.crypto - Crypto currency ID(s) to filter by.\n * @param options.payments - Payment method ID(s) to filter by.\n * @returns The providers response containing providers array.\n */\n async getProviders(\n region?: string,\n options?: ExecuteRequestOptions & {\n provider?: string | string[];\n crypto?: string | string[];\n payments?: string | string[];\n },\n ): Promise<ProvidersResponse> {\n const regionToUse = region ?? this.#requireRegion();\n\n const normalizedRegion = regionToUse.toLowerCase().trim();\n const cacheKey = createCacheKey('getProviders', [\n normalizedRegion,\n options?.provider,\n options?.crypto,\n options?.payments,\n ]);\n\n const response = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call(\n 'RampsService:getProviders',\n normalizedRegion,\n {\n provider: options?.provider,\n crypto: options?.crypto,\n payments: options?.payments,\n },\n );\n },\n {\n ...options,\n resourceType: 'providers',\n isResultCurrent: () => this.#isRegionCurrent(normalizedRegion),\n },\n );\n const { providers } = response;\n\n this.update((state) => {\n const userRegionCode = state.userRegion?.regionCode;\n\n if (userRegionCode === undefined || userRegionCode === normalizedRegion) {\n state.providers.data = providers;\n }\n });\n\n return response;\n }\n\n /**\n * Fetches the list of payment methods for a given context.\n * The payment methods are saved in the controller state once fetched.\n *\n * @param region - User's region code (e.g. \"fr\", \"us-ny\").\n * @param options - Query parameters for filtering payment methods.\n * @param options.assetId - CAIP-19 cryptocurrency identifier.\n * @param options.provider - Provider ID path.\n * @returns The payment methods response containing payments array.\n */\n async getPaymentMethods(\n region?: string,\n options?: ExecuteRequestOptions & {\n assetId?: string;\n provider?: string;\n },\n ): Promise<PaymentMethodsResponse> {\n const regionCode = region ?? this.#requireRegion();\n const assetIdToUse =\n options?.assetId ?? this.state.tokens.selected?.assetId ?? '';\n const providerToUse =\n options?.provider ?? this.state.providers.selected?.id ?? '';\n\n const normalizedRegion = regionCode.toLowerCase().trim();\n const cacheKey = createCacheKey('getPaymentMethods', [\n normalizedRegion,\n assetIdToUse,\n providerToUse,\n ]);\n\n const response = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call('RampsService:getPaymentMethods', {\n region: normalizedRegion,\n assetId: assetIdToUse,\n provider: providerToUse,\n });\n },\n {\n ...options,\n resourceType: 'paymentMethods',\n isResultCurrent: () => {\n const regionMatch = this.#isRegionCurrent(normalizedRegion);\n const tokenMatch = this.#isTokenCurrent(assetIdToUse);\n const providerMatch = this.#isProviderCurrent(providerToUse);\n return regionMatch && tokenMatch && providerMatch;\n },\n },\n );\n\n this.update((state) => {\n const currentAssetId = state.tokens.selected?.assetId ?? '';\n const currentProviderId = state.providers.selected?.id ?? '';\n\n const tokenSelectionUnchanged = assetIdToUse === currentAssetId;\n const providerSelectionUnchanged = providerToUse === currentProviderId;\n\n // this is a race condition check to ensure that the selected token and provider in state are the same as the tokens we're requesting for\n // ex: if the user rapidly changes the token or provider, the in-flight payment methods might not be valid\n // so this check will ensure that the payment methods are still valid for the token and provider that were requested\n if (tokenSelectionUnchanged && providerSelectionUnchanged) {\n state.paymentMethods.data = response.payments;\n\n // this will auto-select the first payment method if the selected payment method is not in the new payment methods\n const currentSelectionStillValid = response.payments.some(\n (pm: PaymentMethod) => pm.id === state.paymentMethods.selected?.id,\n );\n if (!currentSelectionStillValid) {\n state.paymentMethods.selected = response.payments[0] ?? null;\n }\n }\n });\n\n return response;\n }\n\n /**\n * Fetches payment methods for a quoting context without coupling callers to\n * the Buy flow's globally selected provider/token catalog.\n *\n * Provider contribution mirrors {@link getQuotes}:\n * - explicit `providers` (optionally filtered when\n * `restrictToKnownOrNativeProviders` is set)\n * - auto-select / restrict path, including `moneyHeadlessAllProviders`\n * widening: flag off uses the restricted/native resolver; flag on uses\n * supporting providers, intersected with the flag allowlist when that\n * allowlist is non-empty (pick-survivor set for picker methods)\n * - when those resolution flags and `providers` are omitted, uses only\n * `providers.selected` (UB2 selected-provider context)\n *\n * By default this is request-only: it does **not** mutate\n * `paymentMethods.data` or `paymentMethods.selected`. Pass `updateState:\n * true` only when the caller explicitly wants Buy-catalog write semantics\n * (UB2). Headless / MM Pay selection stays TPC-owned. `updateState: true`\n * throws when the resolved provider set holds more than one provider, because\n * the write guards cannot tell two such requests apart.\n *\n * Methods are request-eligible for the resolved provider set; they are not\n * guaranteed to produce a quote for every amount (provider fiat limits still\n * apply at quote time).\n *\n * @param options - Context for the payment-method fetch.\n * @param options.region - Region code. Defaults to `userRegion`.\n * @param options.assetId - Required CAIP-19 quoting asset.\n * @param options.providers - Explicit provider ids.\n * @param options.autoSelectProvider - Resolve providers like `getQuotes`.\n * @param options.preferredProviderIds - Preferred ids for auto-selection.\n * @param options.restrictToKnownOrNativeProviders - Headless gating.\n * @param options.updateState - When true, write `paymentMethods` state.\n * @param options.preferPaymentMethodId - Preserve this id when still present.\n * @param options.forceRefresh - Bypass request cache for provider fetches.\n * @param options.ttl - Custom TTL for provider payment-method fetches.\n * @returns Deduped methods, a request-only suggested selection, and the\n * provider ids that contributed.\n */\n async getPaymentMethodsForContext(options: {\n region?: string;\n assetId: string;\n providers?: string[];\n autoSelectProvider?: boolean;\n preferredProviderIds?: string[];\n restrictToKnownOrNativeProviders?: boolean;\n updateState?: boolean;\n preferPaymentMethodId?: string;\n forceRefresh?: boolean;\n ttl?: number;\n }): Promise<PaymentMethodsForContextResponse> {\n const regionToUse = options.region ?? this.#requireRegion();\n const normalizedRegion = regionToUse.toLowerCase().trim();\n const assetId = options.assetId.trim();\n if (assetId === '') {\n throw new Error('assetId is required.');\n }\n const normalizedAssetContext = normalizeRampsAssetId(assetId);\n const updateState = options.updateState === true;\n const providerIdForState =\n options.providers?.length === 1\n ? options.providers[0].trim()\n : (this.state.providers.selected?.id.trim() ?? '');\n\n const providerIds = await this.#resolveProviderIdsForPaymentMethods({\n assetId,\n region: normalizedRegion,\n providers: options.providers,\n autoSelectProvider: options.autoSelectProvider,\n preferredProviderIds: options.preferredProviderIds,\n restrictToKnownOrNativeProviders:\n options.restrictToKnownOrNativeProviders,\n });\n\n // A fan-out across several providers produces a merged catalog whose value\n // depends on the provider set, but the write guards below only compare\n // region, selected token, and selected provider. Two concurrent\n // multi-provider requests share all three, so nothing distinguishes them\n // and the slower one would silently overwrite the faster one.\n if (updateState && providerIds.length > 1) {\n throw new Error(\n `getPaymentMethodsForContext cannot write paymentMethods state for ${providerIds.length} resolved providers. Use updateState: false, or request exactly one provider.`,\n );\n }\n\n const writeContext = {\n region: normalizedRegion,\n assetId: normalizedAssetContext,\n providerId: providerIdForState,\n };\n\n if (providerIds.length === 0) {\n if (updateState) {\n this.update((state) => {\n if (contextStillMatches(state, writeContext)) {\n state.paymentMethods.data = [];\n state.paymentMethods.selected = null;\n }\n });\n }\n return { methods: [], selected: null, providerIds };\n }\n\n const settled = await Promise.allSettled(\n providerIds.map(async (providerId) => {\n const cacheKey = createCacheKey('getPaymentMethodsForContext', [\n normalizedRegion,\n assetId,\n providerId,\n ]);\n return this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call('RampsService:getPaymentMethods', {\n region: normalizedRegion,\n assetId,\n provider: providerId,\n });\n },\n {\n forceRefresh: options.forceRefresh,\n ttl: options.ttl,\n // Intentionally omit resourceType / isResultCurrent so this\n // request-only path never drives Buy paymentMethods loading or\n // selection state unless `updateState` is explicitly set below.\n },\n );\n }),\n );\n\n const successfulLists: PaymentMethod[][] = [];\n const failures: unknown[] = [];\n for (const result of settled) {\n if (result.status === 'fulfilled') {\n successfulLists.push(result.value.payments);\n } else {\n failures.push(result.reason);\n }\n }\n\n if (successfulLists.length === 0) {\n const firstFailure = failures[0];\n throw firstFailure instanceof Error\n ? firstFailure\n : new Error('Failed to fetch payment methods for context.');\n }\n\n const methods = mergePaymentMethodsById(successfulLists);\n let selected = pickPaymentMethod(methods, [\n options.preferPaymentMethodId,\n this.state.paymentMethods.selected?.id,\n ]);\n\n if (updateState) {\n this.update((state) => {\n if (contextStillMatches(state, writeContext)) {\n // The stored selection outranks the caller's preference: the user may\n // have picked a method while this request was in flight.\n selected = pickPaymentMethod(methods, [\n state.paymentMethods.selected?.id,\n options.preferPaymentMethodId,\n ]);\n state.paymentMethods.data = methods;\n state.paymentMethods.selected = selected;\n }\n });\n }\n\n return { methods, selected, providerIds };\n }\n\n /**\n * Sets the user's selected payment method.\n *\n * Accepts either a payment method ID (looked up from state) or a full\n * PaymentMethod object (stored directly). The object form is preferred\n * when the caller already has the full data (e.g. from React Query cache),\n * as it avoids depending on controller state being populated.\n *\n * @param paymentMethodOrId - A PaymentMethod object, a payment method ID string, or undefined/null to clear.\n */\n setSelectedPaymentMethod(\n paymentMethodOrId?: string | PaymentMethod | null,\n ): void {\n if (!paymentMethodOrId) {\n this.update((state) => {\n state.paymentMethods.selected = null;\n });\n return;\n }\n\n // If a full object is passed, store it directly\n if (typeof paymentMethodOrId !== 'string') {\n this.update((state) => {\n state.paymentMethods.selected = paymentMethodOrId;\n });\n return;\n }\n\n // ID string: look up from state\n const paymentMethodId = paymentMethodOrId;\n const paymentMethods = this.state.paymentMethods.data;\n const paymentMethod = paymentMethods?.find(\n (pm) => pm.id === paymentMethodId,\n );\n\n this.update((state) => {\n state.paymentMethods.selected = paymentMethod ?? null;\n });\n }\n\n /**\n * Fetches quotes from all providers for a given set of parameters.\n * Uses the controller's request cache; callers manage the response in local state.\n *\n * @param options - The parameters for fetching quotes.\n * @param options.region - User's region code. If not provided, uses userRegion from state.\n * @param options.fiat - Fiat currency code. If not provided, uses userRegion currency.\n * @param options.assetId - CAIP-19 cryptocurrency identifier.\n * @param options.amount - The amount (in fiat for buy, crypto for sell).\n * @param options.walletAddress - The destination wallet address.\n * @param options.paymentMethods - Array of payment method IDs. If not provided, uses paymentMethods from state.\n * @param options.providers - Optional provider IDs to filter quotes.\n * @param options.autoSelectProvider - When true and `providers` is omitted,\n * resolves a provider that supports `assetId` for this request only (no\n * state mutation). Ignored when `providers` is passed.\n * @param options.preferredProviderIds - Optional provider IDs to prefer\n * during auto-selection, in priority order (e.g. derived by the caller\n * from completed-order history). Only used when `autoSelectProvider` is\n * true and `providers` is omitted.\n * @param options.restrictToKnownOrNativeProviders - Headless-buy v0 gating. When\n * true, auto-selection resolves only a native provider, and an explicitly\n * passed `providers` list is filtered to those supporting the region and\n * asset. If nothing qualifies, `getQuotes` returns an empty response\n * instead of quoting other providers.\n * @param options.redirectUrl - Optional redirect URL after order completion.\n * @param options.action - The ramp action type. Defaults to 'buy'.\n * @param options.forceRefresh - Whether to bypass cache.\n * @param options.ttl - Custom TTL for this request.\n * @returns The quotes response containing success, sorted, error, and customActions.\n */\n async getQuotes(options: {\n region?: string;\n fiat?: string;\n assetId?: string;\n amount: number;\n walletAddress: string;\n paymentMethods?: string[];\n providers?: string[];\n autoSelectProvider?: boolean;\n preferredProviderIds?: string[];\n restrictToKnownOrNativeProviders?: boolean;\n redirectUrl?: string;\n action?: RampAction;\n forceRefresh?: boolean;\n ttl?: number;\n }): Promise<QuotesResponse> {\n const regionToUse = options.region ?? this.#requireRegion();\n const fiatToUse = options.fiat ?? this.state.userRegion?.country?.currency;\n const paymentMethodsToUse =\n options.paymentMethods ??\n this.state.paymentMethods.data.map((pm: PaymentMethod) => pm.id);\n const action = options.action ?? 'buy';\n const assetIdToUse = options.assetId ?? this.state.tokens.selected?.assetId;\n\n if (!fiatToUse) {\n throw new Error(\n 'Fiat currency is required. Either provide a fiat parameter or ensure userRegion is set in controller state.',\n );\n }\n\n const normalizedAssetIdForValidation = (assetIdToUse ?? '').trim();\n if (normalizedAssetIdForValidation === '') {\n throw new Error('assetId is required.');\n }\n\n // When the all-providers feature flag is enabled, widen the native-only\n // auto-selection path to every supporting provider and pick the best\n // quote from the results. Only the auto-select/restrict path that MM Pay's\n // `getRampsQuote` uses is affected; explicit-`providers` callers and the\n // plain all-provider path are untouched (and never read the flag).\n const wantsAutoSelection =\n !options.providers &&\n (options.autoSelectProvider === true ||\n options.restrictToKnownOrNativeProviders === true);\n // Single flag read per call: the enabled bit and the allowlist come from\n // the same `RemoteFeatureFlagController` state snapshot, so a flag edit\n // during the awaited quote fetch cannot produce a mixed read.\n const { enabled: allProvidersEnabled, allowlist: providerAllowlist } =\n wantsAutoSelection\n ? this.#resolveAllProvidersFlag()\n : { enabled: false, allowlist: undefined };\n const widenToAllProviders = wantsAutoSelection && allProvidersEnabled;\n\n let providersToUse: string[];\n let widenedProviderCatalog: Provider[] = this.state.providers.data;\n if (options.providers) {\n providersToUse = options.restrictToKnownOrNativeProviders\n ? await this.#filterProviderIdsBySupport({\n providerIds: options.providers,\n assetId: normalizedAssetIdForValidation,\n region: regionToUse,\n })\n : options.providers;\n } else if (widenToAllProviders) {\n // `#getSupportingProvidersForRegion` also hydrates the provider catalog\n // when controller state is empty, so all-provider quoting cannot silently\n // return zero providers here.\n const { supporting } = await this.#getSupportingProvidersForRegion({\n assetId: normalizedAssetIdForValidation,\n region: regionToUse,\n });\n widenedProviderCatalog = supporting;\n providersToUse = supporting.map((provider) => provider.id);\n } else if (\n options.autoSelectProvider ||\n options.restrictToKnownOrNativeProviders\n ) {\n // The restriction flag implies resolution: it must narrow the provider\n // set even when `autoSelectProvider` was not explicitly passed, otherwise\n // it would be silently ignored and every provider quoted.\n providersToUse = await this.#resolveProviderIdsForQuote({\n assetId: normalizedAssetIdForValidation,\n region: regionToUse,\n preferredProviderIds: options.preferredProviderIds,\n restrictToKnownOrNative: options.restrictToKnownOrNativeProviders,\n });\n } else {\n providersToUse = this.state.providers.data.map(\n (provider: Provider) => provider.id,\n );\n }\n\n if (\n !paymentMethodsToUse ||\n paymentMethodsToUse.length === 0 ||\n paymentMethodsToUse.some((pm) => pm.trim() === '')\n ) {\n throw new Error(\n 'Payment methods are required. Either provide paymentMethods parameter or ensure paymentMethods are set in controller state.',\n );\n }\n\n if (options.amount <= 0 || !Number.isFinite(options.amount)) {\n throw new Error('Amount must be a positive finite number.');\n }\n\n if (!options.walletAddress || options.walletAddress.trim() === '') {\n throw new Error('walletAddress is required.');\n }\n\n // Under headless-buy gating, an empty resolved provider list means no\n // eligible (native/supporting) provider exists. Return an empty response\n // rather than passing `[]` to the service, which omits the provider filter\n // and would quote every provider. This also guards the widened path:\n // a caller may trigger widening with `autoSelectProvider` alone (no\n // `restrictToKnownOrNativeProviders`), and an empty supporting set must not\n // fall through to unfiltered quotes from providers that do not support the\n // asset.\n if (\n (options.restrictToKnownOrNativeProviders || widenToAllProviders) &&\n providersToUse.length === 0\n ) {\n return { success: [], sorted: [], error: [], customActions: [] };\n }\n\n const normalizedRegion = regionToUse.toLowerCase().trim();\n const normalizedFiat = fiatToUse.toLowerCase().trim();\n const normalizedAssetId = normalizedAssetIdForValidation;\n const normalizedWalletAddress = options.walletAddress.trim();\n\n // The quotes API only embeds a `buyURL`/`buyWidget` when a `redirectUrl` is\n // present, so on the widened path (where MM Pay omits one) ask the service\n // for the callback URL of the environment it is configured with, so\n // aggregator quotes carry a usable widget URL that always matches the\n // environment the quotes came from. An explicit caller `redirectUrl`\n // always wins, and the native-only path (flag off) never injects, so\n // neither reaches the service.\n const effectiveRedirectUrl =\n options.redirectUrl ??\n (widenToAllProviders\n ? this.messenger.call('RampsService:getDefaultRedirectCallbackUrl')\n : undefined);\n\n const cacheKey = createCacheKey('getQuotes', [\n normalizedRegion,\n normalizedFiat,\n normalizedAssetId,\n options.amount,\n normalizedWalletAddress,\n [...paymentMethodsToUse].sort().join(','),\n [...providersToUse].sort().join(','),\n effectiveRedirectUrl,\n action,\n ]);\n\n const params = {\n region: normalizedRegion,\n fiat: normalizedFiat,\n assetId: normalizedAssetId,\n amount: options.amount,\n walletAddress: normalizedWalletAddress,\n paymentMethods: paymentMethodsToUse,\n providers: providersToUse,\n redirectUrl: effectiveRedirectUrl,\n action,\n };\n\n const response = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call('RampsService:getQuotes', params);\n },\n {\n forceRefresh: options.forceRefresh,\n ttl: options.ttl ?? DEFAULT_QUOTES_TTL,\n },\n );\n\n if (!widenToAllProviders) {\n return response;\n }\n\n // Reduce the widened multi-provider result to the single best quote\n // and place it at `success[0]`, since single-pick consumers\n // (`getRampsQuote` -> `success?.[0]`) rely on index 0 while `success[]`\n // order is server-defined rather than ranked.\n const selectedQuote = this.#pickWidenedQuote(response, {\n amount: options.amount,\n fiat: normalizedFiat,\n providers: widenedProviderCatalog,\n allowlist: providerAllowlist,\n });\n\n if (!selectedQuote) {\n // No quote fits the published provider limits: surface \"no quote\"\n // rather than handing the single-pick consumer an out-of-limits quote.\n return {\n success: [],\n sorted: response.sorted,\n error: response.error,\n customActions: response.customActions,\n };\n }\n\n return {\n ...response,\n success: [\n selectedQuote,\n ...response.success.filter((quote) => quote !== selectedQuote),\n ],\n };\n }\n\n /**\n * Selects the best quote from a widened multi-provider response.\n *\n * Every provider class is eligible (native, in-app WebView aggregator, and\n * external-browser / custom-action). When the feature flag payload carries a\n * provider allowlist, candidates from unlisted providers are dropped first.\n * Enforces per-provider fiat limits up front, then orders by reliability and\n * falls back to price using the server-provided `sorted` order. Returns\n * `undefined` when no quote survives.\n *\n * @param response - The multi-provider quotes response.\n * @param options - Selection inputs.\n * @param options.amount - Fiat amount, for the limit-fit check.\n * @param options.fiat - Lowercased fiat short code, for the limit lookup.\n * @param options.providers - Provider catalog for the limit lookup.\n * @param options.allowlist - Optional provider ids (either `/providers/x`\n * or bare form) the pick is restricted to.\n * @returns The selected quote, or `undefined` when none is usable.\n */\n #pickWidenedQuote(\n response: QuotesResponse,\n {\n amount,\n fiat,\n providers,\n allowlist,\n }: {\n amount: number;\n fiat: string;\n providers: Provider[];\n allowlist?: string[];\n },\n ): Quote | undefined {\n const providerByCode = new Map(\n providers.map((provider) => [provider.id, provider]),\n );\n\n const allowedProviderIds =\n allowlist && allowlist.length > 0\n ? new Set(allowlist.map(normalizeHeadlessProviderId))\n : undefined;\n const isAllowedProvider = (quote: Quote): boolean =>\n !allowedProviderIds ||\n allowedProviderIds.has(normalizeHeadlessProviderId(quote.provider));\n\n const fitsProviderLimits = (quote: Quote): boolean => {\n const provider = providerByCode.get(quote.provider);\n const limit = provider?.limits?.fiat?.[fiat]?.[quote.quote.paymentMethod];\n if (!limit) {\n // No published limits for this provider/payment method: treat as\n // eligible and let the provider enforce limits at checkout.\n return true;\n }\n return amount >= limit.minAmount && amount <= limit.maxAmount;\n };\n\n const candidates = response.success.filter(\n (quote) => isAllowedProvider(quote) && fitsProviderLimits(quote),\n );\n if (candidates.length === 0) {\n return undefined;\n }\n\n const candidateByCode = new Map(\n candidates.map((quote) => [quote.provider, quote]),\n );\n\n const pickBySortOrder = (sortBy: QuoteSortBy): Quote | undefined => {\n const order = response.sorted.find(\n (entry) => entry.sortBy === sortBy,\n )?.ids;\n if (!order) {\n return undefined;\n }\n for (const providerId of order) {\n const match = candidateByCode.get(providerId);\n if (match) {\n return match;\n }\n }\n return undefined;\n };\n\n // Reliability first, then price, then the first surviving candidate.\n return (\n pickBySortOrder('reliability') ??\n pickBySortOrder('price') ??\n candidates[0]\n );\n }\n\n /**\n * Returns the region's providers that support the given asset, plus the full\n * region provider list. Uses cached providers only when the request targets\n * the current region; otherwise fetches for the requested region, since\n * `getProviders` does not persist results for a non-current region. Does not\n * mutate state.\n *\n * @param options - The options.\n * @param options.assetId - CAIP-19 asset type identifier to resolve for.\n * @param options.region - Region to resolve providers for.\n * @returns The supporting providers and the full region provider list.\n */\n async #getSupportingProvidersForRegion({\n assetId,\n region,\n }: {\n assetId: string;\n region: string;\n }): Promise<{ supporting: Provider[]; all: Provider[] }> {\n const normalizedRegion = region.toLowerCase().trim();\n\n let providers: Provider[];\n if (\n this.#isRegionCurrent(normalizedRegion) &&\n this.state.providers.data.length > 0\n ) {\n providers = this.state.providers.data;\n } else {\n ({ providers } = await this.getProviders(normalizedRegion));\n }\n\n // Case-insensitive CAIP-19 matching is shared with headless-buy consumers\n // via `getProvidersServingAsset`, so the controller and the UI region gate\n // cannot disagree about which providers serve the asset.\n const supporting = getProvidersServingAsset(providers, assetId);\n\n return { supporting, all: providers };\n }\n\n /**\n * Filters an explicitly-requested provider ID list down to those that support\n * the asset in the region. Used for headless-buy gating so an explicitly\n * passed provider that cannot serve the region/asset yields no providers\n * rather than being trusted blindly.\n *\n * @param options - The options.\n * @param options.providerIds - Explicitly requested provider IDs.\n * @param options.assetId - CAIP-19 asset type identifier to resolve for.\n * @param options.region - Region to resolve providers for.\n * @returns The subset of `providerIds` supporting the asset in the region.\n */\n async #filterProviderIdsBySupport({\n providerIds,\n assetId,\n region,\n }: {\n providerIds: string[];\n assetId: string;\n region: string;\n }): Promise<string[]> {\n const { supporting } = await this.#getSupportingProvidersForRegion({\n assetId,\n region,\n });\n const supportingIds = new Set(supporting.map((provider) => provider.id));\n return providerIds.filter((id) => supportingIds.has(id));\n }\n\n /**\n * Resolves the provider IDs to use for a single quote request, scoped to the\n * given asset and region. Does not mutate `providers.selected` or any other\n * state.\n *\n * Resolves against the region's supporting providers using this precedence:\n * 1. The currently selected provider, if it is in the supporting set.\n * 2. The first preferred provider that supports the asset, where the\n * preference is taken from `preferredProviderIds` when supplied, otherwise\n * derived from the user's completed-order history (most recent first).\n * This takes priority over Transak Native to preserve an existing KYC\n * relationship.\n * 3. A native provider (e.g. Transak Native).\n * 4. The first supporting provider — unless `restrictToKnownOrNative` is set, in\n * which case no further provider is introduced and nothing is returned.\n *\n * When `restrictToKnownOrNative` is unset and no provider supports the asset, falls\n * back to all known provider IDs so the request behaves as if no\n * auto-selection occurred.\n *\n * @param options - The options.\n * @param options.assetId - CAIP-19 asset type identifier to resolve for.\n * @param options.region - Region to resolve providers for.\n * @param options.preferredProviderIds - Provider IDs to prefer, in order.\n * @param options.restrictToKnownOrNative - When true, resolve only a native provider\n * (or no providers when none supports the asset).\n * @returns Provider IDs for this request only.\n */\n async #resolveProviderIdsForQuote({\n assetId,\n region,\n preferredProviderIds,\n restrictToKnownOrNative,\n }: {\n assetId: string;\n region: string;\n preferredProviderIds?: string[];\n restrictToKnownOrNative?: boolean;\n }): Promise<string[]> {\n const { supporting, all } = await this.#getSupportingProvidersForRegion({\n assetId,\n region,\n });\n\n // When not restricted and nothing supports the asset, behave as if no\n // auto-selection occurred (quote against all known providers).\n if (!restrictToKnownOrNative && supporting.length === 0) {\n return all.map((provider) => provider.id);\n }\n\n // 1. The currently selected provider, if it supports the asset.\n const { selected } = this.state.providers;\n if (\n selected &&\n supporting.some((provider) => provider.id === selected.id)\n ) {\n return [selected.id];\n }\n\n // 2. A provider the user has transacted with before — from\n // `preferredProviderIds` when supplied, otherwise completed-order\n // history. Takes priority over Transak Native to preserve an existing\n // KYC relationship and avoid churn.\n const preferred =\n preferredProviderIds ?? this.#getPreferredProviderIdsFromOrders();\n\n for (const preferredId of preferred) {\n const match = supporting.find((provider) => provider.id === preferredId);\n if (match) {\n return [match.id];\n }\n }\n\n // 3. A native provider (e.g. Transak Native).\n const nativeProvider = supporting.find(\n (provider) => provider.type === 'native',\n );\n if (nativeProvider) {\n return [nativeProvider.id];\n }\n\n // 4. Fallback. Under headless gating, introduce no other provider — return\n // nothing so the caller surfaces an \"unavailable\" state. Otherwise the\n // aggregator and all other providers are treated equally: first wins.\n if (restrictToKnownOrNative) {\n return [];\n }\n return [supporting[0].id];\n }\n\n /**\n * Resolves provider IDs that should contribute payment methods for a\n * quoting context. Mirrors {@link getQuotes} provider-set selection, with\n * one intentional difference on the widened path: when the all-providers\n * flag allowlist is non-empty, returns supporting providers intersected\n * with that allowlist (pick survivors for the picker). Does not mutate\n * state.\n *\n * @param options - Resolution inputs aligned with `getQuotes`.\n * @param options.assetId - CAIP-19 asset type identifier to resolve for.\n * @param options.region - Region to resolve providers for.\n * @param options.providers - Explicit provider IDs, when provided.\n * @param options.autoSelectProvider - Resolve providers like `getQuotes`.\n * @param options.preferredProviderIds - Preferred provider IDs in order.\n * @param options.restrictToKnownOrNativeProviders - Headless gating.\n * @returns Provider IDs for this request only.\n */\n async #resolveProviderIdsForPaymentMethods({\n assetId,\n region,\n providers,\n autoSelectProvider,\n preferredProviderIds,\n restrictToKnownOrNativeProviders,\n }: {\n assetId: string;\n region: string;\n providers?: string[];\n autoSelectProvider?: boolean;\n preferredProviderIds?: string[];\n restrictToKnownOrNativeProviders?: boolean;\n }): Promise<string[]> {\n const wantsAutoSelection =\n !providers &&\n (autoSelectProvider === true ||\n restrictToKnownOrNativeProviders === true);\n const { enabled: allProvidersEnabled, allowlist: providerAllowlist } =\n wantsAutoSelection\n ? this.#resolveAllProvidersFlag()\n : { enabled: false, allowlist: undefined };\n const widenToAllProviders = wantsAutoSelection && allProvidersEnabled;\n\n if (providers) {\n return restrictToKnownOrNativeProviders\n ? this.#filterProviderIdsBySupport({\n providerIds: providers,\n assetId,\n region,\n })\n : providers;\n }\n\n if (widenToAllProviders) {\n const { supporting } = await this.#getSupportingProvidersForRegion({\n assetId,\n region,\n });\n if (providerAllowlist && providerAllowlist.length > 0) {\n const allowedProviderIds = new Set(\n providerAllowlist.map(normalizeHeadlessProviderId),\n );\n return supporting\n .filter((provider) =>\n allowedProviderIds.has(normalizeHeadlessProviderId(provider.id)),\n )\n .map((provider) => provider.id);\n }\n return supporting.map((provider) => provider.id);\n }\n\n if (autoSelectProvider || restrictToKnownOrNativeProviders) {\n return this.#resolveProviderIdsForQuote({\n assetId,\n region,\n preferredProviderIds,\n restrictToKnownOrNative: restrictToKnownOrNativeProviders,\n });\n }\n\n const selectedId = this.state.providers.selected?.id;\n return selectedId ? [selectedId] : [];\n }\n\n /**\n * Derives an ordered list of provider IDs from the user's completed-order\n * history, most recently completed first, with duplicates removed.\n *\n * Reads only this controller's own normalized order state, so it carries no\n * dependency on any client-specific order representation.\n *\n * @returns Provider IDs ordered by most recent completed order.\n */\n #getPreferredProviderIdsFromOrders(): string[] {\n const orderedIds: string[] = [];\n\n const completedOrders = this.state.orders\n .filter(\n (order) =>\n order.status === RampsOrderStatus.Completed && order.provider?.id,\n )\n .sort((orderA, orderB) => orderB.createdAt - orderA.createdAt);\n\n for (const order of completedOrders) {\n const id = order.provider?.id;\n if (id && !orderedIds.includes(id)) {\n orderedIds.push(id);\n }\n }\n\n return orderedIds;\n }\n\n // === ORDER MANAGEMENT ===\n\n /**\n * Adds or updates a V2 order in controller state.\n * If an order with the same internal order code already exists, the incoming\n * fields are merged on top of the existing order so that fields not present\n * in the update (e.g. paymentDetails from the Transak API) are preserved.\n *\n * @param order - The RampsOrder to add or update.\n */\n addOrder(order: RampsOrder): void {\n const internalOrderCode = getInternalOrderCode(order);\n const healedOrder = {\n ...order,\n providerOrderId: internalOrderCode,\n };\n\n this.update((state) => {\n const idx = state.orders.findIndex(\n (existing) => getInternalOrderCode(existing) === internalOrderCode,\n );\n if (idx === -1) {\n state.orders.push(healedOrder as Draft<RampsOrder>);\n } else {\n state.orders[idx] = {\n ...state.orders[idx],\n ...healedOrder,\n } as Draft<RampsOrder>;\n }\n });\n }\n\n /**\n * Removes a V2 order from controller state by providerOrderId.\n *\n * @param providerOrderId - The provider order ID to remove.\n */\n removeOrder(providerOrderId: string): void {\n this.update((state) => {\n state.orders = state.orders.filter(\n (order) => order.providerOrderId !== providerOrderId,\n );\n });\n\n this.#orderPollingMeta.delete(providerOrderId);\n }\n\n /**\n * Refreshes a single order via the V2 API and updates it in state.\n * Publishes orderStatusChanged if the status transitioned.\n *\n * @param order - The order to refresh (needs provider and providerOrderId).\n */\n async #refreshOrder(order: RampsOrder): Promise<void> {\n const providerCode = order.provider?.id ?? '';\n if (!providerCode || !order.providerOrderId || !order.walletAddress) {\n return;\n }\n\n const previousStatus = order.status;\n\n try {\n const updatedOrder = await this.getOrder(\n providerCode,\n order.providerOrderId,\n order.walletAddress,\n );\n\n const meta = this.#orderPollingMeta.get(order.providerOrderId) ?? {\n lastTimeFetched: 0,\n errorCount: 0,\n };\n\n if (updatedOrder.status === RampsOrderStatus.Unknown) {\n meta.errorCount = Math.min(meta.errorCount + 1, MAX_ERROR_COUNT);\n } else {\n meta.errorCount = 0;\n }\n\n meta.lastTimeFetched = Date.now();\n this.#orderPollingMeta.set(order.providerOrderId, meta);\n\n if (\n previousStatus !== updatedOrder.status &&\n previousStatus !== undefined\n ) {\n this.messenger.publish('RampsController:orderStatusChanged', {\n order: updatedOrder,\n previousStatus,\n });\n }\n\n if (TERMINAL_ORDER_STATUSES.has(updatedOrder.status)) {\n this.#orderPollingMeta.delete(order.providerOrderId);\n }\n } catch {\n const meta = this.#orderPollingMeta.get(order.providerOrderId) ?? {\n lastTimeFetched: 0,\n errorCount: 0,\n };\n meta.errorCount = Math.min(meta.errorCount + 1, MAX_ERROR_COUNT);\n meta.lastTimeFetched = Date.now();\n this.#orderPollingMeta.set(order.providerOrderId, meta);\n }\n }\n\n /**\n * Starts polling all pending V2 orders at a fixed interval.\n * Each poll cycle iterates orders with non-terminal statuses,\n * respects pollingSecondsMinimum and backoff from error count.\n */\n startOrderPolling(): void {\n if (this.#orderPollingTimer) {\n return;\n }\n\n this.#orderPollingTimer = setInterval(() => {\n this.#pollPendingOrders().catch(() => undefined);\n }, DEFAULT_POLLING_INTERVAL_MS);\n\n this.#pollPendingOrders().catch(() => undefined);\n }\n\n /**\n * Stops order polling and clears the interval.\n */\n stopOrderPolling(): void {\n if (this.#orderPollingTimer) {\n clearInterval(this.#orderPollingTimer);\n this.#orderPollingTimer = null;\n }\n }\n\n async #pollPendingOrders(): Promise<void> {\n if (this.#isPolling) {\n return;\n }\n this.#isPolling = true;\n try {\n const pendingOrders = this.state.orders.filter((order) =>\n PENDING_ORDER_STATUSES.has(order.status),\n );\n\n const now = Date.now();\n\n await Promise.allSettled(\n pendingOrders.map(async (order) => {\n const meta = this.#orderPollingMeta.get(order.providerOrderId);\n\n if (meta) {\n const backoffMs =\n meta.errorCount > 0\n ? Math.min(\n DEFAULT_POLLING_INTERVAL_MS *\n Math.pow(2, meta.errorCount - 1),\n 5 * 60 * 1000,\n )\n : 0;\n\n const pollingMinMs = (order.pollingSecondsMinimum ?? 0) * 1000;\n const minWait = Math.max(backoffMs, pollingMinMs);\n\n if (now - meta.lastTimeFetched < minWait) {\n return;\n }\n }\n\n await this.#refreshOrder(order);\n }),\n );\n } finally {\n this.#isPolling = false;\n }\n }\n\n /**\n * Cleans up controller resources.\n * Should be called when the controller is no longer needed.\n */\n override destroy(): void {\n this.stopOrderPolling();\n super.destroy();\n }\n\n /**\n * Fetches the widget data from a quote for redirect providers.\n * Makes a request to the buyURL endpoint via the RampsService to get the\n * actual provider widget URL and optional order ID for polling.\n *\n * @param quote - The quote to fetch the widget URL from.\n * @returns Promise resolving to the full BuyWidget (url, browser, orderId), or null if not available (missing buyURL or empty url in response).\n * @throws Rethrows errors from the RampsService (e.g. HttpError, network failures) so clients can react to fetch failures.\n */\n async getBuyWidgetData(quote: Quote): Promise<BuyWidget | null> {\n const buyUrl = quote.quote?.buyURL;\n if (!buyUrl) {\n return null;\n }\n\n const buyWidget = await this.messenger.call(\n 'RampsService:getBuyWidgetUrl',\n buyUrl,\n );\n if (!buyWidget?.url) {\n return null;\n }\n return buyWidget;\n }\n\n /**\n * Registers an order ID for polling until the order is created or resolved.\n * Adds a minimal stub order to controller state; the existing order polling\n * will fetch the full order when the provider has created it.\n *\n * @param params - Object containing order identifiers and wallet info.\n * @param params.orderId - Full order ID (e.g. \"/providers/paypal/orders/abc123\") or order code.\n * @param params.providerCode - Canonical provider code (e.g. \"paypal\", \"transak\").\n * @param params.walletAddress - Wallet address for the order.\n * @param params.chainId - Chain ID for the order (decimal, hex, or CAIP-2). Must be non-empty.\n */\n addPrecreatedOrder(params: {\n orderId: string;\n providerCode: string;\n walletAddress: string;\n chainId: string;\n }): void {\n const { orderId, providerCode, walletAddress, chainId } = params;\n\n const orderCode = getInternalOrderCode(orderId);\n if (!orderCode?.trim()) {\n return;\n }\n if (!chainId.trim()) {\n return;\n }\n const stubOrder: RampsOrder = {\n providerOrderId: orderCode,\n provider: {\n id: providerCode,\n name: '',\n environmentType: '',\n description: '',\n hqAddress: '',\n links: [],\n logos: { light: '', dark: '', height: 0, width: 0 },\n },\n walletAddress,\n status: RampsOrderStatus.Precreated,\n orderType: 'buy',\n createdAt: Date.now(),\n isOnlyLink: false,\n success: false,\n cryptoAmount: 0,\n fiatAmount: 0,\n providerOrderLink: '',\n totalFeesFiat: 0,\n txHash: '',\n network: { chainId, name: '' },\n canBeUpdated: true,\n idHasExpired: false,\n excludeFromPurchases: false,\n timeDescriptionPending: '',\n };\n\n this.addOrder(stubOrder);\n }\n\n /**\n * Fetches an order from the unified V2 API endpoint.\n * Returns a normalized RampsOrder for all provider types (aggregator and native).\n *\n * @param providerCode - The provider code (e.g., \"transak\", \"transak-native\", \"moonpay\").\n * @param orderCode - The order identifier.\n * @param wallet - The wallet address associated with the order.\n * @returns The unified order data.\n */\n async getOrder(\n providerCode: string,\n orderCode: string,\n wallet: string,\n ): Promise<RampsOrder> {\n const order = await this.messenger.call(\n 'RampsService:getOrder',\n providerCode,\n orderCode,\n wallet,\n );\n\n const healedWalletAddress = order.walletAddress || wallet;\n const internalOrderCode = getInternalOrderCode({\n id: order.id,\n providerOrderId: orderCode,\n });\n const healedOrder = {\n ...order,\n walletAddress: healedWalletAddress,\n providerOrderId: internalOrderCode,\n };\n\n this.update((state) => {\n const idx = state.orders.findIndex(\n (existing: RampsOrder) =>\n getInternalOrderCode(existing) === internalOrderCode,\n );\n if (idx === -1) {\n state.orders.push(healedOrder as Draft<RampsOrder>);\n } else {\n state.orders[idx] = {\n ...state.orders[idx],\n ...healedOrder,\n } as Draft<RampsOrder>;\n }\n });\n\n return healedOrder;\n }\n\n /**\n * Extracts an order from a provider callback URL.\n * Sends the callback URL to the V2 backend for provider-specific parsing,\n * then fetches the full order. This is the V2 equivalent of the aggregator\n * SDK's `getOrderFromCallback`.\n *\n * @param providerCode - The provider code (e.g., \"transak\", \"moonpay\").\n * @param callbackUrl - The full callback URL the provider redirected to.\n * @param wallet - The wallet address associated with the order.\n * @returns The unified order data.\n */\n async getOrderFromCallback(\n providerCode: string,\n callbackUrl: string,\n wallet: string,\n ): Promise<RampsOrder> {\n const order = await this.messenger.call(\n 'RampsService:getOrderFromCallback',\n providerCode,\n callbackUrl,\n wallet,\n );\n\n return order;\n }\n\n // === TRANSAK METHODS ===\n //\n // Auth state is managed at two levels:\n // - TransakService stores the access token (needed for API calls)\n // - RampsController stores isAuthenticated (needed for UI state)\n // Both are kept in sync by the controller methods below.\n\n /**\n * Checks whether an error is a 401 HTTP error (expired/missing token) and,\n * if so, marks the Transak session as unauthenticated so the UI stays in\n * sync with the cleared token inside TransakService.\n *\n * @param error - The caught error to inspect.\n */\n #syncTransakAuthOnError(error: unknown): void {\n if (hasHttpStatus(error) && error.httpStatus === 401) {\n this.transakSetAuthenticated(false);\n }\n }\n\n #getNormalizedTransakError(\n error: unknown,\n options: { syncAuth?: boolean } = {},\n ): NormalizedRampsError {\n if (options.syncAuth) {\n this.#syncTransakAuthOnError(error);\n }\n\n return getNormalizedRampsError(error);\n }\n\n /**\n * Sets the Transak API key used for all Transak API requests.\n *\n * @param apiKey - The Transak API key.\n */\n transakSetApiKey(apiKey: string): void {\n this.messenger.call('TransakService:setApiKey', apiKey);\n }\n\n /**\n * Sets the Transak access token and marks the user as authenticated.\n *\n * @param token - The access token received from Transak auth.\n */\n transakSetAccessToken(token: TransakAccessToken): void {\n this.messenger.call('TransakService:setAccessToken', token);\n this.transakSetAuthenticated(true);\n }\n\n /**\n * Clears the Transak access token and marks the user as unauthenticated.\n */\n transakClearAccessToken(): void {\n this.messenger.call('TransakService:clearAccessToken');\n this.transakSetAuthenticated(false);\n }\n\n /**\n * Updates the Transak authentication flag in controller state.\n *\n * @param isAuthenticated - Whether the user is authenticated with Transak.\n */\n transakSetAuthenticated(isAuthenticated: boolean): void {\n this.update((state) => {\n state.nativeProviders.transak.isAuthenticated = isAuthenticated;\n });\n }\n\n /**\n * Resets all Transak state back to defaults (unauthenticated, no data).\n */\n transakResetState(): void {\n this.messenger.call('TransakService:clearAccessToken');\n this.update((state) => {\n state.nativeProviders.transak =\n getDefaultRampsControllerState().nativeProviders.transak;\n });\n }\n\n /**\n * Sends a one-time password to the user's email for Transak authentication.\n *\n * @param email - The user's email address.\n * @returns The OTP response containing a state token for verification.\n */\n async transakSendUserOtp(email: string): Promise<{\n isTncAccepted: boolean;\n stateToken: string;\n email: string;\n expiresIn: number;\n }> {\n try {\n return await this.messenger.call('TransakService:sendUserOtp', email);\n } catch (error) {\n throw this.#getNormalizedTransakError(error).normalizedError;\n }\n }\n\n /**\n * Verifies a one-time password and authenticates the user with Transak.\n * Updates the controller's authentication state on success.\n *\n * @param email - The user's email address.\n * @param verificationCode - The OTP code entered by the user.\n * @param stateToken - The state token from the sendUserOtp response.\n * @returns The access token for subsequent authenticated requests.\n */\n async transakVerifyUserOtp(\n email: string,\n verificationCode: string,\n stateToken: string,\n ): Promise<TransakAccessToken> {\n try {\n const token = await this.messenger.call(\n 'TransakService:verifyUserOtp',\n email,\n verificationCode,\n stateToken,\n );\n this.transakSetAuthenticated(true);\n return token;\n } catch (error) {\n throw this.#getNormalizedTransakError(error).normalizedError;\n }\n }\n\n /**\n * Logs the user out of Transak. Clears authentication state and user details\n * regardless of whether the API call succeeds or fails.\n *\n * @returns A message indicating the logout result.\n */\n async transakLogout(): Promise<string> {\n try {\n return await this.messenger.call('TransakService:logout');\n } catch (error) {\n throw this.#getNormalizedTransakError(error).normalizedError;\n } finally {\n this.transakClearAccessToken();\n this.update((state) => {\n state.nativeProviders.transak.userDetails.data = null;\n });\n }\n }\n\n /**\n * Fetches the authenticated user's details from Transak.\n * Updates the userDetails resource state with loading/success/error states.\n *\n * @returns The user's profile and KYC details.\n */\n async transakGetUserDetails(): Promise<TransakUserDetails> {\n this.update((state) => {\n state.nativeProviders.transak.userDetails.isLoading = true;\n state.nativeProviders.transak.userDetails.error = null;\n delete state.nativeProviders.transak.userDetails.errorKey;\n });\n try {\n const details = await this.messenger.call(\n 'TransakService:getUserDetails',\n );\n this.update((state) => {\n state.nativeProviders.transak.userDetails.data = details;\n state.nativeProviders.transak.userDetails.isLoading = false;\n });\n return details;\n } catch (error) {\n const { errorInfo, normalizedError } = this.#getNormalizedTransakError(\n error,\n {\n syncAuth: true,\n },\n );\n this.update((state) => {\n state.nativeProviders.transak.userDetails.isLoading = false;\n state.nativeProviders.transak.userDetails.error = errorInfo.message;\n state.nativeProviders.transak.userDetails.errorKey = errorInfo.errorKey;\n });\n throw normalizedError;\n }\n }\n\n /**\n * Fetches a buy quote from Transak for the given parameters.\n * Updates the buyQuote resource state with loading/success/error states.\n *\n * @param fiatCurrency - The fiat currency code (e.g., \"USD\").\n * @param cryptoCurrency - The cryptocurrency identifier.\n * @param network - The blockchain network identifier.\n * @param paymentMethod - The payment method identifier.\n * @param fiatAmount - The fiat amount as a string.\n * @returns The buy quote with pricing and fee details.\n */\n async transakGetBuyQuote(\n fiatCurrency: string,\n cryptoCurrency: string,\n network: string,\n paymentMethod: string,\n fiatAmount: string,\n ): Promise<TransakBuyQuote> {\n this.update((state) => {\n state.nativeProviders.transak.buyQuote.isLoading = true;\n state.nativeProviders.transak.buyQuote.error = null;\n delete state.nativeProviders.transak.buyQuote.errorKey;\n });\n try {\n const quote = await this.messenger.call(\n 'TransakService:getBuyQuote',\n fiatCurrency,\n cryptoCurrency,\n network,\n paymentMethod,\n fiatAmount,\n );\n this.update((state) => {\n state.nativeProviders.transak.buyQuote.data = quote;\n state.nativeProviders.transak.buyQuote.isLoading = false;\n });\n return quote;\n } catch (error) {\n const { errorInfo, normalizedError } =\n this.#getNormalizedTransakError(error);\n this.update((state) => {\n state.nativeProviders.transak.buyQuote.isLoading = false;\n state.nativeProviders.transak.buyQuote.error = errorInfo.message;\n state.nativeProviders.transak.buyQuote.errorKey = errorInfo.errorKey;\n });\n throw normalizedError;\n }\n }\n\n /**\n * Fetches the KYC requirement for a given quote.\n * Updates the kycRequirement resource state with loading/success/error states.\n *\n * @param quoteId - The quote ID to check KYC requirements for.\n * @returns The KYC requirement status and whether the user can place an order.\n */\n async transakGetKycRequirement(\n quoteId: string,\n ): Promise<TransakKycRequirement> {\n this.update((state) => {\n state.nativeProviders.transak.kycRequirement.isLoading = true;\n state.nativeProviders.transak.kycRequirement.error = null;\n delete state.nativeProviders.transak.kycRequirement.errorKey;\n });\n try {\n const requirement = await this.messenger.call(\n 'TransakService:getKycRequirement',\n quoteId,\n );\n this.update((state) => {\n state.nativeProviders.transak.kycRequirement.data = requirement;\n state.nativeProviders.transak.kycRequirement.isLoading = false;\n });\n return requirement;\n } catch (error) {\n const { errorInfo, normalizedError } = this.#getNormalizedTransakError(\n error,\n {\n syncAuth: true,\n },\n );\n this.update((state) => {\n state.nativeProviders.transak.kycRequirement.isLoading = false;\n state.nativeProviders.transak.kycRequirement.error = errorInfo.message;\n state.nativeProviders.transak.kycRequirement.errorKey =\n errorInfo.errorKey;\n });\n throw normalizedError;\n }\n }\n\n /**\n * Fetches additional KYC requirements (e.g., ID proof, address proof) for a quote.\n *\n * @param quoteId - The quote ID to check additional requirements for.\n * @returns The list of additional forms required.\n */\n async transakGetAdditionalRequirements(\n quoteId: string,\n ): Promise<TransakAdditionalRequirementsResponse> {\n try {\n return await this.messenger.call(\n 'TransakService:getAdditionalRequirements',\n quoteId,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Creates a new order on Transak. If an existing order conflicts (HTTP 409),\n * active orders are cancelled and the creation is retried.\n *\n * @param quoteId - The quote ID to create an order from.\n * @param walletAddress - The destination wallet address.\n * @param paymentMethodId - The payment method to use.\n * @returns The created deposit order.\n */\n async transakCreateOrder(\n quoteId: string,\n walletAddress: string,\n paymentMethodId: string,\n ): Promise<TransakDepositOrder> {\n try {\n return await this.messenger.call(\n 'TransakService:createOrder',\n quoteId,\n walletAddress,\n paymentMethodId,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Fetches an existing order from Transak by order ID.\n *\n * @param orderId - The order ID (deposit format or raw Transak format).\n * @param wallet - The wallet address associated with the order.\n * @param paymentDetails - Optional payment details to attach to the order.\n * @returns The deposit order details.\n */\n async transakGetOrder(\n orderId: string,\n wallet: string,\n paymentDetails?: TransakOrderPaymentMethod[],\n ): Promise<TransakDepositOrder> {\n try {\n return await this.messenger.call(\n 'TransakService:getOrder',\n orderId,\n wallet,\n paymentDetails,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error).normalizedError;\n }\n }\n\n /**\n * Fetches the user's spending limits for a given currency and payment method.\n *\n * @param fiatCurrency - The fiat currency code.\n * @param paymentMethod - The payment method identifier.\n * @param kycType - The KYC level type.\n * @returns The user's limits, spending, and remaining amounts.\n */\n async transakGetUserLimits(\n fiatCurrency: string,\n paymentMethod: string,\n kycType: string,\n ): Promise<TransakUserLimits> {\n try {\n return await this.messenger.call(\n 'TransakService:getUserLimits',\n fiatCurrency,\n paymentMethod,\n kycType,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Requests a one-time token (OTT) for the Transak payment widget.\n *\n * @returns The OTT response containing the token.\n */\n async transakRequestOtt(): Promise<TransakOttResponse> {\n try {\n return await this.messenger.call('TransakService:requestOtt');\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Generates a URL for the Transak payment widget with pre-filled parameters.\n *\n * @param ottToken - The one-time token for widget authentication.\n * @param quote - The buy quote to pre-fill in the widget.\n * @param walletAddress - The destination wallet address.\n * @param extraParams - Optional additional URL parameters.\n * @returns The fully constructed widget URL string.\n */\n transakGeneratePaymentWidgetUrl(\n ottToken: string,\n quote: TransakBuyQuote,\n walletAddress: string,\n extraParams?: Record<string, string>,\n ): string {\n return this.messenger.call(\n 'TransakService:generatePaymentWidgetUrl',\n ottToken,\n quote,\n walletAddress,\n extraParams,\n );\n }\n\n /**\n * Creates a Transak payment widget URL via the ramps API proxy, which\n * injects the partner API key server-side. Replaces the OTT flow\n * ({@link transakRequestOtt} + {@link transakGeneratePaymentWidgetUrl}).\n *\n * @param quote - The buy quote to pre-fill in the widget.\n * @param walletAddress - The destination wallet address.\n * @param extraParams - Optional additional widget parameters (e.g. theming).\n * @returns The single-use widget URL.\n */\n async transakCreateWidgetUrl(\n quote: TransakBuyQuote,\n walletAddress: string,\n extraParams?: Record<string, string>,\n ): Promise<string> {\n try {\n return await this.messenger.call(\n 'TransakService:createWidgetUrl',\n quote,\n walletAddress,\n extraParams,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Submits the user's purpose of usage form for KYC compliance.\n *\n * @param purpose - Array of purpose strings selected by the user.\n * @returns A promise that resolves when the form is submitted.\n */\n async transakSubmitPurposeOfUsageForm(purpose: string[]): Promise<void> {\n try {\n return await this.messenger.call(\n 'TransakService:submitPurposeOfUsageForm',\n purpose,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Updates the user's personal or address details on Transak.\n *\n * @param data - The user data fields to update.\n * @returns The API response data.\n */\n async transakPatchUser(data: PatchUserRequestBody): Promise<unknown> {\n try {\n return await this.messenger.call('TransakService:patchUser', data);\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Submits the user's SSN for identity verification.\n *\n * @param ssn - The Social Security Number.\n * @param quoteId - The quote ID associated with the order requiring SSN.\n * @returns The API response data.\n */\n async transakSubmitSsnDetails(\n ssn: string,\n quoteId: string,\n ): Promise<unknown> {\n try {\n return await this.messenger.call(\n 'TransakService:submitSsnDetails',\n ssn,\n quoteId,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Confirms payment for an order after the user has completed payment.\n *\n * @param orderId - The order ID to confirm payment for.\n * @param paymentMethodId - The payment method used.\n * @returns Whether the payment confirmation was successful.\n */\n async transakConfirmPayment(\n orderId: string,\n paymentMethodId: string,\n ): Promise<{ success: boolean }> {\n try {\n return await this.messenger.call(\n 'TransakService:confirmPayment',\n orderId,\n paymentMethodId,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Translates generic ramps identifiers to Transak-specific identifiers.\n *\n * @param request - The translation request with optional identifiers to translate.\n * @returns The translated Transak-specific identifiers.\n */\n async transakGetTranslation(\n request: TransakTranslationRequest,\n ): Promise<TransakQuoteTranslation> {\n try {\n return await this.messenger.call(\n 'TransakService:getTranslation',\n request,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error).normalizedError;\n }\n }\n\n /**\n * Checks the status of an ID proof submission for KYC.\n *\n * @param workFlowRunId - The workflow run ID to check status for.\n * @returns The current ID proof status.\n */\n async transakGetIdProofStatus(\n workFlowRunId: string,\n ): Promise<TransakIdProofStatus> {\n try {\n return await this.messenger.call(\n 'TransakService:getIdProofStatus',\n workFlowRunId,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Cancels a specific Transak order.\n *\n * @param depositOrderId - The deposit order ID to cancel.\n * @returns A promise that resolves when the order is cancelled.\n */\n async transakCancelOrder(depositOrderId: string): Promise<void> {\n try {\n return await this.messenger.call(\n 'TransakService:cancelOrder',\n depositOrderId,\n );\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Cancels all active Transak orders. Individual cancellation failures\n * are collected and returned rather than thrown.\n *\n * @returns An array of errors from any failed cancellations (empty if all succeeded).\n */\n async transakCancelAllActiveOrders(): Promise<Error[]> {\n try {\n return await this.messenger.call('TransakService:cancelAllActiveOrders');\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n\n /**\n * Fetches all active Transak orders for the authenticated user.\n *\n * @returns The list of active orders.\n */\n async transakGetActiveOrders(): Promise<TransakOrder[]> {\n try {\n return await this.messenger.call('TransakService:getActiveOrders');\n } catch (error) {\n throw this.#getNormalizedTransakError(error, { syncAuth: true })\n .normalizedError;\n }\n }\n}\n"]}