@metamask/ramps-controller 10.0.0 → 10.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.
- package/CHANGELOG.md +18 -1
- package/dist/RampsController.cjs +188 -4
- package/dist/RampsController.cjs.map +1 -1
- package/dist/RampsController.d.cts +66 -2
- package/dist/RampsController.d.cts.map +1 -1
- package/dist/RampsController.d.mts +66 -2
- package/dist/RampsController.d.mts.map +1 -1
- package/dist/RampsController.mjs +188 -4
- package/dist/RampsController.mjs.map +1 -1
- package/dist/RampsService.cjs.map +1 -1
- package/dist/RampsService.d.cts +14 -0
- package/dist/RampsService.d.cts.map +1 -1
- package/dist/RampsService.d.mts +14 -0
- package/dist/RampsService.d.mts.map +1 -1
- package/dist/RampsService.mjs.map +1 -1
- package/dist/TransakService.cjs +14 -3
- package/dist/TransakService.cjs.map +1 -1
- package/dist/TransakService.d.cts +2 -1
- package/dist/TransakService.d.cts.map +1 -1
- package/dist/TransakService.d.mts +2 -1
- package/dist/TransakService.d.mts.map +1 -1
- package/dist/TransakService.mjs +14 -3
- package/dist/TransakService.mjs.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RampsController.cjs","sourceRoot":"","sources":["../src/RampsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,+DAA2D;AAqC3D,qDASwB;AA6CxB,kBAAkB;AAElB;;;;GAIG;AACU,QAAA,cAAc,GAAG,iBAAiB,CAAC;AAEhD;;;;GAIG;AACU,QAAA,yCAAyC,GAGhD;IACJ,6BAA6B;IAC7B,2BAA2B;IAC3B,wBAAwB;IACxB,2BAA2B;IAC3B,gCAAgC;IAChC,wBAAwB;IACxB,8BAA8B;IAC9B,uB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AAC,EAAE,EAAE,CAAC;gBACzC,MAAM,WAAW,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;gBAClC,IAAI,WAAW,EAAE,CAAC;oBAChB,OAAO,QAAQ,CAAC,WAAW,CAAC,CAAC;gBAC/B,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC,6FAiqBuB,KAAc;IACpC,IACE,KAAK,YAAY,KAAK;QACtB,YAAY,IAAI,KAAK;QACpB,KAAwC,CAAC,UAAU,KAAK,GAAG,EAC5D,CAAC;QACD,IAAI,CAAC,uBAAuB,CAAC,KAAK,CAAC,CAAC;IACtC,CAAC;AACH,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { Json } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n Country,\n TokensResponse,\n Provider,\n State,\n RampAction,\n PaymentMethod,\n PaymentMethodsResponse,\n QuotesResponse,\n Quote,\n RampsToken,\n RampsServiceActions,\n RampsOrder,\n} from './RampsService';\nimport type {\n RampsServiceGetGeolocationAction,\n RampsServiceGetCountriesAction,\n RampsServiceGetTokensAction,\n RampsServiceGetProvidersAction,\n RampsServiceGetPaymentMethodsAction,\n RampsServiceGetQuotesAction,\n RampsServiceGetBuyWidgetUrlAction,\n RampsServiceGetOrderAction,\n RampsServiceGetOrderFromCallbackAction,\n} from './RampsService-method-action-types';\nimport type {\n RequestCache as RequestCacheType,\n RequestState,\n ExecuteRequestOptions,\n PendingRequest,\n ResourceType,\n} from './RequestCache';\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';\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';\nimport type { TransakServiceActions } from './TransakService';\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 TransakServiceSubmitPurposeOfUsageFormAction,\n TransakServicePatchUserAction,\n TransakServiceSubmitSsnDetailsAction,\n TransakServiceConfirmPaymentAction,\n TransakServiceGetTranslationAction,\n TransakServiceGetIdProofStatusAction,\n TransakServiceCancelOrderAction,\n TransakServiceCancelAllActiveOrdersAction,\n TransakServiceGetActiveOrdersAction,\n} from './TransakService-method-action-types';\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: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: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\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\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\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: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n providers: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n tokens: {\n persist: true,\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} 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 };\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 resetResource(\n state: Draft<RampsControllerState>,\n resourceType: DependentResourceKey,\n defaultResource?: RampsControllerState[DependentResourceKey],\n): void {\n const def = defaultResource ?? getDefaultRampsControllerState()[resourceType];\n const resource = state[resourceType];\n resource.data = def.data;\n resource.selected = def.selected;\n resource.isLoading = def.isLoading;\n resource.error = def.error;\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}\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 = RampsControllerGetStateAction;\n\n/**\n * Actions from other messengers that {@link RampsController} calls.\n */\ntype AllowedActions =\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 | 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 * Events that {@link RampsControllerMessenger} exposes to other consumers.\n */\nexport type RampsControllerEvents = RampsControllerStateChangeEvent;\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// === CONTROLLER DEFINITION ===\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 * 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 }\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\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\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 errorMessage = (error as Error)?.message ?? 'Unknown error';\n this.#updateRequestState(\n cacheKey,\n createErrorState(errorMessage, lastFetchedAt),\n );\n if (resourceType) {\n const isCurrent =\n !options?.isResultCurrent || options.isResultCurrent();\n if (isCurrent) {\n this.#setResourceError(resourceType, errorMessage);\n }\n }\n throw error;\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 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 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 /**\n * Executes a promise without awaiting, swallowing errors.\n * Errors are stored in state via executeRequest.\n *\n * @param promise - The promise to execute.\n */\n #fireAndForget<Result>(promise: Promise<Result>): void {\n promise.catch((_error: unknown) => undefined);\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',\n value: boolean | string | null,\n ): void {\n this.update((state) => {\n const resource = state[resourceType];\n if (resource) {\n (resource as Record<string, unknown>)[field] = value;\n }\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 error - The error message, or null to clear.\n */\n #setResourceError(resourceType: ResourceType, error: string | null): void {\n this.#updateResourceField(resourceType, 'error', error);\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 normalizedRegion !== this.state.userRegion?.regionCode;\n\n const needsRefetch =\n regionChanged ||\n !this.state.tokens.data ||\n this.state.providers.data.length === 0;\n\n if (regionChanged) {\n this.#abortDependentRequests();\n this.#clearPendingResourceCountForDependentResources();\n }\n this.update((state) => {\n if (regionChanged) {\n resetDependentResources(state);\n }\n state.userRegion = userRegion;\n });\n\n if (needsRefetch) {\n const refetchPromises: Promise<unknown>[] = [];\n if (regionChanged || !this.state.tokens.data) {\n refetchPromises.push(\n this.getTokens(userRegion.regionCode, 'buy', options),\n );\n }\n if (regionChanged || this.state.providers.data.length === 0) {\n refetchPromises.push(\n this.getProviders(userRegion.regionCode, options),\n );\n }\n if (refetchPromises.length > 0) {\n this.#fireAndForget(Promise.all(refetchPromises));\n }\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 by ID, or clears the selection.\n * Looks up the provider from the current providers in state and automatically\n * fetches payment methods for that provider.\n *\n * @param providerId - The provider ID (e.g., \"/providers/moonpay\"), or null to clear.\n * @throws If region is not set, providers are not loaded, or provider is not found.\n */\n setSelectedProvider(providerId: string | null): void {\n if (providerId === null) {\n this.update((state) => {\n state.providers.selected = null;\n resetResource(state, 'paymentMethods');\n });\n return;\n }\n\n const regionCode = this.#requireRegion();\n const providers = this.state.providers.data;\n if (!providers || providers.length === 0) {\n throw new Error(\n 'Providers not loaded. Cannot set selected provider before providers are fetched.',\n );\n }\n\n const provider = providers.find((prov) => prov.id === providerId);\n if (!provider) {\n throw new Error(\n `Provider with ID \"${providerId}\" not found in available providers.`,\n );\n }\n\n this.update((state) => {\n state.providers.selected = provider;\n resetResource(state, 'paymentMethods');\n });\n\n this.#fireAndForget(\n this.getPaymentMethods(regionCode, { provider: provider.id }),\n );\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 * If a userRegion already exists (from persistence or manual selection),\n * this method will skip geolocation fetch and use the existing region.\n *\n * @param options - Options for cache behavior.\n * @returns Promise that resolves when initialization is complete.\n */\n async init(options?: ExecuteRequestOptions): Promise<void> {\n await this.getCountries(options);\n\n let regionCode = this.state.userRegion?.regionCode;\n regionCode ??= 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 await this.setUserRegion(regionCode, options);\n }\n\n hydrateState(options?: ExecuteRequestOptions): void {\n const regionCode = this.#requireRegion();\n\n this.#fireAndForget(this.getTokens(regionCode, 'buy', options));\n this.#fireAndForget(this.getProviders(regionCode, options));\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 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 resetResource(state, 'paymentMethods');\n });\n return;\n }\n\n const regionCode = 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 resetResource(state, 'paymentMethods');\n });\n\n this.#fireAndForget(\n this.getPaymentMethods(regionCode, { assetId: token.assetId }),\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.fiat - Fiat 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 fiat?: 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?.fiat,\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 fiat: options?.fiat,\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.fiat - Fiat currency code (e.g., \"usd\"). If not provided, uses the user's region currency.\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 fiat?: string;\n assetId?: string;\n provider?: string;\n },\n ): Promise<PaymentMethodsResponse> {\n const regionCode = region ?? this.#requireRegion();\n const fiatToUse =\n options?.fiat ?? this.state.userRegion?.country?.currency ?? null;\n const assetIdToUse =\n options?.assetId ?? this.state.tokens.selected?.assetId ?? '';\n const providerToUse =\n options?.provider ?? this.state.providers.selected?.id ?? '';\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 normalizedRegion = regionCode.toLowerCase().trim();\n const normalizedFiat = fiatToUse.toLowerCase().trim();\n const cacheKey = createCacheKey('getPaymentMethods', [\n normalizedRegion,\n normalizedFiat,\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 fiat: normalizedFiat,\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 by ID.\n * Looks up the payment method from the current payment methods in state.\n *\n * @param paymentMethodId - The payment method ID (e.g., \"/payments/debit-credit-card\"), or null to clear.\n * @throws If payment methods are not loaded or payment method is not found.\n */\n setSelectedPaymentMethod(paymentMethodId?: string): void {\n if (!paymentMethodId) {\n this.update((state) => {\n state.paymentMethods.selected = null;\n });\n return;\n }\n\n const paymentMethods = this.state.paymentMethods.data;\n if (!paymentMethods || paymentMethods.length === 0) {\n throw new Error(\n 'Payment methods not loaded. Cannot set selected payment method before payment methods are fetched.',\n );\n }\n\n const paymentMethod = paymentMethods.find(\n (pm) => pm.id === paymentMethodId,\n );\n if (!paymentMethod) {\n throw new Error(\n `Payment method with ID \"${paymentMethodId}\" not found in available payment methods.`,\n );\n }\n\n this.update((state) => {\n state.paymentMethods.selected = paymentMethod;\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.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 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 providersToUse =\n options.providers ??\n this.state.providers.data.map((provider: Provider) => provider.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 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 const normalizedRegion = regionToUse.toLowerCase().trim();\n const normalizedFiat = fiatToUse.toLowerCase().trim();\n const normalizedAssetId = normalizedAssetIdForValidation;\n const normalizedWalletAddress = options.walletAddress.trim();\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 options.redirectUrl,\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: options.redirectUrl,\n action,\n };\n\n return 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\n /**\n * Cleans up controller resources.\n * Should be called when the controller is no longer needed.\n */\n override destroy(): void {\n super.destroy();\n }\n\n /**\n * Fetches the widget URL 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.\n *\n * @param quote - The quote to fetch the widget URL from.\n * @returns Promise resolving to the widget URL string, or null if not available.\n */\n async getWidgetUrl(quote: Quote): Promise<string | null> {\n const buyUrl = quote.quote?.buyURL;\n if (!buyUrl) {\n return null;\n }\n\n try {\n const buyWidget = await this.messenger.call(\n 'RampsService:getBuyWidgetUrl',\n buyUrl,\n );\n return buyWidget.url ?? null;\n } catch {\n return null;\n }\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 return await this.messenger.call(\n 'RampsService:getOrder',\n providerCode,\n orderCode,\n wallet,\n );\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 return await this.messenger.call(\n 'RampsService:getOrderFromCallback',\n providerCode,\n callbackUrl,\n wallet,\n );\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 (\n error instanceof Error &&\n 'httpStatus' in error &&\n (error as Error & { httpStatus: number }).httpStatus === 401\n ) {\n this.transakSetAuthenticated(false);\n }\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 return this.messenger.call('TransakService:sendUserOtp', email);\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 const token = await this.messenger.call(\n 'TransakService:verifyUserOtp',\n email,\n verificationCode,\n stateToken,\n );\n this.transakSetAuthenticated(true);\n return token;\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 const result = await this.messenger.call('TransakService:logout');\n return result;\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 });\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 this.#syncTransakAuthOnError(error);\n const errorMessage = (error as Error)?.message ?? 'Unknown error';\n this.update((state) => {\n state.nativeProviders.transak.userDetails.isLoading = false;\n state.nativeProviders.transak.userDetails.error = errorMessage;\n });\n throw error;\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 });\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 errorMessage = (error as Error)?.message ?? 'Unknown error';\n this.update((state) => {\n state.nativeProviders.transak.buyQuote.isLoading = false;\n state.nativeProviders.transak.buyQuote.error = errorMessage;\n });\n throw error;\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 });\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 this.#syncTransakAuthOnError(error);\n const errorMessage = (error as Error)?.message ?? 'Unknown error';\n this.update((state) => {\n state.nativeProviders.transak.kycRequirement.isLoading = false;\n state.nativeProviders.transak.kycRequirement.error = errorMessage;\n });\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 return this.messenger.call(\n 'TransakService:getOrder',\n orderId,\n wallet,\n paymentDetails,\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 * 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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 return this.messenger.call('TransakService:getTranslation', request);\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"RampsController.cjs","sourceRoot":"","sources":["../src/RampsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,+DAA2D;AAmB3D,qDAAkD;AAmBlD,qDASwB;AA6CxB,kBAAkB;AAElB;;;;GAIG;AACU,QAAA,cAAc,GAAG,iBAAiB,CAAC;AAEhD;;;;GAIG;AACU,QAAA,yCAAyC,GAGhD;IACJ,6BAA6B;IAC7B,2BAA2B;IAC3B,wBAAwB;IACxB,2BAA2B;IAC3B,gCAAgC;IAChC,wBAAwB;IACxB,8BAA8B;IAC9B,uBAAuB;IACvB,mCAAmC;IACnC,0BAA0B;IAC1B,+BAA+B;IAC/B,iCAAiC;IACjC,4BAA4B;IAC5B,8BAA8B;IAC9B,uBAAuB;IACvB,+BAA+B;IAC/B,4BAA4B;IAC5B,kCAAkC;IAClC,0CAA0C;IAC1C,4BAA4B;IAC5B,yBAAyB;IACzB,8BAA8B;IAC9B,2BAA2B;IAC3B,yCAAyC;IACzC,yCAAyC;IACzC,0BAA0B;IAC1B,iCAAiC;IACjC,+BAA+B;IAC/B,+BAA+B;IAC/B,iCAAiC;IACjC,4BAA4B;IAC5B,sCAAsC;IACtC,gCAAgC;CACjC,CAAC;AAEF;;;GAGG;AACH,MAAM,kBAAkB,GAAG,KAAK,CAAC;AAkHjC;;GAEG;AACH,MAAM,uBAAuB,GAAG;IAC9B,UAAU,EAAE;QACV,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,kBAAkB,EAAE,IAAI;QACxB,QAAQ,EAAE,IAAI;KACf;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CAAC;IACJ,CAAC;YAAS,CAAC;QACT,uBAAA,IAAI,8BAAc,KAAK,MAAA,CAAC;IAC1B,CAAC;AACH,CAAC,6FA8GuB,KAAc;IACpC,IACE,KAAK,YAAY,KAAK;QACtB,YAAY,IAAI,KAAK;QACpB,KAAwC,CAAC,UAAU,KAAK,GAAG,EAC5D,CAAC;QACD,IAAI,CAAC,uBAAuB,CAAC,KAAK,CAAC,CAAC;IACtC,CAAC;AACH,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { Json } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n Country,\n TokensResponse,\n Provider,\n State,\n RampAction,\n PaymentMethod,\n PaymentMethodsResponse,\n QuotesResponse,\n Quote,\n RampsToken,\n RampsServiceActions,\n RampsOrder,\n} from './RampsService';\nimport { RampsOrderStatus } from './RampsService';\nimport type {\n RampsServiceGetGeolocationAction,\n RampsServiceGetCountriesAction,\n RampsServiceGetTokensAction,\n RampsServiceGetProvidersAction,\n RampsServiceGetPaymentMethodsAction,\n RampsServiceGetQuotesAction,\n RampsServiceGetBuyWidgetUrlAction,\n RampsServiceGetOrderAction,\n RampsServiceGetOrderFromCallbackAction,\n} from './RampsService-method-action-types';\nimport type {\n RequestCache as RequestCacheType,\n RequestState,\n ExecuteRequestOptions,\n PendingRequest,\n ResourceType,\n} from './RequestCache';\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';\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';\nimport type { TransakServiceActions } from './TransakService';\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 TransakServiceSubmitPurposeOfUsageFormAction,\n TransakServicePatchUserAction,\n TransakServiceSubmitSsnDetailsAction,\n TransakServiceConfirmPaymentAction,\n TransakServiceGetTranslationAction,\n TransakServiceGetIdProofStatusAction,\n TransakServiceCancelOrderAction,\n TransakServiceCancelAllActiveOrdersAction,\n TransakServiceGetActiveOrdersAction,\n} from './TransakService-method-action-types';\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: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: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\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\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 * V2 orders stored directly as RampsOrder[].\n * The controller is the authority for V2 orders — it polls, updates,\n * and persists them. No FiatOrder wrapper needed.\n */\n orders: RampsOrder[];\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: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n providers: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n tokens: {\n persist: true,\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} 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 };\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 resetResource(\n state: Draft<RampsControllerState>,\n resourceType: DependentResourceKey,\n defaultResource?: RampsControllerState[DependentResourceKey],\n): void {\n const def = defaultResource ?? getDefaultRampsControllerState()[resourceType];\n const resource = state[resourceType];\n resource.data = def.data;\n resource.selected = def.selected;\n resource.isLoading = def.isLoading;\n resource.error = def.error;\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}\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 * Sets selected token in the {@link RampsController}.\n */\nexport type RampsControllerSetSelectedTokenAction = {\n type: 'RampsController:setSelectedToken';\n handler: RampsController['setSelectedToken'];\n};\n\n/**\n * Fetches quotes via the {@link RampsController}.\n */\nexport type RampsControllerGetQuotesAction = {\n type: 'RampsController:getQuotes';\n handler: RampsController['getQuotes'];\n};\n\n/**\n * Fetches an order via the {@link RampsController}.\n */\nexport type RampsControllerGetOrderAction = {\n type: 'RampsController:getOrder';\n handler: RampsController['getOrder'];\n};\n\n/**\n * Actions that {@link RampsControllerMessenger} exposes to other consumers.\n */\nexport type RampsControllerActions =\n | RampsControllerGetStateAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuotesAction\n | RampsControllerSetSelectedTokenAction;\n\n/**\n * Actions from other messengers that {@link RampsController} calls.\n */\ntype AllowedActions =\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 | 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// === 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\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 readonly #orderPollingMeta: Map<string, OrderPollingMetadata> = new Map();\n\n #orderPollingTimer: ReturnType<typeof setInterval> | null = null;\n\n #isPolling = false;\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 }\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.#registerActionHandlers();\n }\n\n #registerActionHandlers(): void {\n this.messenger.registerActionHandler(\n 'RampsController:getOrder',\n this.getOrder.bind(this),\n );\n this.messenger.registerActionHandler(\n 'RampsController:getQuotes',\n this.getQuotes.bind(this),\n );\n this.messenger.registerActionHandler(\n 'RampsController:setSelectedToken',\n this.setSelectedToken.bind(this),\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\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 errorMessage = (error as Error)?.message ?? 'Unknown error';\n this.#updateRequestState(\n cacheKey,\n createErrorState(errorMessage, lastFetchedAt),\n );\n if (resourceType) {\n const isCurrent =\n !options?.isResultCurrent || options.isResultCurrent();\n if (isCurrent) {\n this.#setResourceError(resourceType, errorMessage);\n }\n }\n throw error;\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 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 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 /**\n * Executes a promise without awaiting, swallowing errors.\n * Errors are stored in state via executeRequest.\n *\n * @param promise - The promise to execute.\n */\n #fireAndForget<Result>(promise: Promise<Result>): void {\n promise.catch((_error: unknown) => undefined);\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',\n value: boolean | string | null,\n ): void {\n this.update((state) => {\n const resource = state[resourceType];\n if (resource) {\n (resource as Record<string, unknown>)[field] = value;\n }\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 error - The error message, or null to clear.\n */\n #setResourceError(resourceType: ResourceType, error: string | null): void {\n this.#updateResourceField(resourceType, 'error', error);\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 normalizedRegion !== this.state.userRegion?.regionCode;\n\n const needsRefetch =\n regionChanged ||\n !this.state.tokens.data ||\n this.state.providers.data.length === 0;\n\n if (regionChanged) {\n this.#abortDependentRequests();\n this.#clearPendingResourceCountForDependentResources();\n }\n this.update((state) => {\n if (regionChanged) {\n resetDependentResources(state);\n }\n state.userRegion = userRegion;\n });\n\n if (needsRefetch) {\n const refetchPromises: Promise<unknown>[] = [];\n if (regionChanged || !this.state.tokens.data) {\n refetchPromises.push(\n this.getTokens(userRegion.regionCode, 'buy', options),\n );\n }\n if (regionChanged || this.state.providers.data.length === 0) {\n refetchPromises.push(\n this.getProviders(userRegion.regionCode, options),\n );\n }\n if (refetchPromises.length > 0) {\n this.#fireAndForget(Promise.all(refetchPromises));\n }\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 by ID, or clears the selection.\n * Looks up the provider from the current providers in state and automatically\n * fetches payment methods for that provider.\n *\n * @param providerId - The provider ID (e.g., \"/providers/moonpay\"), or null to clear.\n * @throws If region is not set, providers are not loaded, or provider is not found.\n */\n setSelectedProvider(providerId: string | null): void {\n if (providerId === null) {\n this.update((state) => {\n state.providers.selected = null;\n resetResource(state, 'paymentMethods');\n });\n return;\n }\n\n const regionCode = this.#requireRegion();\n const providers = this.state.providers.data;\n if (!providers || providers.length === 0) {\n throw new Error(\n 'Providers not loaded. Cannot set selected provider before providers are fetched.',\n );\n }\n\n const provider = providers.find((prov) => prov.id === providerId);\n if (!provider) {\n throw new Error(\n `Provider with ID \"${providerId}\" not found in available providers.`,\n );\n }\n\n const selectedToken = this.state.tokens.selected;\n const supportedCryptos = provider.supportedCryptoCurrencies;\n\n // Only fetch payment methods if the selected token is supported by the new\n // provider. If it isn't, the payment methods request would fail or return\n // empty for the wrong reason; the UI will show the Token Not Available modal\n // so the user can change token or pick a different provider.\n const assetId = selectedToken?.assetId;\n const tokenSupportedByProvider = !(\n assetId && supportedCryptos?.[assetId] === false\n );\n\n this.update((state) => {\n state.providers.selected = provider;\n resetResource(state, 'paymentMethods');\n });\n\n if (tokenSupportedByProvider) {\n this.#fireAndForget(\n this.getPaymentMethods(regionCode, { provider: provider.id }),\n );\n }\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 * If a userRegion already exists (from persistence or manual selection),\n * this method will skip geolocation fetch and use the existing region.\n *\n * @param options - Options for cache behavior.\n * @returns Promise that resolves when initialization is complete.\n */\n async init(options?: ExecuteRequestOptions): Promise<void> {\n await this.getCountries(options);\n\n let regionCode = this.state.userRegion?.regionCode;\n regionCode ??= 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 await this.setUserRegion(regionCode, options);\n }\n\n hydrateState(options?: ExecuteRequestOptions): void {\n const regionCode = this.#requireRegion();\n\n this.#fireAndForget(this.getTokens(regionCode, 'buy', options));\n this.#fireAndForget(this.getProviders(regionCode, options));\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 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 resetResource(state, 'paymentMethods');\n });\n return;\n }\n\n const regionCode = 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 resetResource(state, 'paymentMethods');\n });\n\n this.#fireAndForget(\n this.getPaymentMethods(regionCode, { assetId: token.assetId }),\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.fiat - Fiat 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 fiat?: 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?.fiat,\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 fiat: options?.fiat,\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.fiat - Fiat currency code (e.g., \"usd\"). If not provided, uses the user's region currency.\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 fiat?: string;\n assetId?: string;\n provider?: string;\n },\n ): Promise<PaymentMethodsResponse> {\n const regionCode = region ?? this.#requireRegion();\n const fiatToUse =\n options?.fiat ?? this.state.userRegion?.country?.currency ?? null;\n const assetIdToUse =\n options?.assetId ?? this.state.tokens.selected?.assetId ?? '';\n const providerToUse =\n options?.provider ?? this.state.providers.selected?.id ?? '';\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 normalizedRegion = regionCode.toLowerCase().trim();\n const normalizedFiat = fiatToUse.toLowerCase().trim();\n const cacheKey = createCacheKey('getPaymentMethods', [\n normalizedRegion,\n normalizedFiat,\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 fiat: normalizedFiat,\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 by ID.\n * Looks up the payment method from the current payment methods in state.\n *\n * @param paymentMethodId - The payment method ID (e.g., \"/payments/debit-credit-card\"), or null to clear.\n * @throws If payment methods are not loaded or payment method is not found.\n */\n setSelectedPaymentMethod(paymentMethodId?: string): void {\n if (!paymentMethodId) {\n this.update((state) => {\n state.paymentMethods.selected = null;\n });\n return;\n }\n\n const paymentMethods = this.state.paymentMethods.data;\n if (!paymentMethods || paymentMethods.length === 0) {\n throw new Error(\n 'Payment methods not loaded. Cannot set selected payment method before payment methods are fetched.',\n );\n }\n\n const paymentMethod = paymentMethods.find(\n (pm) => pm.id === paymentMethodId,\n );\n if (!paymentMethod) {\n throw new Error(\n `Payment method with ID \"${paymentMethodId}\" not found in available payment methods.`,\n );\n }\n\n this.update((state) => {\n state.paymentMethods.selected = paymentMethod;\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.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 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 providersToUse =\n options.providers ??\n this.state.providers.data.map((provider: Provider) => provider.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 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 const normalizedRegion = regionToUse.toLowerCase().trim();\n const normalizedFiat = fiatToUse.toLowerCase().trim();\n const normalizedAssetId = normalizedAssetIdForValidation;\n const normalizedWalletAddress = options.walletAddress.trim();\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 options.redirectUrl,\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: options.redirectUrl,\n action,\n };\n\n return 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\n // === ORDER MANAGEMENT ===\n\n /**\n * Adds or updates a V2 order in controller state.\n * If an order with the same providerOrderId 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 this.update((state) => {\n const idx = state.orders.findIndex(\n (existing) => existing.providerOrderId === order.providerOrderId,\n );\n if (idx === -1) {\n state.orders.push(order as Draft<RampsOrder>);\n } else {\n state.orders[idx] = {\n ...state.orders[idx],\n ...order,\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 providerCodeSegment = providerCode.replace('/providers/', '');\n const previousStatus = order.status;\n\n try {\n const updatedOrder = await this.getOrder(\n providerCodeSegment,\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 URL 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.\n *\n * @param quote - The quote to fetch the widget URL from.\n * @returns Promise resolving to the widget URL string, or null if not available.\n */\n async getWidgetUrl(quote: Quote): Promise<string | null> {\n const buyUrl = quote.quote?.buyURL;\n if (!buyUrl) {\n return null;\n }\n\n try {\n const buyWidget = await this.messenger.call(\n 'RampsService:getBuyWidgetUrl',\n buyUrl,\n );\n return buyWidget.url ?? null;\n } catch {\n return null;\n }\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 this.update((state) => {\n const idx = state.orders.findIndex(\n (existing) => existing.providerOrderId === orderCode,\n );\n if (idx !== -1) {\n state.orders[idx] = {\n ...state.orders[idx],\n ...order,\n } as Draft<RampsOrder>;\n }\n });\n\n return order;\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 return await this.messenger.call(\n 'RampsService:getOrderFromCallback',\n providerCode,\n callbackUrl,\n wallet,\n );\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 (\n error instanceof Error &&\n 'httpStatus' in error &&\n (error as Error & { httpStatus: number }).httpStatus === 401\n ) {\n this.transakSetAuthenticated(false);\n }\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 return this.messenger.call('TransakService:sendUserOtp', email);\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 const token = await this.messenger.call(\n 'TransakService:verifyUserOtp',\n email,\n verificationCode,\n stateToken,\n );\n this.transakSetAuthenticated(true);\n return token;\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 const result = await this.messenger.call('TransakService:logout');\n return result;\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 });\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 this.#syncTransakAuthOnError(error);\n const errorMessage = (error as Error)?.message ?? 'Unknown error';\n this.update((state) => {\n state.nativeProviders.transak.userDetails.isLoading = false;\n state.nativeProviders.transak.userDetails.error = errorMessage;\n });\n throw error;\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 });\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 errorMessage = (error as Error)?.message ?? 'Unknown error';\n this.update((state) => {\n state.nativeProviders.transak.buyQuote.isLoading = false;\n state.nativeProviders.transak.buyQuote.error = errorMessage;\n });\n throw error;\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 });\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 this.#syncTransakAuthOnError(error);\n const errorMessage = (error as Error)?.message ?? 'Unknown error';\n this.update((state) => {\n state.nativeProviders.transak.kycRequirement.isLoading = false;\n state.nativeProviders.transak.kycRequirement.error = errorMessage;\n });\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 return this.messenger.call(\n 'TransakService:getOrder',\n orderId,\n wallet,\n paymentDetails,\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 * 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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 return this.messenger.call('TransakService:getTranslation', request);\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\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 this.#syncTransakAuthOnError(error);\n throw error;\n }\n }\n}\n"]}
|