@metamask/ramps-controller 9.0.0 → 10.1.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 +31 -1
- package/dist/RampsController.cjs +165 -200
- package/dist/RampsController.cjs.map +1 -1
- package/dist/RampsController.d.cts +61 -44
- package/dist/RampsController.d.cts.map +1 -1
- package/dist/RampsController.d.mts +61 -44
- package/dist/RampsController.d.mts.map +1 -1
- package/dist/RampsController.mjs +165 -200
- 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/RequestCache.cjs.map +1 -1
- package/dist/RequestCache.d.cts +1 -1
- package/dist/RequestCache.d.cts.map +1 -1
- package/dist/RequestCache.d.mts +1 -1
- package/dist/RequestCache.d.mts.map +1 -1
- package/dist/RequestCache.mjs.map +1 -1
- package/dist/TransakService.cjs +29 -16
- 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 +29 -16
- 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 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RampsService.mjs","sourceRoot":"","sources":["../src/RampsService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,mCAAmC;AAI5E,OAAO,WAAW,8CAAwB;AAwe1C,sBAAs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AwB,EACxB,IAAY,EACZ,OAGC;IAED,OAAO,uBAAA,IAAI,4BAAQ,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE;QACrC,MAAM,OAAO,GAAG,uBAAA,IAAI,yDAAY,MAAhB,IAAI,EAAa,OAAO,CAAC,CAAC;QAC1C,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACnC,uBAAA,IAAI,8DAAiB,MAArB,IAAI,EAAkB,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;QAE3C,MAAM,QAAQ,GAAG,MAAM,uBAAA,IAAI,2BAAO,MAAX,IAAI,EAAQ,GAAG,CAAC,CAAC;QACxC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,SAAS,CACjB,QAAQ,CAAC,MAAM,EACf,aAAa,GAAG,CAAC,QAAQ,EAAE,yBAAyB,QAAQ,CAAC,MAAM,GAAG,CACvE,CAAC;QACJ,CAAC;QAED,OAAO,OAAO,CAAC,YAAY,KAAK,MAAM;YACpC,CAAC,CAAE,QAAQ,CAAC,IAAI,EAAyB;YACzC,CAAC,CAAE,QAAQ,CAAC,IAAI,EAAyB,CAAC;IAC9C,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport { createServicePolicy, HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\n\nimport type { RampsServiceMethodActions } from './RampsService-method-action-types';\nimport packageJson from '../package.json';\n\n/**\n * Represents phone number information for a country.\n */\nexport type CountryPhone = {\n prefix: string;\n placeholder: string;\n template: string;\n};\n\n/**\n * Indicates whether a region supports buy and/or sell actions.\n */\nexport type SupportedActions = {\n /**\n * Whether buy actions are supported.\n */\n buy: boolean;\n /**\n * Whether sell actions are supported.\n */\n sell: boolean;\n};\n\n/**\n * Represents a state/province within a country.\n */\nexport type State = {\n /**\n * State identifier. Can be in path format (e.g., \"/regions/us-ut\") or ISO code format (e.g., \"us-ut\").\n */\n id?: string;\n /**\n * State name.\n */\n name?: string;\n /**\n * ISO state code (e.g., \"UT\", \"NY\").\n */\n stateId?: string;\n /**\n * Whether this state is supported for buy and/or sell ramp actions.\n */\n supported?: SupportedActions;\n /**\n * Whether this state is recommended.\n */\n recommended?: boolean;\n};\n\n/**\n * Represents a provider link.\n */\nexport type ProviderLink = {\n name: string;\n url: string;\n};\n\n/**\n * Represents provider logos.\n */\nexport type ProviderLogos = {\n light: string;\n dark: string;\n height: number;\n width: number;\n};\n\n/**\n * Browser type for provider buy features.\n */\nexport type ProviderBrowserType = 'APP_BROWSER' | 'IN_APP_OS_BROWSER' | null;\n\n/**\n * Represents a ramp provider.\n */\nexport type Provider = {\n id: string;\n name: string;\n environmentType: string;\n description: string;\n hqAddress: string;\n links: ProviderLink[];\n logos: ProviderLogos;\n supportedCryptoCurrencies?: Record<string, boolean>;\n supportedFiatCurrencies?: Record<string, boolean>;\n supportedPaymentMethods?: Record<string, boolean>;\n};\n\n/**\n * Represents a payment method for funding a purchase.\n */\nexport type PaymentMethod = {\n /**\n * Canonical payment method ID (e.g., \"/payments/debit-credit-card\").\n */\n id: string;\n /**\n * Payment type identifier (e.g., \"debit-credit-card\", \"bank-transfer\").\n */\n paymentType: string;\n /**\n * User-facing name for the payment method.\n */\n name: string;\n /**\n * Score for sorting payment methods (higher is better).\n */\n score: number;\n /**\n * Icon identifier for the payment method.\n */\n icon: string;\n /**\n * Localized disclaimer text (optional).\n */\n disclaimer?: string;\n /**\n * Delay in minutes (e.g., [5, 10]).\n */\n delay?: number[];\n /**\n * Localized pending order description (optional).\n */\n pendingOrderDescription?: string;\n /**\n * Whether this payment method is a manual bank transfer.\n */\n isManualBankTransfer?: boolean;\n};\n\n/**\n * Response from the paymentMethods API.\n */\nexport type PaymentMethodsResponse = {\n /**\n * List of available payment methods.\n */\n payments: PaymentMethod[];\n /**\n * Recommended sorting for payment methods.\n */\n sort?: {\n ids: string[];\n sortBy: string;\n };\n};\n\n// === QUOTES TYPES ===\n\n/**\n * Sort criteria for quotes.\n */\nexport type QuoteSortBy = 'price' | 'reliability';\n\n/**\n * Represents crypto translation info for a quote.\n */\nexport type QuoteCryptoTranslation = {\n /**\n * The crypto currency ID.\n */\n id?: string;\n /**\n * The crypto symbol.\n */\n symbol?: string;\n /**\n * The chain ID.\n */\n chainId?: string;\n};\n\n/**\n * Widget information for executing a buy order.\n */\nexport type BuyWidget = {\n /**\n * The widget URL to open for the user to complete the purchase.\n */\n url: string;\n /**\n * The browser type to use for opening the widget.\n */\n browser?: ProviderBrowserType;\n /**\n * Order ID if already created.\n */\n orderId?: string | null;\n};\n\n/**\n * Represents an individual quote from a provider.\n */\nexport type Quote = {\n /**\n * The provider ID (e.g., \"/providers/moonpay\").\n */\n provider: string;\n /**\n * The quote details.\n */\n quote: {\n /**\n * The amount the user is paying (in fiat for buy, crypto for sell).\n */\n amountIn: number | string;\n /**\n * The amount the user will receive (in crypto for buy, fiat for sell).\n */\n amountOut: number | string;\n /**\n * The payment method used for this quote.\n */\n paymentMethod: string;\n /**\n * The fiat value of the output amount (for buy actions).\n */\n amountOutInFiat?: number;\n /**\n * Crypto translation info for display.\n */\n cryptoTranslation?: QuoteCryptoTranslation;\n /**\n * Total fees in the source currency.\n */\n totalFees?: number | string;\n /**\n * Network fees.\n */\n networkFee?: number | string;\n /**\n * Provider fees.\n */\n providerFee?: number | string;\n /**\n * Buy URL endpoint that returns the actual provider widget URL.\n *\n * This is a MetaMask-hosted endpoint that, when fetched, returns JSON with the provider's widget URL.\n *\n * @deprecated Use buyWidget instead - it's embedded in the quote response.\n */\n buyURL?: string;\n /**\n * Widget information embedded in the quote response.\n * Contains the widget URL, browser type, and optional pre-order tracking ID.\n */\n buyWidget?: BuyWidget;\n };\n /**\n * Metadata about the quote.\n */\n metadata?: {\n /**\n * Reliability score for the provider (0-100).\n */\n reliability?: number;\n /**\n * Tags for the quote.\n */\n tags?: {\n /**\n * Whether this is the best rate quote.\n */\n isBestRate?: boolean;\n /**\n * Whether this is the most reliable provider.\n */\n isMostReliable?: boolean;\n };\n };\n};\n\n/**\n * Represents an error from a provider when fetching quotes.\n */\nexport type QuoteError = {\n /**\n * The provider ID that failed.\n */\n provider: string;\n /**\n * Error message.\n */\n error?: string;\n};\n\n/**\n * Sort order information for quotes.\n */\nexport type QuoteSortOrder = {\n /**\n * The sort criteria.\n */\n sortBy: QuoteSortBy;\n /**\n * Provider IDs in sorted order.\n */\n ids: string[];\n};\n\n/**\n * Custom action for a provider (e.g., Apple Pay).\n */\nexport type QuoteCustomAction = {\n /**\n * Buy action details.\n */\n buy: {\n /**\n * Provider ID.\n */\n providerId: string;\n };\n /**\n * Payment method ID this action applies to.\n */\n paymentMethodId: string;\n /**\n * Supported payment method IDs.\n */\n supportedPaymentMethodIds: string[];\n};\n\n/**\n * Response from the quotes API.\n */\nexport type QuotesResponse = {\n /**\n * Successfully retrieved quotes.\n */\n success: Quote[];\n /**\n * Sort orders for the quotes.\n */\n sorted: QuoteSortOrder[];\n /**\n * Errors from providers that failed to return quotes.\n */\n error: QuoteError[];\n /**\n * Custom actions available from providers.\n */\n customActions: QuoteCustomAction[];\n};\n\n/**\n * Parameters for fetching quotes.\n */\nexport type GetQuotesParams = {\n /**\n * The region code (e.g., \"us\", \"us-ca\").\n */\n region: string;\n /**\n * Array of payment method IDs to get quotes for.\n */\n paymentMethods: string[];\n /**\n * The CAIP-19 asset ID (e.g., \"eip155:1/erc20:0x...\").\n */\n assetId: string;\n /**\n * The fiat currency code (e.g., \"usd\").\n */\n fiat: string;\n /**\n * The amount (in fiat for buy, crypto for sell).\n */\n amount: number;\n /**\n * The destination wallet address.\n */\n walletAddress: string;\n /**\n * Optional redirect URL after order completion.\n */\n redirectUrl?: string;\n /**\n * Optional provider IDs to filter quotes.\n */\n providers?: string[];\n /**\n * The ramp action type. Defaults to 'buy'.\n */\n action?: RampAction;\n};\n\n/**\n * Represents a country returned from the regions/countries API.\n */\nexport type Country = {\n /**\n * ISO-2 country code (e.g., \"US\", \"GB\").\n */\n isoCode: string;\n /**\n * Country identifier. Can be in path format (e.g., \"/regions/us\") or ISO code format.\n * If not provided, defaults to isoCode.\n */\n id?: string;\n /**\n * Country flag emoji or code.\n */\n flag: string;\n /**\n * Country name.\n */\n name: string;\n /**\n * Phone number information.\n */\n phone: CountryPhone;\n /**\n * Default currency code.\n */\n currency: string;\n /**\n * Whether this country is supported for buy and/or sell ramp actions.\n */\n supported: SupportedActions;\n /**\n * Whether this country is recommended.\n */\n recommended?: boolean;\n /**\n * Array of state objects.\n */\n states?: State[];\n /**\n * Default amount for ramps transactions.\n */\n defaultAmount?: number;\n /**\n * Quick amount options for ramps transactions.\n */\n quickAmounts?: number[];\n};\n\n/**\n * Represents a token returned from the regions/{region}/tokens API.\n */\nexport type RampsToken = {\n /**\n * The asset identifier in CAIP-19 format (e.g., \"eip155:1/erc20:0x...\").\n */\n assetId: string;\n /**\n * The chain identifier in CAIP-2 format (e.g., \"eip155:1\").\n */\n chainId: string;\n /**\n * Token name (e.g., \"USD Coin\").\n */\n name: string;\n /**\n * Token symbol (e.g., \"USDC\").\n */\n symbol: string;\n /**\n * Number of decimals for the token.\n */\n decimals: number;\n /**\n * URL to the token icon.\n */\n iconUrl: string;\n /**\n * Whether this token is supported.\n */\n tokenSupported: boolean;\n};\n\n/**\n * Response from the regions/{region}/tokens API.\n */\nexport type TokensResponse = {\n /**\n * Top/popular tokens for the region.\n */\n topTokens: RampsToken[];\n /**\n * All available tokens for the region.\n */\n allTokens: RampsToken[];\n};\n\n// === ORDER TYPES ===\n\n/**\n * Possible statuses for a ramps order.\n */\nexport enum RampsOrderStatus {\n Unknown = 'UNKNOWN',\n Precreated = 'PRECREATED',\n Created = 'CREATED',\n Pending = 'PENDING',\n Failed = 'FAILED',\n Completed = 'COMPLETED',\n Cancelled = 'CANCELLED',\n IdExpired = 'ID_EXPIRED',\n}\n\n/**\n * Network information associated with an order.\n */\nexport type RampsOrderNetwork = {\n name: string;\n chainId: string;\n};\n\n/**\n * Crypto currency information associated with an order.\n */\nexport type RampsOrderCryptoCurrency = {\n assetId?: string;\n name?: string;\n chainId?: string;\n decimals?: number;\n iconUrl?: string;\n symbol: string;\n};\n\n/**\n * Payment method information associated with an order.\n */\nexport type RampsOrderPaymentMethod = {\n id: string;\n name?: string;\n shortName?: string;\n duration?: string;\n icon?: string;\n isManualBankTransfer?: boolean;\n};\n\n/**\n * Fiat currency information associated with an order.\n */\nexport type RampsOrderFiatCurrency = {\n id?: string;\n symbol: string;\n name?: string;\n decimals?: number;\n denomSymbol?: string;\n};\n\n/**\n * A unified order type returned from the V2 API.\n * The V2 endpoint normalizes all provider responses into this shape.\n */\nexport type RampsOrder = {\n id?: string;\n isOnlyLink: boolean;\n provider?: Provider;\n success: boolean;\n cryptoAmount: string | number;\n fiatAmount: number;\n cryptoCurrency?: RampsOrderCryptoCurrency;\n fiatCurrency?: RampsOrderFiatCurrency;\n providerOrderId: string;\n providerOrderLink: string;\n createdAt: number;\n paymentMethod?: RampsOrderPaymentMethod;\n totalFeesFiat: number;\n txHash: string;\n walletAddress: string;\n status: RampsOrderStatus;\n network: RampsOrderNetwork;\n canBeUpdated: boolean;\n idHasExpired: boolean;\n idExpirationDate?: number;\n excludeFromPurchases: boolean;\n timeDescriptionPending: string;\n fiatAmountInUsd?: number;\n feesInUsd?: number;\n region?: string;\n orderType: string;\n exchangeRate?: number;\n pollingSecondsMinimum?: number;\n statusDescription?: string;\n partnerFees?: number;\n networkFees?: number;\n};\n\n/**\n * The SDK version to send with API requests. (backwards-compatibility)\n */\nexport const RAMPS_SDK_VERSION = '2.1.6';\n\n/**\n * The type of ramp action: 'buy' or 'sell'.\n */\nexport type RampAction = 'buy' | 'sell';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link RampsService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'RampsService';\n\n/**\n * The environment to use for API requests.\n */\nexport enum RampsEnvironment {\n Production = 'production',\n Staging = 'staging',\n Development = 'development',\n Local = 'local',\n}\n\n/**\n * The type of ramps API service.\n * Determines which base URL to use (cache vs standard).\n */\nexport enum RampsApiService {\n Regions = 'regions',\n Orders = 'orders',\n}\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getGeolocation',\n 'getCountries',\n 'getTokens',\n 'getProviders',\n 'getPaymentMethods',\n 'getQuotes',\n 'getBuyWidgetUrl',\n 'getOrder',\n 'getOrderFromCallback',\n] as const;\n\n/**\n * Actions that {@link RampsService} exposes to other consumers.\n */\nexport type RampsServiceActions = RampsServiceMethodActions;\n\n/**\n * Actions from other messengers that {@link RampsService} calls.\n */\ntype AllowedActions = never;\n\n/**\n * Events that {@link RampsService} exposes to other consumers.\n */\nexport type RampsServiceEvents = never;\n\n/**\n * Events from other messengers that {@link RampsService} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link RampsService}.\n */\nexport type RampsServiceMessenger = Messenger<\n typeof serviceName,\n RampsServiceActions | AllowedActions,\n RampsServiceEvents | AllowedEvents\n>;\n\n// === SERVICE DEFINITION ===\n\n/**\n * Gets the base URL for API requests based on the environment and service type.\n * The Regions service uses a cache URL, while other services use the standard URL.\n *\n * @param environment - The environment to use.\n * @param service - The API service type (determines if cache URL is used).\n * @returns The base URL for API requests.\n */\nfunction getBaseUrl(\n environment: RampsEnvironment,\n service: RampsApiService,\n): string {\n const cache = service === RampsApiService.Regions ? '-cache' : '';\n\n switch (environment) {\n case RampsEnvironment.Production:\n return `https://on-ramp${cache}.api.cx.metamask.io`;\n case RampsEnvironment.Staging:\n case RampsEnvironment.Development:\n return `https://on-ramp${cache}.uat-api.cx.metamask.io`;\n case RampsEnvironment.Local:\n return 'http://localhost:3000';\n default:\n throw new Error(`Invalid environment: ${String(environment)}`);\n }\n}\n\n/**\n * Constructs an API path with a version prefix.\n *\n * @param path - The API endpoint path.\n * @param version - The API version prefix. Defaults to 'v2'.\n * @returns The versioned API path.\n */\nfunction getApiPath(path: string, version: string = 'v2'): string {\n return `${version}/${path}`;\n}\n\n/**\n * This service object is responsible for interacting with the Ramps API.\n *\n * @example\n *\n * ``` ts\n * import { Messenger } from '@metamask/messenger';\n * import type {\n * RampsServiceActions,\n * RampsServiceEvents,\n * } from '@metamask/ramps-controller';\n *\n * const rootMessenger = new Messenger<\n * 'Root',\n * RampsServiceActions\n * RampsServiceEvents\n * >({ namespace: 'Root' });\n * const rampsServiceMessenger = new Messenger<\n * 'RampsService',\n * RampsServiceActions,\n * RampsServiceEvents,\n * typeof rootMessenger,\n * >({\n * namespace: 'RampsService',\n * parent: rootMessenger,\n * });\n * // Instantiate the service to register its actions on the messenger\n * new RampsService({\n * messenger: rampsServiceMessenger,\n * environment: RampsEnvironment.Production,\n * context: 'mobile-ios',\n * fetch,\n * });\n *\n * // Later...\n * // Get the user's geolocation\n * const geolocation = await rootMessenger.call(\n * 'RampsService:getGeolocation',\n * );\n * // ... Do something with the geolocation ...\n * ```\n */\nexport class RampsService {\n /**\n * The name of the service.\n */\n readonly name: typeof serviceName;\n\n /**\n * The messenger suited for this service.\n */\n readonly #messenger: ConstructorParameters<\n typeof RampsService\n >[0]['messenger'];\n\n /**\n * A function that can be used to make an HTTP request.\n */\n readonly #fetch: ConstructorParameters<typeof RampsService>[0]['fetch'];\n\n /**\n * The policy that wraps the request.\n *\n * @see {@link createServicePolicy}\n */\n readonly #policy: ServicePolicy;\n\n /**\n * The environment used for API requests.\n */\n readonly #environment: RampsEnvironment;\n\n /**\n * The context for API requests (e.g., 'mobile-ios', 'mobile-android').\n */\n readonly #context: string;\n\n /**\n * Optional base URL override for local development.\n */\n readonly #baseUrlOverride?: string;\n\n /**\n * Constructs a new RampsService object.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this service.\n * @param args.environment - The environment to use for API requests.\n * @param args.context - The context for API requests (e.g., 'mobile-ios', 'mobile-android').\n * @param args.fetch - A function that can be used to make an HTTP request. If\n * your JavaScript environment supports `fetch` natively, you'll probably want\n * to pass that; otherwise you can pass an equivalent (such as `fetch` via\n * `node-fetch`).\n * @param args.policyOptions - Options to pass to `createServicePolicy`, which\n * is used to wrap each request. See {@link CreateServicePolicyOptions}.\n * @param args.baseUrlOverride - Optional base URL override for local development.\n */\n constructor({\n messenger,\n environment = RampsEnvironment.Staging,\n context,\n fetch: fetchFunction,\n policyOptions = {},\n baseUrlOverride,\n }: {\n messenger: RampsServiceMessenger;\n environment?: RampsEnvironment;\n context: string;\n fetch: typeof fetch;\n policyOptions?: CreateServicePolicyOptions;\n baseUrlOverride?: string;\n }) {\n this.name = serviceName;\n this.#messenger = messenger;\n this.#fetch = fetchFunction;\n this.#policy = createServicePolicy(policyOptions);\n this.#environment = environment;\n this.#context = context;\n this.#baseUrlOverride = baseUrlOverride;\n\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Gets the base URL for API requests, respecting the baseUrlOverride if set.\n *\n * @param service - The API service type.\n * @returns The base URL to use.\n */\n #getBaseUrl(service: RampsApiService): string {\n if (this.#baseUrlOverride) {\n return this.#baseUrlOverride;\n }\n return getBaseUrl(this.#environment, service);\n }\n\n /**\n * Registers a handler that will be called after a request returns a non-500\n * response, causing a retry. Primarily useful in tests where timers are being\n * mocked.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n * @see {@link createServicePolicy}\n */\n onRetry(\n listener: Parameters<ServicePolicy['onRetry']>[0],\n ): ReturnType<ServicePolicy['onRetry']> {\n return this.#policy.onRetry(listener);\n }\n\n /**\n * Registers a handler that will be called after a set number of retry rounds\n * prove that requests to the API endpoint consistently return a 5xx response.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n * @see {@link createServicePolicy}\n */\n onBreak(\n listener: Parameters<ServicePolicy['onBreak']>[0],\n ): ReturnType<ServicePolicy['onBreak']> {\n return this.#policy.onBreak(listener);\n }\n\n /**\n * Registers a handler that will be called under one of two circumstances:\n *\n * 1. After a set number of retries prove that requests to the API\n * consistently result in one of the following failures:\n * 1. A connection initiation error\n * 2. A connection reset error\n * 3. A timeout error\n * 4. A non-JSON response\n * 5. A 502, 503, or 504 response\n * 2. After a successful request is made to the API, but the response takes\n * longer than a set duration to return.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n */\n onDegraded(\n listener: Parameters<ServicePolicy['onDegraded']>[0],\n ): ReturnType<ServicePolicy['onDegraded']> {\n return this.#policy.onDegraded(listener);\n }\n\n /**\n * Adds common request parameters to a URL.\n *\n * @param url - The URL to add parameters to.\n * @param action - The ramp action type (optional, not all endpoints require it).\n */\n #addCommonParams(url: URL, action?: RampAction): void {\n if (action) {\n url.searchParams.set('action', action);\n }\n url.searchParams.set('sdk', RAMPS_SDK_VERSION);\n url.searchParams.set('controller', packageJson.version);\n url.searchParams.set('context', this.#context);\n }\n\n /**\n * Makes an API request with retry policy and error handling.\n *\n * @param service - The API service type (determines base URL).\n * @param path - The endpoint path.\n * @param options - Request options.\n * @param options.action - The ramp action type (optional).\n * @param options.responseType - How to parse the response ('json' or 'text').\n * @returns The parsed response data.\n */\n async #request<TResponse>(\n service: RampsApiService,\n path: string,\n options: {\n action?: RampAction;\n responseType: 'json' | 'text';\n },\n ): Promise<TResponse> {\n return this.#policy.execute(async () => {\n const baseUrl = this.#getBaseUrl(service);\n const url = new URL(path, baseUrl);\n this.#addCommonParams(url, options.action);\n\n const response = await this.#fetch(url);\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Fetching '${url.toString()}' failed with status '${response.status}'`,\n );\n }\n\n return options.responseType === 'json'\n ? (response.json() as Promise<TResponse>)\n : (response.text() as Promise<TResponse>);\n });\n }\n\n /**\n * Makes a request to the API in order to retrieve the user's geolocation\n * based on their IP address.\n *\n * @returns The user's country/region code (e.g., \"US-UT\" for Utah, USA).\n */\n async getGeolocation(): Promise<string> {\n const textResponse = await this.#request<string>(\n RampsApiService.Orders,\n 'geolocation',\n { responseType: 'text' },\n );\n\n const trimmedResponse = textResponse.trim();\n if (trimmedResponse.length > 0) {\n return trimmedResponse;\n }\n\n throw new Error('Malformed response received from geolocation API');\n }\n\n /**\n * Makes a request to the cached API to retrieve the list of supported countries.\n * The API returns countries with support information for both buy and sell actions.\n * Filters countries based on aggregator support (preserves OnRampSDK logic).\n *\n * @returns An array of countries filtered by aggregator support.\n */\n async getCountries(): Promise<Country[]> {\n const countries = await this.#request<Country[]>(\n RampsApiService.Regions,\n getApiPath('regions/countries'),\n { responseType: 'json' },\n );\n\n if (!Array.isArray(countries)) {\n throw new Error('Malformed response received from countries API');\n }\n\n return countries.filter((country) => {\n const isCountrySupported =\n country.supported.buy || country.supported.sell;\n\n if (country.states && country.states.length > 0) {\n const hasSupportedState = country.states.some(\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- intentionally using || to treat false as unsupported\n (state) => state.supported?.buy || state.supported?.sell,\n );\n return isCountrySupported || hasSupportedState;\n }\n\n return isCountrySupported;\n });\n }\n\n /**\n * Fetches the list of available tokens for a given region and action.\n * Supports optional provider filter.\n *\n * @param region - The region code (e.g., \"us\", \"fr\", \"us-ny\").\n * @param action - The ramp action type ('buy' or 'sell').\n * @param options - Optional query parameters for filtering tokens.\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?: {\n provider?: string | string[];\n },\n ): Promise<TokensResponse> {\n const normalizedRegion = region.toLowerCase().trim();\n const url = new URL(\n getApiPath(`regions/${normalizedRegion}/topTokens`),\n this.#getBaseUrl(RampsApiService.Regions),\n );\n this.#addCommonParams(url, action);\n\n if (options?.provider) {\n const providerIds = Array.isArray(options.provider)\n ? options.provider\n : [options.provider];\n providerIds.forEach((id) => url.searchParams.append('provider', id));\n }\n\n const response = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(url);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<TokensResponse>;\n });\n\n if (!response || typeof response !== 'object') {\n throw new Error('Malformed response received from tokens API');\n }\n\n if (\n !Array.isArray(response.topTokens) ||\n !Array.isArray(response.allTokens)\n ) {\n throw new Error('Malformed response received from tokens API');\n }\n\n return response;\n }\n\n /**\n * Fetches the list of providers for a given region.\n * Supports optional query filters: provider, crypto, fiat, payments.\n *\n * @param regionCode - The region code (e.g., \"us\", \"fr\", \"us-ny\").\n * @param options - Optional query parameters for filtering providers.\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 regionCode: string,\n options?: {\n provider?: string | string[];\n crypto?: string | string[];\n fiat?: string | string[];\n payments?: string | string[];\n },\n ): Promise<{ providers: Provider[] }> {\n const normalizedRegion = regionCode.toLowerCase().trim();\n const url = new URL(\n getApiPath(`regions/${normalizedRegion}/providers`),\n this.#getBaseUrl(RampsApiService.Regions),\n );\n this.#addCommonParams(url);\n\n if (options?.provider) {\n const providerIds = Array.isArray(options.provider)\n ? options.provider\n : [options.provider];\n providerIds.forEach((id) => url.searchParams.append('provider', id));\n }\n\n if (options?.crypto) {\n const cryptoIds = Array.isArray(options.crypto)\n ? options.crypto\n : [options.crypto];\n cryptoIds.forEach((id) => url.searchParams.append('crypto', id));\n }\n\n if (options?.fiat) {\n const fiatIds = Array.isArray(options.fiat)\n ? options.fiat\n : [options.fiat];\n fiatIds.forEach((id) => url.searchParams.append('fiat', id));\n }\n\n if (options?.payments) {\n const paymentIds = Array.isArray(options.payments)\n ? options.payments\n : [options.payments];\n paymentIds.forEach((id) => url.searchParams.append('payments', id));\n }\n\n const response = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(url);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<{ providers: Provider[] }>;\n });\n\n if (!response || typeof response !== 'object') {\n throw new Error('Malformed response received from providers API');\n }\n\n if (!Array.isArray(response.providers)) {\n throw new Error('Malformed response received from providers API');\n }\n\n return response;\n }\n\n /**\n * Fetches the list of payment methods for a given region, asset, and provider.\n *\n * @param options - Query parameters for filtering payment methods.\n * @param options.region - User's region code (e.g., \"us-al\").\n * @param options.fiat - Fiat currency code (e.g., \"usd\").\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(options: {\n region: string;\n fiat: string;\n assetId: string;\n provider: string;\n }): Promise<PaymentMethodsResponse> {\n const normalizedRegion = options.region.toLowerCase().trim();\n const url = new URL(\n getApiPath(`regions/${normalizedRegion}/payments`),\n this.#getBaseUrl(RampsApiService.Regions),\n );\n this.#addCommonParams(url);\n\n url.searchParams.set('region', options.region.toLowerCase().trim());\n url.searchParams.set('fiat', options.fiat.toLowerCase().trim());\n url.searchParams.set('crypto', options.assetId);\n url.searchParams.set('provider', options.provider);\n\n const response = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(url);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<PaymentMethodsResponse>;\n });\n\n if (!response || typeof response !== 'object') {\n throw new Error('Malformed response received from paymentMethods API');\n }\n\n if (!Array.isArray(response.payments)) {\n throw new Error('Malformed response received from paymentMethods API');\n }\n\n return response;\n }\n\n /**\n * Fetches quotes from all providers for a given set of parameters.\n * Uses the V2 orders API to get quotes for multiple payment methods at once.\n *\n * @param params - The parameters for fetching quotes.\n * @param params.region - User's region code (e.g., \"us\", \"us-ca\").\n * @param params.paymentMethods - Array of payment method IDs.\n * @param params.assetId - CAIP-19 cryptocurrency identifier.\n * @param params.fiat - Fiat currency code (e.g., \"usd\").\n * @param params.amount - The amount (in fiat for buy, crypto for sell).\n * @param params.walletAddress - The destination wallet address.\n * @param params.redirectUrl - Optional redirect URL after order completion.\n * @param params.providers - Optional provider IDs to filter quotes.\n * @param params.action - The ramp action type. Defaults to 'buy'.\n * @returns The quotes response containing success, sorted, error, and customActions.\n */\n async getQuotes(params: GetQuotesParams): Promise<QuotesResponse> {\n const normalizedRegion = params.region.toLowerCase().trim();\n const normalizedFiat = params.fiat.toLowerCase().trim();\n const action = params.action ?? 'buy';\n\n const url = new URL(\n getApiPath('quotes'),\n getBaseUrl(this.#environment, RampsApiService.Orders),\n );\n this.#addCommonParams(url, action);\n\n // Build region ID in the format expected by the API\n url.searchParams.set('region', normalizedRegion);\n url.searchParams.set('fiat', normalizedFiat);\n url.searchParams.set('crypto', params.assetId);\n url.searchParams.set('amount', String(params.amount));\n url.searchParams.set('walletAddress', params.walletAddress);\n\n // Add payment methods as array parameters\n params.paymentMethods.forEach((paymentMethod) => {\n url.searchParams.append('payments', paymentMethod);\n });\n\n // Add provider filter if specified\n params.providers?.forEach((provider) => {\n url.searchParams.append('providers', provider);\n });\n\n // Add redirect URL if specified\n if (params.redirectUrl) {\n url.searchParams.set('redirectUrl', params.redirectUrl);\n }\n\n const response = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(url);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<QuotesResponse>;\n });\n\n if (!response || typeof response !== 'object') {\n throw new Error('Malformed response received from quotes API');\n }\n\n if (\n !Array.isArray(response.success) ||\n !Array.isArray(response.sorted) ||\n !Array.isArray(response.error) ||\n !Array.isArray(response.customActions)\n ) {\n throw new Error('Malformed response received from quotes API');\n }\n\n return response;\n }\n\n /**\n * Fetches the buy widget data from a buy URL endpoint.\n * Makes a request to the buyURL (as provided in a quote) to get the actual\n * provider widget URL, browser type, and order ID.\n *\n * @param buyUrl - The full buy URL endpoint to fetch from.\n * @returns The buy widget data containing the provider widget URL.\n */\n async getBuyWidgetUrl(buyUrl: string): Promise<BuyWidget> {\n const url = new URL(buyUrl);\n this.#addCommonParams(url);\n\n const response = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(url);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<BuyWidget>;\n });\n\n if (!response || typeof response !== 'object' || !response.url) {\n throw new Error('Malformed response received from buy widget URL API');\n }\n\n return response;\n }\n\n /**\n * Fetches an order from the unified V2 API endpoint.\n * This endpoint returns a normalized `RampsOrder` (DepositOrder shape)\n * for all provider types, including both aggregator and native providers.\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 url = new URL(\n getApiPath(`providers/${providerCode}/orders/${orderCode}`),\n this.#getBaseUrl(RampsApiService.Orders),\n );\n this.#addCommonParams(url);\n url.searchParams.set('wallet', wallet);\n\n const response = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(url);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<RampsOrder>;\n });\n\n if (!response || typeof response !== 'object') {\n throw new Error('Malformed response received from order API');\n }\n\n return response;\n }\n\n /**\n * Extracts an order from a provider callback URL.\n * Sends the callback URL to the V2 API backend, which knows how to parse\n * each provider's callback format and extract the order ID. Then fetches\n * the full order using that ID.\n *\n * This is the V2 equivalent of the aggregator 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 // Step 1: Send the callback URL to the backend to extract the order ID.\n // The backend parses it using provider-specific logic.\n const callbackApiUrl = new URL(\n getApiPath(`providers/${providerCode}/callback`),\n this.#getBaseUrl(RampsApiService.Orders),\n );\n this.#addCommonParams(callbackApiUrl);\n callbackApiUrl.searchParams.set('url', callbackUrl);\n\n const callbackResponse = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(callbackApiUrl);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${callbackApiUrl.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<{ id: string }>;\n });\n\n const rawOrderId = callbackResponse?.id;\n if (!rawOrderId) {\n throw new Error(\n 'Could not extract order ID from callback URL via provider',\n );\n }\n\n // The callback response id may be a full resource path like\n // \"/providers/transak-staging/orders/3ec2e8ac-...\".\n // Extract just the order code (last segment) so getOrder doesn't\n // build a doubled path.\n const lastSlash = rawOrderId.lastIndexOf('/');\n const orderCode =\n lastSlash >= 0 ? rawOrderId.slice(lastSlash + 1) : rawOrderId;\n\n // Step 2: Fetch the full order using the extracted order code.\n return this.getOrder(providerCode, orderCode, wallet);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"RampsService.mjs","sourceRoot":"","sources":["../src/RampsService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,mCAAmC;AAI5E,OAAO,WAAW,8CAAwB;AAwe1C,sBAAsB;AAEtB;;GAEG;AACH,MAAM,CAAN,IAAY,gBASX;AATD,WAAY,gBAAgB;IAC1B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O,CAAC,KAAK,IAAI,EAAE;QACrC,MAAM,OAAO,GAAG,uBAAA,IAAI,yDAAY,MAAhB,IAAI,EAAa,OAAO,CAAC,CAAC;QAC1C,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACnC,uBAAA,IAAI,8DAAiB,MAArB,IAAI,EAAkB,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;QAE3C,MAAM,QAAQ,GAAG,MAAM,uBAAA,IAAI,2BAAO,MAAX,IAAI,EAAQ,GAAG,CAAC,CAAC;QACxC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,SAAS,CACjB,QAAQ,CAAC,MAAM,EACf,aAAa,GAAG,CAAC,QAAQ,EAAE,yBAAyB,QAAQ,CAAC,MAAM,GAAG,CACvE,CAAC;QACJ,CAAC;QAED,OAAO,OAAO,CAAC,YAAY,KAAK,MAAM;YACpC,CAAC,CAAE,QAAQ,CAAC,IAAI,EAAyB;YACzC,CAAC,CAAE,QAAQ,CAAC,IAAI,EAAyB,CAAC;IAC9C,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport { createServicePolicy, HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\n\nimport type { RampsServiceMethodActions } from './RampsService-method-action-types';\nimport packageJson from '../package.json';\n\n/**\n * Represents phone number information for a country.\n */\nexport type CountryPhone = {\n prefix: string;\n placeholder: string;\n template: string;\n};\n\n/**\n * Indicates whether a region supports buy and/or sell actions.\n */\nexport type SupportedActions = {\n /**\n * Whether buy actions are supported.\n */\n buy: boolean;\n /**\n * Whether sell actions are supported.\n */\n sell: boolean;\n};\n\n/**\n * Represents a state/province within a country.\n */\nexport type State = {\n /**\n * State identifier. Can be in path format (e.g., \"/regions/us-ut\") or ISO code format (e.g., \"us-ut\").\n */\n id?: string;\n /**\n * State name.\n */\n name?: string;\n /**\n * ISO state code (e.g., \"UT\", \"NY\").\n */\n stateId?: string;\n /**\n * Whether this state is supported for buy and/or sell ramp actions.\n */\n supported?: SupportedActions;\n /**\n * Whether this state is recommended.\n */\n recommended?: boolean;\n};\n\n/**\n * Represents a provider link.\n */\nexport type ProviderLink = {\n name: string;\n url: string;\n};\n\n/**\n * Represents provider logos.\n */\nexport type ProviderLogos = {\n light: string;\n dark: string;\n height: number;\n width: number;\n};\n\n/**\n * Browser type for provider buy features.\n */\nexport type ProviderBrowserType = 'APP_BROWSER' | 'IN_APP_OS_BROWSER' | null;\n\n/**\n * Represents a ramp provider.\n */\nexport type Provider = {\n id: string;\n name: string;\n environmentType: string;\n description: string;\n hqAddress: string;\n links: ProviderLink[];\n logos: ProviderLogos;\n supportedCryptoCurrencies?: Record<string, boolean>;\n supportedFiatCurrencies?: Record<string, boolean>;\n supportedPaymentMethods?: Record<string, boolean>;\n};\n\n/**\n * Represents a payment method for funding a purchase.\n */\nexport type PaymentMethod = {\n /**\n * Canonical payment method ID (e.g., \"/payments/debit-credit-card\").\n */\n id: string;\n /**\n * Payment type identifier (e.g., \"debit-credit-card\", \"bank-transfer\").\n */\n paymentType: string;\n /**\n * User-facing name for the payment method.\n */\n name: string;\n /**\n * Score for sorting payment methods (higher is better).\n */\n score: number;\n /**\n * Icon identifier for the payment method.\n */\n icon: string;\n /**\n * Localized disclaimer text (optional).\n */\n disclaimer?: string;\n /**\n * Delay in minutes (e.g., [5, 10]).\n */\n delay?: number[];\n /**\n * Localized pending order description (optional).\n */\n pendingOrderDescription?: string;\n /**\n * Whether this payment method is a manual bank transfer.\n */\n isManualBankTransfer?: boolean;\n};\n\n/**\n * Response from the paymentMethods API.\n */\nexport type PaymentMethodsResponse = {\n /**\n * List of available payment methods.\n */\n payments: PaymentMethod[];\n /**\n * Recommended sorting for payment methods.\n */\n sort?: {\n ids: string[];\n sortBy: string;\n };\n};\n\n// === QUOTES TYPES ===\n\n/**\n * Sort criteria for quotes.\n */\nexport type QuoteSortBy = 'price' | 'reliability';\n\n/**\n * Represents crypto translation info for a quote.\n */\nexport type QuoteCryptoTranslation = {\n /**\n * The crypto currency ID.\n */\n id?: string;\n /**\n * The crypto symbol.\n */\n symbol?: string;\n /**\n * The chain ID.\n */\n chainId?: string;\n};\n\n/**\n * Widget information for executing a buy order.\n */\nexport type BuyWidget = {\n /**\n * The widget URL to open for the user to complete the purchase.\n */\n url: string;\n /**\n * The browser type to use for opening the widget.\n */\n browser?: ProviderBrowserType;\n /**\n * Order ID if already created.\n */\n orderId?: string | null;\n};\n\n/**\n * Represents an individual quote from a provider.\n */\nexport type Quote = {\n /**\n * The provider ID (e.g., \"/providers/moonpay\").\n */\n provider: string;\n /**\n * The quote details.\n */\n quote: {\n /**\n * The amount the user is paying (in fiat for buy, crypto for sell).\n */\n amountIn: number | string;\n /**\n * The amount the user will receive (in crypto for buy, fiat for sell).\n */\n amountOut: number | string;\n /**\n * The payment method used for this quote.\n */\n paymentMethod: string;\n /**\n * The fiat value of the output amount (for buy actions).\n */\n amountOutInFiat?: number;\n /**\n * Crypto translation info for display.\n */\n cryptoTranslation?: QuoteCryptoTranslation;\n /**\n * Total fees in the source currency.\n */\n totalFees?: number | string;\n /**\n * Network fees.\n */\n networkFee?: number | string;\n /**\n * Provider fees.\n */\n providerFee?: number | string;\n /**\n * Buy URL endpoint that returns the actual provider widget URL.\n *\n * This is a MetaMask-hosted endpoint that, when fetched, returns JSON with the provider's widget URL.\n *\n * @deprecated Use buyWidget instead - it's embedded in the quote response.\n */\n buyURL?: string;\n /**\n * Widget information embedded in the quote response.\n * Contains the widget URL, browser type, and optional pre-order tracking ID.\n */\n buyWidget?: BuyWidget;\n };\n /**\n * Metadata about the quote.\n */\n metadata?: {\n /**\n * Reliability score for the provider (0-100).\n */\n reliability?: number;\n /**\n * Tags for the quote.\n */\n tags?: {\n /**\n * Whether this is the best rate quote.\n */\n isBestRate?: boolean;\n /**\n * Whether this is the most reliable provider.\n */\n isMostReliable?: boolean;\n };\n };\n};\n\n/**\n * Represents an error from a provider when fetching quotes.\n */\nexport type QuoteError = {\n /**\n * The provider ID that failed.\n */\n provider: string;\n /**\n * Error message.\n */\n error?: string;\n};\n\n/**\n * Sort order information for quotes.\n */\nexport type QuoteSortOrder = {\n /**\n * The sort criteria.\n */\n sortBy: QuoteSortBy;\n /**\n * Provider IDs in sorted order.\n */\n ids: string[];\n};\n\n/**\n * Custom action for a provider (e.g., Apple Pay).\n */\nexport type QuoteCustomAction = {\n /**\n * Buy action details.\n */\n buy: {\n /**\n * Provider ID.\n */\n providerId: string;\n };\n /**\n * Payment method ID this action applies to.\n */\n paymentMethodId: string;\n /**\n * Supported payment method IDs.\n */\n supportedPaymentMethodIds: string[];\n};\n\n/**\n * Response from the quotes API.\n */\nexport type QuotesResponse = {\n /**\n * Successfully retrieved quotes.\n */\n success: Quote[];\n /**\n * Sort orders for the quotes.\n */\n sorted: QuoteSortOrder[];\n /**\n * Errors from providers that failed to return quotes.\n */\n error: QuoteError[];\n /**\n * Custom actions available from providers.\n */\n customActions: QuoteCustomAction[];\n};\n\n/**\n * Parameters for fetching quotes.\n */\nexport type GetQuotesParams = {\n /**\n * The region code (e.g., \"us\", \"us-ca\").\n */\n region: string;\n /**\n * Array of payment method IDs to get quotes for.\n */\n paymentMethods: string[];\n /**\n * The CAIP-19 asset ID (e.g., \"eip155:1/erc20:0x...\").\n */\n assetId: string;\n /**\n * The fiat currency code (e.g., \"usd\").\n */\n fiat: string;\n /**\n * The amount (in fiat for buy, crypto for sell).\n */\n amount: number;\n /**\n * The destination wallet address.\n */\n walletAddress: string;\n /**\n * Optional redirect URL after order completion.\n */\n redirectUrl?: string;\n /**\n * Optional provider IDs to filter quotes.\n */\n providers?: string[];\n /**\n * The ramp action type. Defaults to 'buy'.\n */\n action?: RampAction;\n};\n\n/**\n * Represents a country returned from the regions/countries API.\n */\nexport type Country = {\n /**\n * ISO-2 country code (e.g., \"US\", \"GB\").\n */\n isoCode: string;\n /**\n * Country identifier. Can be in path format (e.g., \"/regions/us\") or ISO code format.\n * If not provided, defaults to isoCode.\n */\n id?: string;\n /**\n * Country flag emoji or code.\n */\n flag: string;\n /**\n * Country name.\n */\n name: string;\n /**\n * Phone number information.\n */\n phone: CountryPhone;\n /**\n * Default currency code.\n */\n currency: string;\n /**\n * Whether this country is supported for buy and/or sell ramp actions.\n */\n supported: SupportedActions;\n /**\n * Whether this country is recommended.\n */\n recommended?: boolean;\n /**\n * Array of state objects.\n */\n states?: State[];\n /**\n * Default amount for ramps transactions.\n */\n defaultAmount?: number;\n /**\n * Quick amount options for ramps transactions.\n */\n quickAmounts?: number[];\n};\n\n/**\n * Represents a token returned from the regions/{region}/tokens API.\n */\nexport type RampsToken = {\n /**\n * The asset identifier in CAIP-19 format (e.g., \"eip155:1/erc20:0x...\").\n */\n assetId: string;\n /**\n * The chain identifier in CAIP-2 format (e.g., \"eip155:1\").\n */\n chainId: string;\n /**\n * Token name (e.g., \"USD Coin\").\n */\n name: string;\n /**\n * Token symbol (e.g., \"USDC\").\n */\n symbol: string;\n /**\n * Number of decimals for the token.\n */\n decimals: number;\n /**\n * URL to the token icon.\n */\n iconUrl: string;\n /**\n * Whether this token is supported.\n */\n tokenSupported: boolean;\n};\n\n/**\n * Response from the regions/{region}/tokens API.\n */\nexport type TokensResponse = {\n /**\n * Top/popular tokens for the region.\n */\n topTokens: RampsToken[];\n /**\n * All available tokens for the region.\n */\n allTokens: RampsToken[];\n};\n\n// === ORDER TYPES ===\n\n/**\n * Possible statuses for a ramps order.\n */\nexport enum RampsOrderStatus {\n Unknown = 'UNKNOWN',\n Precreated = 'PRECREATED',\n Created = 'CREATED',\n Pending = 'PENDING',\n Failed = 'FAILED',\n Completed = 'COMPLETED',\n Cancelled = 'CANCELLED',\n IdExpired = 'ID_EXPIRED',\n}\n\n/**\n * Network information associated with an order.\n */\nexport type RampsOrderNetwork = {\n name: string;\n chainId: string;\n};\n\n/**\n * Crypto currency information associated with an order.\n */\nexport type RampsOrderCryptoCurrency = {\n assetId?: string;\n name?: string;\n chainId?: string;\n decimals?: number;\n iconUrl?: string;\n symbol: string;\n};\n\n/**\n * Payment method information associated with an order.\n */\nexport type RampsOrderPaymentMethod = {\n id: string;\n name?: string;\n shortName?: string;\n duration?: string;\n icon?: string;\n isManualBankTransfer?: boolean;\n};\n\n/**\n * Bank transfer instruction fields attached to an order by providers\n * that require manual payment (e.g. SEPA, wire transfer).\n */\nexport type OrderPaymentDetail = {\n fiatCurrency: string;\n paymentMethod: string;\n fields: { name: string; id: string; value: string }[];\n};\n\n/**\n * Fiat currency information associated with an order.\n */\nexport type RampsOrderFiatCurrency = {\n id?: string;\n symbol: string;\n name?: string;\n decimals?: number;\n denomSymbol?: string;\n};\n\n/**\n * A unified order type returned from the V2 API.\n * The V2 endpoint normalizes all provider responses into this shape.\n */\nexport type RampsOrder = {\n id?: string;\n isOnlyLink: boolean;\n provider?: Provider;\n success: boolean;\n cryptoAmount: string | number;\n fiatAmount: number;\n cryptoCurrency?: RampsOrderCryptoCurrency;\n fiatCurrency?: RampsOrderFiatCurrency;\n providerOrderId: string;\n providerOrderLink: string;\n createdAt: number;\n paymentMethod?: RampsOrderPaymentMethod;\n totalFeesFiat: number;\n txHash: string;\n walletAddress: string;\n status: RampsOrderStatus;\n network: RampsOrderNetwork;\n canBeUpdated: boolean;\n idHasExpired: boolean;\n idExpirationDate?: number;\n excludeFromPurchases: boolean;\n timeDescriptionPending: string;\n fiatAmountInUsd?: number;\n feesInUsd?: number;\n region?: string;\n orderType: string;\n exchangeRate?: number;\n pollingSecondsMinimum?: number;\n statusDescription?: string;\n partnerFees?: number;\n networkFees?: number;\n paymentDetails?: OrderPaymentDetail[];\n};\n\n/**\n * The SDK version to send with API requests. (backwards-compatibility)\n */\nexport const RAMPS_SDK_VERSION = '2.1.6';\n\n/**\n * The type of ramp action: 'buy' or 'sell'.\n */\nexport type RampAction = 'buy' | 'sell';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link RampsService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'RampsService';\n\n/**\n * The environment to use for API requests.\n */\nexport enum RampsEnvironment {\n Production = 'production',\n Staging = 'staging',\n Development = 'development',\n Local = 'local',\n}\n\n/**\n * The type of ramps API service.\n * Determines which base URL to use (cache vs standard).\n */\nexport enum RampsApiService {\n Regions = 'regions',\n Orders = 'orders',\n}\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getGeolocation',\n 'getCountries',\n 'getTokens',\n 'getProviders',\n 'getPaymentMethods',\n 'getQuotes',\n 'getBuyWidgetUrl',\n 'getOrder',\n 'getOrderFromCallback',\n] as const;\n\n/**\n * Actions that {@link RampsService} exposes to other consumers.\n */\nexport type RampsServiceActions = RampsServiceMethodActions;\n\n/**\n * Actions from other messengers that {@link RampsService} calls.\n */\ntype AllowedActions = never;\n\n/**\n * Events that {@link RampsService} exposes to other consumers.\n */\nexport type RampsServiceEvents = never;\n\n/**\n * Events from other messengers that {@link RampsService} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link RampsService}.\n */\nexport type RampsServiceMessenger = Messenger<\n typeof serviceName,\n RampsServiceActions | AllowedActions,\n RampsServiceEvents | AllowedEvents\n>;\n\n// === SERVICE DEFINITION ===\n\n/**\n * Gets the base URL for API requests based on the environment and service type.\n * The Regions service uses a cache URL, while other services use the standard URL.\n *\n * @param environment - The environment to use.\n * @param service - The API service type (determines if cache URL is used).\n * @returns The base URL for API requests.\n */\nfunction getBaseUrl(\n environment: RampsEnvironment,\n service: RampsApiService,\n): string {\n const cache = service === RampsApiService.Regions ? '-cache' : '';\n\n switch (environment) {\n case RampsEnvironment.Production:\n return `https://on-ramp${cache}.api.cx.metamask.io`;\n case RampsEnvironment.Staging:\n case RampsEnvironment.Development:\n return `https://on-ramp${cache}.uat-api.cx.metamask.io`;\n case RampsEnvironment.Local:\n return 'http://localhost:3000';\n default:\n throw new Error(`Invalid environment: ${String(environment)}`);\n }\n}\n\n/**\n * Constructs an API path with a version prefix.\n *\n * @param path - The API endpoint path.\n * @param version - The API version prefix. Defaults to 'v2'.\n * @returns The versioned API path.\n */\nfunction getApiPath(path: string, version: string = 'v2'): string {\n return `${version}/${path}`;\n}\n\n/**\n * This service object is responsible for interacting with the Ramps API.\n *\n * @example\n *\n * ``` ts\n * import { Messenger } from '@metamask/messenger';\n * import type {\n * RampsServiceActions,\n * RampsServiceEvents,\n * } from '@metamask/ramps-controller';\n *\n * const rootMessenger = new Messenger<\n * 'Root',\n * RampsServiceActions\n * RampsServiceEvents\n * >({ namespace: 'Root' });\n * const rampsServiceMessenger = new Messenger<\n * 'RampsService',\n * RampsServiceActions,\n * RampsServiceEvents,\n * typeof rootMessenger,\n * >({\n * namespace: 'RampsService',\n * parent: rootMessenger,\n * });\n * // Instantiate the service to register its actions on the messenger\n * new RampsService({\n * messenger: rampsServiceMessenger,\n * environment: RampsEnvironment.Production,\n * context: 'mobile-ios',\n * fetch,\n * });\n *\n * // Later...\n * // Get the user's geolocation\n * const geolocation = await rootMessenger.call(\n * 'RampsService:getGeolocation',\n * );\n * // ... Do something with the geolocation ...\n * ```\n */\nexport class RampsService {\n /**\n * The name of the service.\n */\n readonly name: typeof serviceName;\n\n /**\n * The messenger suited for this service.\n */\n readonly #messenger: ConstructorParameters<\n typeof RampsService\n >[0]['messenger'];\n\n /**\n * A function that can be used to make an HTTP request.\n */\n readonly #fetch: ConstructorParameters<typeof RampsService>[0]['fetch'];\n\n /**\n * The policy that wraps the request.\n *\n * @see {@link createServicePolicy}\n */\n readonly #policy: ServicePolicy;\n\n /**\n * The environment used for API requests.\n */\n readonly #environment: RampsEnvironment;\n\n /**\n * The context for API requests (e.g., 'mobile-ios', 'mobile-android').\n */\n readonly #context: string;\n\n /**\n * Optional base URL override for local development.\n */\n readonly #baseUrlOverride?: string;\n\n /**\n * Constructs a new RampsService object.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this service.\n * @param args.environment - The environment to use for API requests.\n * @param args.context - The context for API requests (e.g., 'mobile-ios', 'mobile-android').\n * @param args.fetch - A function that can be used to make an HTTP request. If\n * your JavaScript environment supports `fetch` natively, you'll probably want\n * to pass that; otherwise you can pass an equivalent (such as `fetch` via\n * `node-fetch`).\n * @param args.policyOptions - Options to pass to `createServicePolicy`, which\n * is used to wrap each request. See {@link CreateServicePolicyOptions}.\n * @param args.baseUrlOverride - Optional base URL override for local development.\n */\n constructor({\n messenger,\n environment = RampsEnvironment.Staging,\n context,\n fetch: fetchFunction,\n policyOptions = {},\n baseUrlOverride,\n }: {\n messenger: RampsServiceMessenger;\n environment?: RampsEnvironment;\n context: string;\n fetch: typeof fetch;\n policyOptions?: CreateServicePolicyOptions;\n baseUrlOverride?: string;\n }) {\n this.name = serviceName;\n this.#messenger = messenger;\n this.#fetch = fetchFunction;\n this.#policy = createServicePolicy(policyOptions);\n this.#environment = environment;\n this.#context = context;\n this.#baseUrlOverride = baseUrlOverride;\n\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Gets the base URL for API requests, respecting the baseUrlOverride if set.\n *\n * @param service - The API service type.\n * @returns The base URL to use.\n */\n #getBaseUrl(service: RampsApiService): string {\n if (this.#baseUrlOverride) {\n return this.#baseUrlOverride;\n }\n return getBaseUrl(this.#environment, service);\n }\n\n /**\n * Registers a handler that will be called after a request returns a non-500\n * response, causing a retry. Primarily useful in tests where timers are being\n * mocked.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n * @see {@link createServicePolicy}\n */\n onRetry(\n listener: Parameters<ServicePolicy['onRetry']>[0],\n ): ReturnType<ServicePolicy['onRetry']> {\n return this.#policy.onRetry(listener);\n }\n\n /**\n * Registers a handler that will be called after a set number of retry rounds\n * prove that requests to the API endpoint consistently return a 5xx response.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n * @see {@link createServicePolicy}\n */\n onBreak(\n listener: Parameters<ServicePolicy['onBreak']>[0],\n ): ReturnType<ServicePolicy['onBreak']> {\n return this.#policy.onBreak(listener);\n }\n\n /**\n * Registers a handler that will be called under one of two circumstances:\n *\n * 1. After a set number of retries prove that requests to the API\n * consistently result in one of the following failures:\n * 1. A connection initiation error\n * 2. A connection reset error\n * 3. A timeout error\n * 4. A non-JSON response\n * 5. A 502, 503, or 504 response\n * 2. After a successful request is made to the API, but the response takes\n * longer than a set duration to return.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n */\n onDegraded(\n listener: Parameters<ServicePolicy['onDegraded']>[0],\n ): ReturnType<ServicePolicy['onDegraded']> {\n return this.#policy.onDegraded(listener);\n }\n\n /**\n * Adds common request parameters to a URL.\n *\n * @param url - The URL to add parameters to.\n * @param action - The ramp action type (optional, not all endpoints require it).\n */\n #addCommonParams(url: URL, action?: RampAction): void {\n if (action) {\n url.searchParams.set('action', action);\n }\n url.searchParams.set('sdk', RAMPS_SDK_VERSION);\n url.searchParams.set('controller', packageJson.version);\n url.searchParams.set('context', this.#context);\n }\n\n /**\n * Makes an API request with retry policy and error handling.\n *\n * @param service - The API service type (determines base URL).\n * @param path - The endpoint path.\n * @param options - Request options.\n * @param options.action - The ramp action type (optional).\n * @param options.responseType - How to parse the response ('json' or 'text').\n * @returns The parsed response data.\n */\n async #request<TResponse>(\n service: RampsApiService,\n path: string,\n options: {\n action?: RampAction;\n responseType: 'json' | 'text';\n },\n ): Promise<TResponse> {\n return this.#policy.execute(async () => {\n const baseUrl = this.#getBaseUrl(service);\n const url = new URL(path, baseUrl);\n this.#addCommonParams(url, options.action);\n\n const response = await this.#fetch(url);\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Fetching '${url.toString()}' failed with status '${response.status}'`,\n );\n }\n\n return options.responseType === 'json'\n ? (response.json() as Promise<TResponse>)\n : (response.text() as Promise<TResponse>);\n });\n }\n\n /**\n * Makes a request to the API in order to retrieve the user's geolocation\n * based on their IP address.\n *\n * @returns The user's country/region code (e.g., \"US-UT\" for Utah, USA).\n */\n async getGeolocation(): Promise<string> {\n const textResponse = await this.#request<string>(\n RampsApiService.Orders,\n 'geolocation',\n { responseType: 'text' },\n );\n\n const trimmedResponse = textResponse.trim();\n if (trimmedResponse.length > 0) {\n return trimmedResponse;\n }\n\n throw new Error('Malformed response received from geolocation API');\n }\n\n /**\n * Makes a request to the cached API to retrieve the list of supported countries.\n * The API returns countries with support information for both buy and sell actions.\n * Filters countries based on aggregator support (preserves OnRampSDK logic).\n *\n * @returns An array of countries filtered by aggregator support.\n */\n async getCountries(): Promise<Country[]> {\n const countries = await this.#request<Country[]>(\n RampsApiService.Regions,\n getApiPath('regions/countries'),\n { responseType: 'json' },\n );\n\n if (!Array.isArray(countries)) {\n throw new Error('Malformed response received from countries API');\n }\n\n return countries.filter((country) => {\n const isCountrySupported =\n country.supported.buy || country.supported.sell;\n\n if (country.states && country.states.length > 0) {\n const hasSupportedState = country.states.some(\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- intentionally using || to treat false as unsupported\n (state) => state.supported?.buy || state.supported?.sell,\n );\n return isCountrySupported || hasSupportedState;\n }\n\n return isCountrySupported;\n });\n }\n\n /**\n * Fetches the list of available tokens for a given region and action.\n * Supports optional provider filter.\n *\n * @param region - The region code (e.g., \"us\", \"fr\", \"us-ny\").\n * @param action - The ramp action type ('buy' or 'sell').\n * @param options - Optional query parameters for filtering tokens.\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?: {\n provider?: string | string[];\n },\n ): Promise<TokensResponse> {\n const normalizedRegion = region.toLowerCase().trim();\n const url = new URL(\n getApiPath(`regions/${normalizedRegion}/topTokens`),\n this.#getBaseUrl(RampsApiService.Regions),\n );\n this.#addCommonParams(url, action);\n\n if (options?.provider) {\n const providerIds = Array.isArray(options.provider)\n ? options.provider\n : [options.provider];\n providerIds.forEach((id) => url.searchParams.append('provider', id));\n }\n\n const response = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(url);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<TokensResponse>;\n });\n\n if (!response || typeof response !== 'object') {\n throw new Error('Malformed response received from tokens API');\n }\n\n if (\n !Array.isArray(response.topTokens) ||\n !Array.isArray(response.allTokens)\n ) {\n throw new Error('Malformed response received from tokens API');\n }\n\n return response;\n }\n\n /**\n * Fetches the list of providers for a given region.\n * Supports optional query filters: provider, crypto, fiat, payments.\n *\n * @param regionCode - The region code (e.g., \"us\", \"fr\", \"us-ny\").\n * @param options - Optional query parameters for filtering providers.\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 regionCode: string,\n options?: {\n provider?: string | string[];\n crypto?: string | string[];\n fiat?: string | string[];\n payments?: string | string[];\n },\n ): Promise<{ providers: Provider[] }> {\n const normalizedRegion = regionCode.toLowerCase().trim();\n const url = new URL(\n getApiPath(`regions/${normalizedRegion}/providers`),\n this.#getBaseUrl(RampsApiService.Regions),\n );\n this.#addCommonParams(url);\n\n if (options?.provider) {\n const providerIds = Array.isArray(options.provider)\n ? options.provider\n : [options.provider];\n providerIds.forEach((id) => url.searchParams.append('provider', id));\n }\n\n if (options?.crypto) {\n const cryptoIds = Array.isArray(options.crypto)\n ? options.crypto\n : [options.crypto];\n cryptoIds.forEach((id) => url.searchParams.append('crypto', id));\n }\n\n if (options?.fiat) {\n const fiatIds = Array.isArray(options.fiat)\n ? options.fiat\n : [options.fiat];\n fiatIds.forEach((id) => url.searchParams.append('fiat', id));\n }\n\n if (options?.payments) {\n const paymentIds = Array.isArray(options.payments)\n ? options.payments\n : [options.payments];\n paymentIds.forEach((id) => url.searchParams.append('payments', id));\n }\n\n const response = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(url);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<{ providers: Provider[] }>;\n });\n\n if (!response || typeof response !== 'object') {\n throw new Error('Malformed response received from providers API');\n }\n\n if (!Array.isArray(response.providers)) {\n throw new Error('Malformed response received from providers API');\n }\n\n return response;\n }\n\n /**\n * Fetches the list of payment methods for a given region, asset, and provider.\n *\n * @param options - Query parameters for filtering payment methods.\n * @param options.region - User's region code (e.g., \"us-al\").\n * @param options.fiat - Fiat currency code (e.g., \"usd\").\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(options: {\n region: string;\n fiat: string;\n assetId: string;\n provider: string;\n }): Promise<PaymentMethodsResponse> {\n const normalizedRegion = options.region.toLowerCase().trim();\n const url = new URL(\n getApiPath(`regions/${normalizedRegion}/payments`),\n this.#getBaseUrl(RampsApiService.Regions),\n );\n this.#addCommonParams(url);\n\n url.searchParams.set('region', options.region.toLowerCase().trim());\n url.searchParams.set('fiat', options.fiat.toLowerCase().trim());\n url.searchParams.set('crypto', options.assetId);\n url.searchParams.set('provider', options.provider);\n\n const response = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(url);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<PaymentMethodsResponse>;\n });\n\n if (!response || typeof response !== 'object') {\n throw new Error('Malformed response received from paymentMethods API');\n }\n\n if (!Array.isArray(response.payments)) {\n throw new Error('Malformed response received from paymentMethods API');\n }\n\n return response;\n }\n\n /**\n * Fetches quotes from all providers for a given set of parameters.\n * Uses the V2 orders API to get quotes for multiple payment methods at once.\n *\n * @param params - The parameters for fetching quotes.\n * @param params.region - User's region code (e.g., \"us\", \"us-ca\").\n * @param params.paymentMethods - Array of payment method IDs.\n * @param params.assetId - CAIP-19 cryptocurrency identifier.\n * @param params.fiat - Fiat currency code (e.g., \"usd\").\n * @param params.amount - The amount (in fiat for buy, crypto for sell).\n * @param params.walletAddress - The destination wallet address.\n * @param params.redirectUrl - Optional redirect URL after order completion.\n * @param params.providers - Optional provider IDs to filter quotes.\n * @param params.action - The ramp action type. Defaults to 'buy'.\n * @returns The quotes response containing success, sorted, error, and customActions.\n */\n async getQuotes(params: GetQuotesParams): Promise<QuotesResponse> {\n const normalizedRegion = params.region.toLowerCase().trim();\n const normalizedFiat = params.fiat.toLowerCase().trim();\n const action = params.action ?? 'buy';\n\n const url = new URL(\n getApiPath('quotes'),\n getBaseUrl(this.#environment, RampsApiService.Orders),\n );\n this.#addCommonParams(url, action);\n\n // Build region ID in the format expected by the API\n url.searchParams.set('region', normalizedRegion);\n url.searchParams.set('fiat', normalizedFiat);\n url.searchParams.set('crypto', params.assetId);\n url.searchParams.set('amount', String(params.amount));\n url.searchParams.set('walletAddress', params.walletAddress);\n\n // Add payment methods as array parameters\n params.paymentMethods.forEach((paymentMethod) => {\n url.searchParams.append('payments', paymentMethod);\n });\n\n // Add provider filter if specified\n params.providers?.forEach((provider) => {\n url.searchParams.append('providers', provider);\n });\n\n // Add redirect URL if specified\n if (params.redirectUrl) {\n url.searchParams.set('redirectUrl', params.redirectUrl);\n }\n\n const response = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(url);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<QuotesResponse>;\n });\n\n if (!response || typeof response !== 'object') {\n throw new Error('Malformed response received from quotes API');\n }\n\n if (\n !Array.isArray(response.success) ||\n !Array.isArray(response.sorted) ||\n !Array.isArray(response.error) ||\n !Array.isArray(response.customActions)\n ) {\n throw new Error('Malformed response received from quotes API');\n }\n\n return response;\n }\n\n /**\n * Fetches the buy widget data from a buy URL endpoint.\n * Makes a request to the buyURL (as provided in a quote) to get the actual\n * provider widget URL, browser type, and order ID.\n *\n * @param buyUrl - The full buy URL endpoint to fetch from.\n * @returns The buy widget data containing the provider widget URL.\n */\n async getBuyWidgetUrl(buyUrl: string): Promise<BuyWidget> {\n const url = new URL(buyUrl);\n this.#addCommonParams(url);\n\n const response = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(url);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<BuyWidget>;\n });\n\n if (!response || typeof response !== 'object' || !response.url) {\n throw new Error('Malformed response received from buy widget URL API');\n }\n\n return response;\n }\n\n /**\n * Fetches an order from the unified V2 API endpoint.\n * This endpoint returns a normalized `RampsOrder` (DepositOrder shape)\n * for all provider types, including both aggregator and native providers.\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 url = new URL(\n getApiPath(`providers/${providerCode}/orders/${orderCode}`),\n this.#getBaseUrl(RampsApiService.Orders),\n );\n this.#addCommonParams(url);\n url.searchParams.set('wallet', wallet);\n\n const response = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(url);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<RampsOrder>;\n });\n\n if (!response || typeof response !== 'object') {\n throw new Error('Malformed response received from order API');\n }\n\n return response;\n }\n\n /**\n * Extracts an order from a provider callback URL.\n * Sends the callback URL to the V2 API backend, which knows how to parse\n * each provider's callback format and extract the order ID. Then fetches\n * the full order using that ID.\n *\n * This is the V2 equivalent of the aggregator 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 // Step 1: Send the callback URL to the backend to extract the order ID.\n // The backend parses it using provider-specific logic.\n const callbackApiUrl = new URL(\n getApiPath(`providers/${providerCode}/callback`),\n this.#getBaseUrl(RampsApiService.Orders),\n );\n this.#addCommonParams(callbackApiUrl);\n callbackApiUrl.searchParams.set('url', callbackUrl);\n\n const callbackResponse = await this.#policy.execute(async () => {\n const fetchResponse = await this.#fetch(callbackApiUrl);\n if (!fetchResponse.ok) {\n throw new HttpError(\n fetchResponse.status,\n `Fetching '${callbackApiUrl.toString()}' failed with status '${fetchResponse.status}'`,\n );\n }\n return fetchResponse.json() as Promise<{ id: string }>;\n });\n\n const rawOrderId = callbackResponse?.id;\n if (!rawOrderId) {\n throw new Error(\n 'Could not extract order ID from callback URL via provider',\n );\n }\n\n // The callback response id may be a full resource path like\n // \"/providers/transak-staging/orders/3ec2e8ac-...\".\n // Extract just the order code (last segment) so getOrder doesn't\n // build a doubled path.\n const lastSlash = rawOrderId.lastIndexOf('/');\n const orderCode =\n lastSlash >= 0 ? rawOrderId.slice(lastSlash + 1) : rawOrderId;\n\n // Step 2: Fetch the full order using the extracted order code.\n return this.getOrder(providerCode, orderCode, wallet);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RequestCache.cjs","sourceRoot":"","sources":["../src/RequestCache.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"RequestCache.cjs","sourceRoot":"","sources":["../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AI,CAAC,GAAG,EAAE;QACrB,aAAa;KACd,CAAC;AACJ,CAAC;AAXD,gDAWC;AAED;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAC9B,KAAa,EACb,aAAqB;IAErB,OAAO;QACL,MAAM,EAAE,aAAa,CAAC,KAAK;QAC3B,IAAI,EAAE,IAAI;QACV,KAAK;QACL,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;QACrB,aAAa;KACd,CAAC;AACJ,CAAC;AAXD,4CAWC","sourcesContent":["import type { Json } from '@metamask/utils';\n\n/**\n * Types of resources that can have loading/error states.\n */\nexport type ResourceType =\n | 'countries'\n | 'providers'\n | 'tokens'\n | 'paymentMethods';\n\n/**\n * Status of a cached request.\n */\nexport enum RequestStatus {\n IDLE = 'idle',\n LOADING = 'loading',\n SUCCESS = 'success',\n ERROR = 'error',\n}\n\n/**\n * State of a single cached request.\n * All properties must be JSON-serializable to satisfy StateConstraint.\n */\nexport type RequestState = {\n /** Current status of the request */\n status: `${RequestStatus}`;\n /** The data returned by the request, if successful */\n data: Json | null;\n /** Error message if the request failed */\n error: string | null;\n /** Timestamp when the request completed (for TTL calculation) */\n timestamp: number;\n /** Timestamp when the fetch started */\n lastFetchedAt: number;\n};\n\n/**\n * Cache of request states, keyed by cache key.\n */\nexport type RequestCache = Record<string, RequestState>;\n\n/**\n * Default TTL for cached requests in milliseconds (15 minutes).\n */\nexport const DEFAULT_REQUEST_CACHE_TTL = 15 * 60 * 1000;\n\n/**\n * Default maximum number of entries in the request cache.\n */\nexport const DEFAULT_REQUEST_CACHE_MAX_SIZE = 250;\n\n/**\n * Creates a cache key from a method name and parameters.\n *\n * @param method - The method name.\n * @param params - The parameters passed to the method.\n * @returns A unique cache key string.\n */\nexport function createCacheKey(method: string, params: unknown[]): string {\n return `${method}:${JSON.stringify(params)}`;\n}\n\n/**\n * Checks if a cached request has expired based on TTL.\n *\n * @param requestState - The cached request state.\n * @param ttl - Time to live in milliseconds.\n * @returns True if the cache entry has expired.\n */\nexport function isCacheExpired(\n requestState: RequestState,\n ttl: number = DEFAULT_REQUEST_CACHE_TTL,\n): boolean {\n if (requestState.status !== RequestStatus.SUCCESS) {\n return true;\n }\n const now = Date.now();\n return now - requestState.timestamp > ttl;\n}\n\n/**\n * Creates an initial loading state for a request.\n *\n * @returns A new RequestState in loading status.\n */\nexport function createLoadingState(): RequestState {\n const now = Date.now();\n return {\n status: RequestStatus.LOADING,\n data: null,\n error: null,\n timestamp: now,\n lastFetchedAt: now,\n };\n}\n\n/**\n * Creates a success state for a request.\n *\n * @param data - The data returned by the request.\n * @param lastFetchedAt - When the fetch started.\n * @returns A new RequestState in success status.\n */\nexport function createSuccessState(\n data: Json,\n lastFetchedAt: number,\n): RequestState {\n return {\n status: RequestStatus.SUCCESS,\n data,\n error: null,\n timestamp: Date.now(),\n lastFetchedAt,\n };\n}\n\n/**\n * Creates an error state for a request.\n *\n * @param error - The error message.\n * @param lastFetchedAt - When the fetch started.\n * @returns A new RequestState in error status.\n */\nexport function createErrorState(\n error: string,\n lastFetchedAt: number,\n): RequestState {\n return {\n status: RequestStatus.ERROR,\n data: null,\n error,\n timestamp: Date.now(),\n lastFetchedAt,\n };\n}\n\n/**\n * Options for executing a cached request.\n */\nexport type ExecuteRequestOptions = {\n /** Force a refresh even if cached data exists */\n forceRefresh?: boolean;\n /** Custom TTL for this request in milliseconds */\n ttl?: number;\n /** Resource type to update loading/error states for */\n resourceType?: ResourceType;\n /**\n * When provided, resource-level error is only set/cleared if this returns true.\n * Used to avoid applying stale errors after e.g. region or selection changes.\n */\n isResultCurrent?: () => boolean;\n};\n\n/**\n * Represents a pending request with its promise and abort controller.\n */\nexport type PendingRequest<TResult = unknown> = {\n promise: Promise<TResult>;\n abortController: AbortController;\n /** When set, used to abort other in-flight requests for this resource when a new one starts. */\n resourceType?: ResourceType;\n};\n"]}
|
package/dist/RequestCache.d.cts
CHANGED
|
@@ -2,7 +2,7 @@ import type { Json } from "@metamask/utils";
|
|
|
2
2
|
/**
|
|
3
3
|
* Types of resources that can have loading/error states.
|
|
4
4
|
*/
|
|
5
|
-
export type ResourceType = 'countries' | 'providers' | 'tokens' | 'paymentMethods'
|
|
5
|
+
export type ResourceType = 'countries' | 'providers' | 'tokens' | 'paymentMethods';
|
|
6
6
|
/**
|
|
7
7
|
* Status of a cached request.
|
|
8
8
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RequestCache.d.cts","sourceRoot":"","sources":["../src/RequestCache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAE5C;;GAEG;AACH,MAAM,MAAM,YAAY,GACpB,WAAW,GACX,WAAW,GACX,QAAQ,GACR,gBAAgB,
|
|
1
|
+
{"version":3,"file":"RequestCache.d.cts","sourceRoot":"","sources":["../src/RequestCache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAE5C;;GAEG;AACH,MAAM,MAAM,YAAY,GACpB,WAAW,GACX,WAAW,GACX,QAAQ,GACR,gBAAgB,CAAC;AAErB;;GAEG;AACH,oBAAY,aAAa;IACvB,IAAI,SAAS;IACb,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,KAAK,UAAU;CAChB;AAED;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,oCAAoC;IACpC,MAAM,EAAE,GAAG,aAAa,EAAE,CAAC;IAC3B,sDAAsD;IACtD,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;IAClB,0CAA0C;IAC1C,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,iEAAiE;IACjE,SAAS,EAAE,MAAM,CAAC;IAClB,uCAAuC;IACvC,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;AAExD;;GAEG;AACH,eAAO,MAAM,yBAAyB,QAAiB,CAAC;AAExD;;GAEG;AACH,eAAO,MAAM,8BAA8B,MAAM,CAAC;AAElD;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAExE;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,YAAY,EAAE,YAAY,EAC1B,GAAG,GAAE,MAAkC,GACtC,OAAO,CAMT;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,IAAI,YAAY,CASjD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,IAAI,EACV,aAAa,EAAE,MAAM,GACpB,YAAY,CAQd;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,MAAM,GACpB,YAAY,CAQd;AAED;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,iDAAiD;IACjD,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,kDAAkD;IAClD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,uDAAuD;IACvD,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,OAAO,CAAC;CACjC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,cAAc,CAAC,OAAO,GAAG,OAAO,IAAI;IAC9C,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IAC1B,eAAe,EAAE,eAAe,CAAC;IACjC,gGAAgG;IAChG,YAAY,CAAC,EAAE,YAAY,CAAC;CAC7B,CAAC"}
|
package/dist/RequestCache.d.mts
CHANGED
|
@@ -2,7 +2,7 @@ import type { Json } from "@metamask/utils";
|
|
|
2
2
|
/**
|
|
3
3
|
* Types of resources that can have loading/error states.
|
|
4
4
|
*/
|
|
5
|
-
export type ResourceType = 'countries' | 'providers' | 'tokens' | 'paymentMethods'
|
|
5
|
+
export type ResourceType = 'countries' | 'providers' | 'tokens' | 'paymentMethods';
|
|
6
6
|
/**
|
|
7
7
|
* Status of a cached request.
|
|
8
8
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RequestCache.d.mts","sourceRoot":"","sources":["../src/RequestCache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAE5C;;GAEG;AACH,MAAM,MAAM,YAAY,GACpB,WAAW,GACX,WAAW,GACX,QAAQ,GACR,gBAAgB,
|
|
1
|
+
{"version":3,"file":"RequestCache.d.mts","sourceRoot":"","sources":["../src/RequestCache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAE5C;;GAEG;AACH,MAAM,MAAM,YAAY,GACpB,WAAW,GACX,WAAW,GACX,QAAQ,GACR,gBAAgB,CAAC;AAErB;;GAEG;AACH,oBAAY,aAAa;IACvB,IAAI,SAAS;IACb,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,KAAK,UAAU;CAChB;AAED;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,oCAAoC;IACpC,MAAM,EAAE,GAAG,aAAa,EAAE,CAAC;IAC3B,sDAAsD;IACtD,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;IAClB,0CAA0C;IAC1C,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,iEAAiE;IACjE,SAAS,EAAE,MAAM,CAAC;IAClB,uCAAuC;IACvC,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;AAExD;;GAEG;AACH,eAAO,MAAM,yBAAyB,QAAiB,CAAC;AAExD;;GAEG;AACH,eAAO,MAAM,8BAA8B,MAAM,CAAC;AAElD;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAExE;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,YAAY,EAAE,YAAY,EAC1B,GAAG,GAAE,MAAkC,GACtC,OAAO,CAMT;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,IAAI,YAAY,CASjD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,IAAI,EACV,aAAa,EAAE,MAAM,GACpB,YAAY,CAQd;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,MAAM,GACpB,YAAY,CAQd;AAED;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,iDAAiD;IACjD,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,kDAAkD;IAClD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,uDAAuD;IACvD,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,OAAO,CAAC;CACjC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,cAAc,CAAC,OAAO,GAAG,OAAO,IAAI;IAC9C,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IAC1B,eAAe,EAAE,eAAe,CAAC;IACjC,gGAAgG;IAChG,YAAY,CAAC,EAAE,YAAY,CAAC;CAC7B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RequestCache.mjs","sourceRoot":"","sources":["../src/RequestCache.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"RequestCache.mjs","sourceRoot":"","sources":["../src/RequestCache.ts"],"names":[],"mappings":"AAWA;;GAEG;AACH,MAAM,CAAN,IAAY,aAKX;AALD,WAAY,aAAa;IACvB,8BAAa,CAAA;IACb,oCAAmB,CAAA;IACnB,oCAAmB,CAAA;IACnB,gCAAe,CAAA;AACjB,CAAC,EALW,aAAa,KAAb,aAAa,QAKxB;AAwBD;;GAEG;AAC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QACL,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;QACrB,aAAa;KACd,CAAC;AACJ,CAAC","sourcesContent":["import type { Json } from '@metamask/utils';\n\n/**\n * Types of resources that can have loading/error states.\n */\nexport type ResourceType =\n | 'countries'\n | 'providers'\n | 'tokens'\n | 'paymentMethods';\n\n/**\n * Status of a cached request.\n */\nexport enum RequestStatus {\n IDLE = 'idle',\n LOADING = 'loading',\n SUCCESS = 'success',\n ERROR = 'error',\n}\n\n/**\n * State of a single cached request.\n * All properties must be JSON-serializable to satisfy StateConstraint.\n */\nexport type RequestState = {\n /** Current status of the request */\n status: `${RequestStatus}`;\n /** The data returned by the request, if successful */\n data: Json | null;\n /** Error message if the request failed */\n error: string | null;\n /** Timestamp when the request completed (for TTL calculation) */\n timestamp: number;\n /** Timestamp when the fetch started */\n lastFetchedAt: number;\n};\n\n/**\n * Cache of request states, keyed by cache key.\n */\nexport type RequestCache = Record<string, RequestState>;\n\n/**\n * Default TTL for cached requests in milliseconds (15 minutes).\n */\nexport const DEFAULT_REQUEST_CACHE_TTL = 15 * 60 * 1000;\n\n/**\n * Default maximum number of entries in the request cache.\n */\nexport const DEFAULT_REQUEST_CACHE_MAX_SIZE = 250;\n\n/**\n * Creates a cache key from a method name and parameters.\n *\n * @param method - The method name.\n * @param params - The parameters passed to the method.\n * @returns A unique cache key string.\n */\nexport function createCacheKey(method: string, params: unknown[]): string {\n return `${method}:${JSON.stringify(params)}`;\n}\n\n/**\n * Checks if a cached request has expired based on TTL.\n *\n * @param requestState - The cached request state.\n * @param ttl - Time to live in milliseconds.\n * @returns True if the cache entry has expired.\n */\nexport function isCacheExpired(\n requestState: RequestState,\n ttl: number = DEFAULT_REQUEST_CACHE_TTL,\n): boolean {\n if (requestState.status !== RequestStatus.SUCCESS) {\n return true;\n }\n const now = Date.now();\n return now - requestState.timestamp > ttl;\n}\n\n/**\n * Creates an initial loading state for a request.\n *\n * @returns A new RequestState in loading status.\n */\nexport function createLoadingState(): RequestState {\n const now = Date.now();\n return {\n status: RequestStatus.LOADING,\n data: null,\n error: null,\n timestamp: now,\n lastFetchedAt: now,\n };\n}\n\n/**\n * Creates a success state for a request.\n *\n * @param data - The data returned by the request.\n * @param lastFetchedAt - When the fetch started.\n * @returns A new RequestState in success status.\n */\nexport function createSuccessState(\n data: Json,\n lastFetchedAt: number,\n): RequestState {\n return {\n status: RequestStatus.SUCCESS,\n data,\n error: null,\n timestamp: Date.now(),\n lastFetchedAt,\n };\n}\n\n/**\n * Creates an error state for a request.\n *\n * @param error - The error message.\n * @param lastFetchedAt - When the fetch started.\n * @returns A new RequestState in error status.\n */\nexport function createErrorState(\n error: string,\n lastFetchedAt: number,\n): RequestState {\n return {\n status: RequestStatus.ERROR,\n data: null,\n error,\n timestamp: Date.now(),\n lastFetchedAt,\n };\n}\n\n/**\n * Options for executing a cached request.\n */\nexport type ExecuteRequestOptions = {\n /** Force a refresh even if cached data exists */\n forceRefresh?: boolean;\n /** Custom TTL for this request in milliseconds */\n ttl?: number;\n /** Resource type to update loading/error states for */\n resourceType?: ResourceType;\n /**\n * When provided, resource-level error is only set/cleared if this returns true.\n * Used to avoid applying stale errors after e.g. region or selection changes.\n */\n isResultCurrent?: () => boolean;\n};\n\n/**\n * Represents a pending request with its promise and abort controller.\n */\nexport type PendingRequest<TResult = unknown> = {\n promise: Promise<TResult>;\n abortController: AbortController;\n /** When set, used to abort other in-flight requests for this resource when a new one starts. */\n resourceType?: ResourceType;\n};\n"]}
|
package/dist/TransakService.cjs
CHANGED
|
@@ -10,7 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
10
10
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
11
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
12
|
};
|
|
13
|
-
var _TransakService_instances, _TransakService_messenger, _TransakService_fetch, _TransakService_policy, _TransakService_environment, _TransakService_context, _TransakService_orderRetryDelayMs, _TransakService_apiKey, _TransakService_accessToken, _TransakService_ensureApiKey, _TransakService_ensureAccessToken, _TransakService_getHeaders, _TransakService_transakGet, _TransakService_transakPost, _TransakService_transakPatch, _TransakService_transakDelete, _TransakService_ordersApiGet;
|
|
13
|
+
var _TransakService_instances, _TransakService_messenger, _TransakService_fetch, _TransakService_policy, _TransakService_environment, _TransakService_context, _TransakService_orderRetryDelayMs, _TransakService_apiKey, _TransakService_accessToken, _TransakService_ensureApiKey, _TransakService_ensureAccessToken, _TransakService_getHeaders, _TransakService_throwTransakApiError, _TransakService_transakGet, _TransakService_transakPost, _TransakService_transakPatch, _TransakService_transakDelete, _TransakService_ordersApiGet;
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.TransakService = exports.TransakApiError = exports.TransakOrderIdTransformer = exports.TransakEnvironment = void 0;
|
|
16
16
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
@@ -138,9 +138,10 @@ function getPaymentWidgetBaseUrl(environment) {
|
|
|
138
138
|
// === TRANSAK API ERROR ===
|
|
139
139
|
const TRANSAK_ORDER_EXISTS_CODE = '4005';
|
|
140
140
|
class TransakApiError extends controller_utils_1.HttpError {
|
|
141
|
-
constructor(status, message, errorCode) {
|
|
141
|
+
constructor(status, message, errorCode, apiMessage) {
|
|
142
142
|
super(status, message);
|
|
143
143
|
this.errorCode = errorCode;
|
|
144
|
+
this.apiMessage = apiMessage;
|
|
144
145
|
}
|
|
145
146
|
}
|
|
146
147
|
exports.TransakApiError = TransakApiError;
|
|
@@ -469,6 +470,28 @@ _TransakService_messenger = new WeakMap(), _TransakService_fetch = new WeakMap()
|
|
|
469
470
|
headers.authorization = __classPrivateFieldGet(this, _TransakService_accessToken, "f").accessToken;
|
|
470
471
|
}
|
|
471
472
|
return headers;
|
|
473
|
+
}, _TransakService_throwTransakApiError = async function _TransakService_throwTransakApiError(fetchResponse, url) {
|
|
474
|
+
let errorBody = '';
|
|
475
|
+
let errorCode;
|
|
476
|
+
let apiMessage;
|
|
477
|
+
try {
|
|
478
|
+
errorBody = await fetchResponse.text();
|
|
479
|
+
const parsed = JSON.parse(errorBody);
|
|
480
|
+
errorCode =
|
|
481
|
+
parsed?.error?.code ??
|
|
482
|
+
(parsed?.error?.errorCode !== null &&
|
|
483
|
+
parsed?.error?.errorCode !== undefined
|
|
484
|
+
? String(parsed.error.errorCode)
|
|
485
|
+
: undefined);
|
|
486
|
+
apiMessage =
|
|
487
|
+
typeof parsed?.error?.message === 'string'
|
|
488
|
+
? parsed.error.message
|
|
489
|
+
: undefined;
|
|
490
|
+
}
|
|
491
|
+
catch {
|
|
492
|
+
// ignore body read/parse failures
|
|
493
|
+
}
|
|
494
|
+
throw new TransakApiError(fetchResponse.status, `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'${errorBody ? `: ${errorBody}` : ''}`, errorCode, apiMessage);
|
|
472
495
|
}, _TransakService_transakGet = async function _TransakService_transakGet(path, params) {
|
|
473
496
|
const baseUrl = getTransakApiBaseUrl(__classPrivateFieldGet(this, _TransakService_environment, "f"));
|
|
474
497
|
const url = new URL(path, baseUrl);
|
|
@@ -487,7 +510,7 @@ _TransakService_messenger = new WeakMap(), _TransakService_fetch = new WeakMap()
|
|
|
487
510
|
headers: __classPrivateFieldGet(this, _TransakService_instances, "m", _TransakService_getHeaders).call(this),
|
|
488
511
|
});
|
|
489
512
|
if (!fetchResponse.ok) {
|
|
490
|
-
|
|
513
|
+
await __classPrivateFieldGet(this, _TransakService_instances, "m", _TransakService_throwTransakApiError).call(this, fetchResponse, url);
|
|
491
514
|
}
|
|
492
515
|
return fetchResponse.json();
|
|
493
516
|
});
|
|
@@ -507,17 +530,7 @@ _TransakService_messenger = new WeakMap(), _TransakService_fetch = new WeakMap()
|
|
|
507
530
|
body: JSON.stringify(requestBody),
|
|
508
531
|
});
|
|
509
532
|
if (!fetchResponse.ok) {
|
|
510
|
-
|
|
511
|
-
let errorCode;
|
|
512
|
-
try {
|
|
513
|
-
errorBody = await fetchResponse.text();
|
|
514
|
-
const parsed = JSON.parse(errorBody);
|
|
515
|
-
errorCode = parsed?.error?.code;
|
|
516
|
-
}
|
|
517
|
-
catch {
|
|
518
|
-
// ignore body read/parse failures
|
|
519
|
-
}
|
|
520
|
-
throw new TransakApiError(fetchResponse.status, `Fetching '${url.toString()}' failed with status '${fetchResponse.status}'${errorBody ? `: ${errorBody}` : ''}`, errorCode);
|
|
533
|
+
await __classPrivateFieldGet(this, _TransakService_instances, "m", _TransakService_throwTransakApiError).call(this, fetchResponse, url);
|
|
521
534
|
}
|
|
522
535
|
return fetchResponse.json();
|
|
523
536
|
});
|
|
@@ -534,7 +547,7 @@ _TransakService_messenger = new WeakMap(), _TransakService_fetch = new WeakMap()
|
|
|
534
547
|
body: JSON.stringify(body),
|
|
535
548
|
});
|
|
536
549
|
if (!fetchResponse.ok) {
|
|
537
|
-
|
|
550
|
+
await __classPrivateFieldGet(this, _TransakService_instances, "m", _TransakService_throwTransakApiError).call(this, fetchResponse, url);
|
|
538
551
|
}
|
|
539
552
|
return fetchResponse.json();
|
|
540
553
|
});
|
|
@@ -557,7 +570,7 @@ _TransakService_messenger = new WeakMap(), _TransakService_fetch = new WeakMap()
|
|
|
557
570
|
headers: __classPrivateFieldGet(this, _TransakService_instances, "m", _TransakService_getHeaders).call(this),
|
|
558
571
|
});
|
|
559
572
|
if (!fetchResponse.ok) {
|
|
560
|
-
|
|
573
|
+
await __classPrivateFieldGet(this, _TransakService_instances, "m", _TransakService_throwTransakApiError).call(this, fetchResponse, url);
|
|
561
574
|
}
|
|
562
575
|
});
|
|
563
576
|
}, _TransakService_ordersApiGet = async function _TransakService_ordersApiGet(path, params) {
|