@metamask/ramps-controller 2.1.0 → 3.0.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 +16 -1
- package/dist/RampsController.cjs +112 -17
- package/dist/RampsController.cjs.map +1 -1
- package/dist/RampsController.d.cts +43 -8
- package/dist/RampsController.d.cts.map +1 -1
- package/dist/RampsController.d.mts +43 -8
- package/dist/RampsController.d.mts.map +1 -1
- package/dist/RampsController.mjs +112 -17
- package/dist/RampsController.mjs.map +1 -1
- package/dist/RampsService-method-action-types.cjs.map +1 -1
- package/dist/RampsService-method-action-types.d.cts +12 -1
- package/dist/RampsService-method-action-types.d.cts.map +1 -1
- package/dist/RampsService-method-action-types.d.mts +12 -1
- package/dist/RampsService-method-action-types.d.mts.map +1 -1
- package/dist/RampsService-method-action-types.mjs.map +1 -1
- package/dist/RampsService.cjs +20 -0
- package/dist/RampsService.cjs.map +1 -1
- package/dist/RampsService.d.cts +54 -0
- package/dist/RampsService.d.cts.map +1 -1
- package/dist/RampsService.d.mts +54 -0
- package/dist/RampsService.d.mts.map +1 -1
- package/dist/RampsService.mjs +20 -0
- package/dist/RampsService.mjs.map +1 -1
- package/dist/selectors.cjs +5 -5
- package/dist/selectors.cjs.map +1 -1
- package/dist/selectors.d.cts +5 -5
- package/dist/selectors.d.mts +5 -5
- package/dist/selectors.mjs +5 -5
- package/dist/selectors.mjs.map +1 -1
- package/package.json +2 -2
package/dist/RampsService.d.mts
CHANGED
|
@@ -94,6 +94,52 @@ export type Country = {
|
|
|
94
94
|
*/
|
|
95
95
|
states?: State[];
|
|
96
96
|
};
|
|
97
|
+
/**
|
|
98
|
+
* Represents a token returned from the regions/{region}/tokens API.
|
|
99
|
+
*/
|
|
100
|
+
export type RampsToken = {
|
|
101
|
+
/**
|
|
102
|
+
* The asset identifier in CAIP-19 format (e.g., "eip155:1/erc20:0x...").
|
|
103
|
+
*/
|
|
104
|
+
assetId: string;
|
|
105
|
+
/**
|
|
106
|
+
* The chain identifier in CAIP-2 format (e.g., "eip155:1").
|
|
107
|
+
*/
|
|
108
|
+
chainId: string;
|
|
109
|
+
/**
|
|
110
|
+
* Token name (e.g., "USD Coin").
|
|
111
|
+
*/
|
|
112
|
+
name: string;
|
|
113
|
+
/**
|
|
114
|
+
* Token symbol (e.g., "USDC").
|
|
115
|
+
*/
|
|
116
|
+
symbol: string;
|
|
117
|
+
/**
|
|
118
|
+
* Number of decimals for the token.
|
|
119
|
+
*/
|
|
120
|
+
decimals: number;
|
|
121
|
+
/**
|
|
122
|
+
* URL to the token icon.
|
|
123
|
+
*/
|
|
124
|
+
iconUrl: string;
|
|
125
|
+
/**
|
|
126
|
+
* Whether this token is supported.
|
|
127
|
+
*/
|
|
128
|
+
tokenSupported: boolean;
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* Response from the regions/{region}/tokens API.
|
|
132
|
+
*/
|
|
133
|
+
export type TokensResponse = {
|
|
134
|
+
/**
|
|
135
|
+
* Top/popular tokens for the region.
|
|
136
|
+
*/
|
|
137
|
+
topTokens: RampsToken[];
|
|
138
|
+
/**
|
|
139
|
+
* All available tokens for the region.
|
|
140
|
+
*/
|
|
141
|
+
allTokens: RampsToken[];
|
|
142
|
+
};
|
|
97
143
|
/**
|
|
98
144
|
* The SDK version to send with API requests. (backwards-compatibility)
|
|
99
145
|
*/
|
|
@@ -270,6 +316,14 @@ export declare class RampsService {
|
|
|
270
316
|
* @returns Eligibility information for the region.
|
|
271
317
|
*/
|
|
272
318
|
getEligibility(isoCode: string): Promise<Eligibility>;
|
|
319
|
+
/**
|
|
320
|
+
* Fetches the list of available tokens for a given region and action.
|
|
321
|
+
*
|
|
322
|
+
* @param region - The region code (e.g., "us", "fr", "us-ny").
|
|
323
|
+
* @param action - The ramp action type ('buy' or 'sell').
|
|
324
|
+
* @returns The tokens response containing topTokens and allTokens.
|
|
325
|
+
*/
|
|
326
|
+
getTokens(region: string, action?: 'buy' | 'sell'): Promise<TokensResponse>;
|
|
273
327
|
}
|
|
274
328
|
export {};
|
|
275
329
|
//# sourceMappingURL=RampsService.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RampsService.d.mts","sourceRoot":"","sources":["../src/RampsService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,0BAA0B,EAC1B,aAAa,EACd,mCAAmC;AAEpC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAErD,OAAO,KAAK,EAAE,yBAAyB,EAAE,+CAA2C;AAGpF;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,KAAK,GAAG;IAClB;;OAEG;IACH,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB;;OAEG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB;;OAEG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;OAEG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,OAAO,GAAG;IACpB;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,KAAK,EAAE,YAAY,CAAC;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vC;;;;;;;;;;;;;;;;OAgBG;IACH,UAAU,CACR,QAAQ,EAAE,UAAU,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,GACnD,UAAU,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC;IAwD1C;;;;;OAKG;IACG,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC;IAevC;;;;;;OAMG;IACG,YAAY,CAAC,MAAM,GAAE,KAAK,GAAG,MAAc,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;IAuBtE;;;;;OAKG;IACG,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAS3D;;;;;;OAMG;IACG,SAAS,CACb,MAAM,EAAE,MAAM,EACd,MAAM,GAAE,KAAK,GAAG,MAAc,GAC7B,OAAO,CAAC,cAAc,CAAC;CAqB3B"}
|
package/dist/RampsService.mjs
CHANGED
|
@@ -45,6 +45,7 @@ const MESSENGER_EXPOSED_METHODS = [
|
|
|
45
45
|
'getGeolocation',
|
|
46
46
|
'getCountries',
|
|
47
47
|
'getEligibility',
|
|
48
|
+
'getTokens',
|
|
48
49
|
];
|
|
49
50
|
// === SERVICE DEFINITION ===
|
|
50
51
|
/**
|
|
@@ -245,6 +246,25 @@ export class RampsService {
|
|
|
245
246
|
const normalizedIsoCode = isoCode.toLowerCase().trim();
|
|
246
247
|
return __classPrivateFieldGet(this, _RampsService_instances, "m", _RampsService_request).call(this, RampsApiService.Regions, `regions/countries/${normalizedIsoCode}`, { responseType: 'json' });
|
|
247
248
|
}
|
|
249
|
+
/**
|
|
250
|
+
* Fetches the list of available tokens for a given region and action.
|
|
251
|
+
*
|
|
252
|
+
* @param region - The region code (e.g., "us", "fr", "us-ny").
|
|
253
|
+
* @param action - The ramp action type ('buy' or 'sell').
|
|
254
|
+
* @returns The tokens response containing topTokens and allTokens.
|
|
255
|
+
*/
|
|
256
|
+
async getTokens(region, action = 'buy') {
|
|
257
|
+
const normalizedRegion = region.toLowerCase().trim();
|
|
258
|
+
const response = await __classPrivateFieldGet(this, _RampsService_instances, "m", _RampsService_request).call(this, RampsApiService.Regions, `regions/${normalizedRegion}/tokens`, { action, responseType: 'json' });
|
|
259
|
+
if (!response || typeof response !== 'object') {
|
|
260
|
+
throw new Error('Malformed response received from tokens API');
|
|
261
|
+
}
|
|
262
|
+
if (!Array.isArray(response.topTokens) ||
|
|
263
|
+
!Array.isArray(response.allTokens)) {
|
|
264
|
+
throw new Error('Malformed response received from tokens API');
|
|
265
|
+
}
|
|
266
|
+
return response;
|
|
267
|
+
}
|
|
248
268
|
}
|
|
249
269
|
_a = RampsService, _RampsService_messenger = new WeakMap(), _RampsService_fetch = new WeakMap(), _RampsService_policy = new WeakMap(), _RampsService_environment = new WeakMap(), _RampsService_context = new WeakMap(), _RampsService_instances = new WeakSet(), _RampsService_addCommonParams = function _RampsService_addCommonParams(url, action) {
|
|
250
270
|
if (action) {
|
|
@@ -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;AAmG1C;;GAEG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,OAAO,CAAC;AAEzC,kBAAkB;AAElB;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,cAAc,CAAC;AAE1C;;GAEG;AACH,MAAM,CAAN,IAAY,gBAIX;AAJD,WAAY,gBAAgB;IAC1B,6CAAyB,CAAA;IACzB,uCAAmB,CAAA;IACnB,+CAA2B,CAAA;AAC7B,CAAC,EAJW,gBAAgB,KAAhB,gBAAgB,QAI3B;AAED;;;GAGG;AACH,MAAM,CAAN,IAAY,eAGX;AAHD,WAAY,eAAe;IACzB,sCAAmB,CAAA;IACnB,oCAAiB,CAAA;AACnB,CAAC,EAHW,eAAe,KAAf,eAAe,QA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AO,uBAAA,IAAI,4BAAQ,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE;QACrC,MAAM,OAAO,GAAG,UAAU,CAAC,uBAAA,IAAI,iCAAa,EAAE,OAAO,CAAC,CAAC;QACvD,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 * 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 ramps.\n */\n supported?: boolean;\n /**\n * Whether this state is recommended.\n */\n recommended?: boolean;\n};\n\n/**\n * Represents eligibility information for a region.\n * Returned from the /regions/countries/{isoCode} endpoint.\n */\nexport type Eligibility = {\n /**\n * Whether aggregator providers are available.\n */\n aggregator?: boolean;\n /**\n * Whether deposit (buy) is available.\n */\n deposit?: boolean;\n /**\n * Whether global providers are available.\n */\n global?: boolean;\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 ramps.\n */\n supported: boolean;\n /**\n * Whether this country is recommended.\n */\n recommended?: boolean;\n /**\n * Array of state objects.\n */\n states?: State[];\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// === 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}\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 'getEligibility',\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 default:\n throw new Error(`Invalid environment: ${String(environment)}`);\n }\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 * 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 */\n constructor({\n messenger,\n environment = RampsEnvironment.Staging,\n context,\n fetch: fetchFunction,\n policyOptions = {},\n }: {\n messenger: RampsServiceMessenger;\n environment?: RampsEnvironment;\n context: string;\n fetch: typeof fetch;\n policyOptions?: CreateServicePolicyOptions;\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\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\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?: 'buy' | 'sell'): 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?: 'buy' | 'sell';\n responseType: 'json' | 'text';\n },\n ): Promise<TResponse> {\n return this.#policy.execute(async () => {\n const baseUrl = getBaseUrl(this.#environment, 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 * Filters countries based on aggregator support (preserves OnRampSDK logic).\n *\n * @param action - The ramp action type ('buy' or 'sell').\n * @returns An array of countries filtered by aggregator support.\n */\n async getCountries(action: 'buy' | 'sell' = 'buy'): Promise<Country[]> {\n const countries = await this.#request<Country[]>(\n RampsApiService.Regions,\n 'regions/countries',\n { action, 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 if (country.states && country.states.length > 0) {\n const hasSupportedState = country.states.some(\n (state) => state.supported !== false,\n );\n return country.supported || hasSupportedState;\n }\n\n return country.supported;\n });\n }\n\n /**\n * Fetches eligibility information for a specific region.\n *\n * @param isoCode - The ISO code for the region (e.g., \"us\", \"fr\", \"us-ny\").\n * @returns Eligibility information for the region.\n */\n async getEligibility(isoCode: string): Promise<Eligibility> {\n const normalizedIsoCode = isoCode.toLowerCase().trim();\n return this.#request<Eligibility>(\n RampsApiService.Regions,\n `regions/countries/${normalizedIsoCode}`,\n { responseType: 'json' },\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"RampsService.mjs","sourceRoot":"","sources":["../src/RampsService.ts"],"names":[],"mapp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,IAAY,EACZ,OAGC;IAED,OAAO,uBAAA,IAAI,4BAAQ,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE;QACrC,MAAM,OAAO,GAAG,UAAU,CAAC,uBAAA,IAAI,iCAAa,EAAE,OAAO,CAAC,CAAC;QACvD,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 * 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 ramps.\n */\n supported?: boolean;\n /**\n * Whether this state is recommended.\n */\n recommended?: boolean;\n};\n\n/**\n * Represents eligibility information for a region.\n * Returned from the /regions/countries/{isoCode} endpoint.\n */\nexport type Eligibility = {\n /**\n * Whether aggregator providers are available.\n */\n aggregator?: boolean;\n /**\n * Whether deposit (buy) is available.\n */\n deposit?: boolean;\n /**\n * Whether global providers are available.\n */\n global?: boolean;\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 ramps.\n */\n supported: boolean;\n /**\n * Whether this country is recommended.\n */\n recommended?: boolean;\n /**\n * Array of state objects.\n */\n states?: State[];\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/**\n * The SDK version to send with API requests. (backwards-compatibility)\n */\nexport const RAMPS_SDK_VERSION = '2.1.6';\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}\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 'getEligibility',\n 'getTokens',\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 default:\n throw new Error(`Invalid environment: ${String(environment)}`);\n }\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 * 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 */\n constructor({\n messenger,\n environment = RampsEnvironment.Staging,\n context,\n fetch: fetchFunction,\n policyOptions = {},\n }: {\n messenger: RampsServiceMessenger;\n environment?: RampsEnvironment;\n context: string;\n fetch: typeof fetch;\n policyOptions?: CreateServicePolicyOptions;\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\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\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?: 'buy' | 'sell'): 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?: 'buy' | 'sell';\n responseType: 'json' | 'text';\n },\n ): Promise<TResponse> {\n return this.#policy.execute(async () => {\n const baseUrl = getBaseUrl(this.#environment, 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 * Filters countries based on aggregator support (preserves OnRampSDK logic).\n *\n * @param action - The ramp action type ('buy' or 'sell').\n * @returns An array of countries filtered by aggregator support.\n */\n async getCountries(action: 'buy' | 'sell' = 'buy'): Promise<Country[]> {\n const countries = await this.#request<Country[]>(\n RampsApiService.Regions,\n 'regions/countries',\n { action, 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 if (country.states && country.states.length > 0) {\n const hasSupportedState = country.states.some(\n (state) => state.supported !== false,\n );\n return country.supported || hasSupportedState;\n }\n\n return country.supported;\n });\n }\n\n /**\n * Fetches eligibility information for a specific region.\n *\n * @param isoCode - The ISO code for the region (e.g., \"us\", \"fr\", \"us-ny\").\n * @returns Eligibility information for the region.\n */\n async getEligibility(isoCode: string): Promise<Eligibility> {\n const normalizedIsoCode = isoCode.toLowerCase().trim();\n return this.#request<Eligibility>(\n RampsApiService.Regions,\n `regions/countries/${normalizedIsoCode}`,\n { responseType: 'json' },\n );\n }\n\n /**\n * Fetches the list of available tokens for a given region and action.\n *\n * @param region - The region code (e.g., \"us\", \"fr\", \"us-ny\").\n * @param action - The ramp action type ('buy' or 'sell').\n * @returns The tokens response containing topTokens and allTokens.\n */\n async getTokens(\n region: string,\n action: 'buy' | 'sell' = 'buy',\n ): Promise<TokensResponse> {\n const normalizedRegion = region.toLowerCase().trim();\n const response = await this.#request<TokensResponse>(\n RampsApiService.Regions,\n `regions/${normalizedRegion}/tokens`,\n { action, responseType: 'json' },\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"]}
|
package/dist/selectors.cjs
CHANGED
|
@@ -15,7 +15,7 @@ const RequestCache_1 = require("./RequestCache.cjs");
|
|
|
15
15
|
*
|
|
16
16
|
* @param getState - Function that extracts RampsControllerState from the root state.
|
|
17
17
|
* Typically a reselect selector like `selectRampsControllerState`.
|
|
18
|
-
* @param method - The controller method name (e.g., '
|
|
18
|
+
* @param method - The controller method name (e.g., 'updateUserRegion').
|
|
19
19
|
* @param params - The parameters passed to the method, used to generate the cache key.
|
|
20
20
|
* Must match the params used when calling the controller method.
|
|
21
21
|
* @returns A selector function that returns `{ data, isFetching, error }`.
|
|
@@ -31,14 +31,14 @@ const RequestCache_1 = require("./RequestCache.cjs");
|
|
|
31
31
|
* (rampsControllerState) => rampsControllerState,
|
|
32
32
|
* );
|
|
33
33
|
*
|
|
34
|
-
* export const
|
|
34
|
+
* export const selectUserRegionRequest = createRequestSelector<
|
|
35
35
|
* RootState,
|
|
36
36
|
* string
|
|
37
|
-
* >(selectRampsControllerState, '
|
|
37
|
+
* >(selectRampsControllerState, 'updateUserRegion', []);
|
|
38
38
|
*
|
|
39
39
|
* // In hook - use directly with useSelector, no shallowEqual needed
|
|
40
|
-
* export function
|
|
41
|
-
* const { isFetching, error } = useSelector(
|
|
40
|
+
* export function useRampsUserRegion() {
|
|
41
|
+
* const { isFetching, error } = useSelector(selectUserRegionRequest);
|
|
42
42
|
* // ... rest of hook
|
|
43
43
|
* }
|
|
44
44
|
* ```
|
package/dist/selectors.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selectors.cjs","sourceRoot":"","sources":["../src/selectors.ts"],"names":[],"mappings":";;;AAEA,qDAA+D;AAkB/D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwDG;AACH,SAAgB,qBAAqB,CACnC,QAAqE,EACrE,MAAc,EACd,MAAiB;IAEjB,MAAM,QAAQ,GAAG,IAAA,6BAAc,EAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAEhD,IAAI,WAAqC,CAAC;IAC1C,IAAI,UAAU,GAAwC,IAAI,CAAC;IAE3D,OAAO,CAAC,KAAiB,EAAgC,EAAE;QACzD,MAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC,QAAQ,CAAC,CAAC;QAEtD,IAAI,OAAO,KAAK,WAAW,IAAI,UAAU,KAAK,IAAI,EAAE,CAAC;YACnD,OAAO,UAAU,CAAC;QACpB,CAAC;QAED,WAAW,GAAG,OAAO,CAAC;QACtB,UAAU,GAAG;YACX,IAAI,EAAG,OAAO,EAAE,IAAc,IAAI,IAAI;YACtC,UAAU,EAAE,OAAO,EAAE,MAAM,KAAK,4BAAa,CAAC,OAAO;YACrD,KAAK,EAAE,OAAO,EAAE,KAAK,IAAI,IAAI;SAC9B,CAAC;QAEF,OAAO,UAAU,CAAC;IACpB,CAAC,CAAC;AACJ,CAAC;AA1BD,sDA0BC","sourcesContent":["import type { RampsControllerState } from './RampsController';\nimport type { RequestState } from './RequestCache';\nimport { RequestStatus, createCacheKey } from './RequestCache';\n\n/**\n * Result shape returned by request selectors.\n *\n * This object is memoized - the same reference is returned when the underlying\n * request state hasn't changed, making it safe to use with React Redux's\n * `useSelector` without `shallowEqual`.\n */\nexport type RequestSelectorResult<TData> = {\n /** The data returned by the request, or null if not yet loaded or on error. */\n data: TData | null;\n /** Whether the request is currently in progress. */\n isFetching: boolean;\n /** Error message if the request failed, or null if successful or not yet attempted. */\n error: string | null;\n};\n\n/**\n * Creates a memoized selector for a controller method's request state.\n *\n * This selector tracks the loading, error, and data state for a specific\n * controller method call. It's optimized for use with React Redux's `useSelector`\n * hook - the selector returns the same object reference when the underlying\n * request state hasn't changed, so no `shallowEqual` is needed.\n *\n * The selector uses reference equality on the request object itself, so it\n * works correctly with arrays and objects without expensive deep equality checks.\n *\n * @param getState - Function that extracts RampsControllerState from the root state.\n * Typically a reselect selector like `selectRampsControllerState`.\n * @param method - The controller method name (e.g., '
|
|
1
|
+
{"version":3,"file":"selectors.cjs","sourceRoot":"","sources":["../src/selectors.ts"],"names":[],"mappings":";;;AAEA,qDAA+D;AAkB/D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwDG;AACH,SAAgB,qBAAqB,CACnC,QAAqE,EACrE,MAAc,EACd,MAAiB;IAEjB,MAAM,QAAQ,GAAG,IAAA,6BAAc,EAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAEhD,IAAI,WAAqC,CAAC;IAC1C,IAAI,UAAU,GAAwC,IAAI,CAAC;IAE3D,OAAO,CAAC,KAAiB,EAAgC,EAAE;QACzD,MAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC,QAAQ,CAAC,CAAC;QAEtD,IAAI,OAAO,KAAK,WAAW,IAAI,UAAU,KAAK,IAAI,EAAE,CAAC;YACnD,OAAO,UAAU,CAAC;QACpB,CAAC;QAED,WAAW,GAAG,OAAO,CAAC;QACtB,UAAU,GAAG;YACX,IAAI,EAAG,OAAO,EAAE,IAAc,IAAI,IAAI;YACtC,UAAU,EAAE,OAAO,EAAE,MAAM,KAAK,4BAAa,CAAC,OAAO;YACrD,KAAK,EAAE,OAAO,EAAE,KAAK,IAAI,IAAI;SAC9B,CAAC;QAEF,OAAO,UAAU,CAAC;IACpB,CAAC,CAAC;AACJ,CAAC;AA1BD,sDA0BC","sourcesContent":["import type { RampsControllerState } from './RampsController';\nimport type { RequestState } from './RequestCache';\nimport { RequestStatus, createCacheKey } from './RequestCache';\n\n/**\n * Result shape returned by request selectors.\n *\n * This object is memoized - the same reference is returned when the underlying\n * request state hasn't changed, making it safe to use with React Redux's\n * `useSelector` without `shallowEqual`.\n */\nexport type RequestSelectorResult<TData> = {\n /** The data returned by the request, or null if not yet loaded or on error. */\n data: TData | null;\n /** Whether the request is currently in progress. */\n isFetching: boolean;\n /** Error message if the request failed, or null if successful or not yet attempted. */\n error: string | null;\n};\n\n/**\n * Creates a memoized selector for a controller method's request state.\n *\n * This selector tracks the loading, error, and data state for a specific\n * controller method call. It's optimized for use with React Redux's `useSelector`\n * hook - the selector returns the same object reference when the underlying\n * request state hasn't changed, so no `shallowEqual` is needed.\n *\n * The selector uses reference equality on the request object itself, so it\n * works correctly with arrays and objects without expensive deep equality checks.\n *\n * @param getState - Function that extracts RampsControllerState from the root state.\n * Typically a reselect selector like `selectRampsControllerState`.\n * @param method - The controller method name (e.g., 'updateUserRegion').\n * @param params - The parameters passed to the method, used to generate the cache key.\n * Must match the params used when calling the controller method.\n * @returns A selector function that returns `{ data, isFetching, error }`.\n *\n * @example\n * ```ts\n * // In selectors file - create once at module level\n * import { createRequestSelector } from '@metamask/ramps-controller';\n * import { createSelector } from 'reselect';\n *\n * const selectRampsControllerState = createSelector(\n * (state: RootState) => state.engine.backgroundState.RampsController,\n * (rampsControllerState) => rampsControllerState,\n * );\n *\n * export const selectUserRegionRequest = createRequestSelector<\n * RootState,\n * string\n * >(selectRampsControllerState, 'updateUserRegion', []);\n *\n * // In hook - use directly with useSelector, no shallowEqual needed\n * export function useRampsUserRegion() {\n * const { isFetching, error } = useSelector(selectUserRegionRequest);\n * // ... rest of hook\n * }\n * ```\n *\n * @example\n * ```ts\n * // For methods with parameters\n * export const selectCryptoCurrenciesRequest = (region: string) =>\n * createRequestSelector<RootState, CryptoCurrency[]>(\n * selectRampsControllerState,\n * 'getCryptoCurrencies',\n * [region],\n * );\n *\n * // In component\n * const { data, isFetching, error } = useSelector(\n * selectCryptoCurrenciesRequest('US')\n * );\n * ```\n */\nexport function createRequestSelector<TRootState, TData>(\n getState: (rootState: TRootState) => RampsControllerState | undefined,\n method: string,\n params: unknown[],\n): (state: TRootState) => RequestSelectorResult<TData> {\n const cacheKey = createCacheKey(method, params);\n\n let lastRequest: RequestState | undefined;\n let lastResult: RequestSelectorResult<TData> | null = null;\n\n return (state: TRootState): RequestSelectorResult<TData> => {\n const request = getState(state)?.requests?.[cacheKey];\n\n if (request === lastRequest && lastResult !== null) {\n return lastResult;\n }\n\n lastRequest = request;\n lastResult = {\n data: (request?.data as TData) ?? null,\n isFetching: request?.status === RequestStatus.LOADING,\n error: request?.error ?? null,\n };\n\n return lastResult;\n };\n}\n"]}
|
package/dist/selectors.d.cts
CHANGED
|
@@ -27,7 +27,7 @@ export type RequestSelectorResult<TData> = {
|
|
|
27
27
|
*
|
|
28
28
|
* @param getState - Function that extracts RampsControllerState from the root state.
|
|
29
29
|
* Typically a reselect selector like `selectRampsControllerState`.
|
|
30
|
-
* @param method - The controller method name (e.g., '
|
|
30
|
+
* @param method - The controller method name (e.g., 'updateUserRegion').
|
|
31
31
|
* @param params - The parameters passed to the method, used to generate the cache key.
|
|
32
32
|
* Must match the params used when calling the controller method.
|
|
33
33
|
* @returns A selector function that returns `{ data, isFetching, error }`.
|
|
@@ -43,14 +43,14 @@ export type RequestSelectorResult<TData> = {
|
|
|
43
43
|
* (rampsControllerState) => rampsControllerState,
|
|
44
44
|
* );
|
|
45
45
|
*
|
|
46
|
-
* export const
|
|
46
|
+
* export const selectUserRegionRequest = createRequestSelector<
|
|
47
47
|
* RootState,
|
|
48
48
|
* string
|
|
49
|
-
* >(selectRampsControllerState, '
|
|
49
|
+
* >(selectRampsControllerState, 'updateUserRegion', []);
|
|
50
50
|
*
|
|
51
51
|
* // In hook - use directly with useSelector, no shallowEqual needed
|
|
52
|
-
* export function
|
|
53
|
-
* const { isFetching, error } = useSelector(
|
|
52
|
+
* export function useRampsUserRegion() {
|
|
53
|
+
* const { isFetching, error } = useSelector(selectUserRegionRequest);
|
|
54
54
|
* // ... rest of hook
|
|
55
55
|
* }
|
|
56
56
|
* ```
|
package/dist/selectors.d.mts
CHANGED
|
@@ -27,7 +27,7 @@ export type RequestSelectorResult<TData> = {
|
|
|
27
27
|
*
|
|
28
28
|
* @param getState - Function that extracts RampsControllerState from the root state.
|
|
29
29
|
* Typically a reselect selector like `selectRampsControllerState`.
|
|
30
|
-
* @param method - The controller method name (e.g., '
|
|
30
|
+
* @param method - The controller method name (e.g., 'updateUserRegion').
|
|
31
31
|
* @param params - The parameters passed to the method, used to generate the cache key.
|
|
32
32
|
* Must match the params used when calling the controller method.
|
|
33
33
|
* @returns A selector function that returns `{ data, isFetching, error }`.
|
|
@@ -43,14 +43,14 @@ export type RequestSelectorResult<TData> = {
|
|
|
43
43
|
* (rampsControllerState) => rampsControllerState,
|
|
44
44
|
* );
|
|
45
45
|
*
|
|
46
|
-
* export const
|
|
46
|
+
* export const selectUserRegionRequest = createRequestSelector<
|
|
47
47
|
* RootState,
|
|
48
48
|
* string
|
|
49
|
-
* >(selectRampsControllerState, '
|
|
49
|
+
* >(selectRampsControllerState, 'updateUserRegion', []);
|
|
50
50
|
*
|
|
51
51
|
* // In hook - use directly with useSelector, no shallowEqual needed
|
|
52
|
-
* export function
|
|
53
|
-
* const { isFetching, error } = useSelector(
|
|
52
|
+
* export function useRampsUserRegion() {
|
|
53
|
+
* const { isFetching, error } = useSelector(selectUserRegionRequest);
|
|
54
54
|
* // ... rest of hook
|
|
55
55
|
* }
|
|
56
56
|
* ```
|
package/dist/selectors.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { RequestStatus, createCacheKey } from "./RequestCache.mjs";
|
|
|
12
12
|
*
|
|
13
13
|
* @param getState - Function that extracts RampsControllerState from the root state.
|
|
14
14
|
* Typically a reselect selector like `selectRampsControllerState`.
|
|
15
|
-
* @param method - The controller method name (e.g., '
|
|
15
|
+
* @param method - The controller method name (e.g., 'updateUserRegion').
|
|
16
16
|
* @param params - The parameters passed to the method, used to generate the cache key.
|
|
17
17
|
* Must match the params used when calling the controller method.
|
|
18
18
|
* @returns A selector function that returns `{ data, isFetching, error }`.
|
|
@@ -28,14 +28,14 @@ import { RequestStatus, createCacheKey } from "./RequestCache.mjs";
|
|
|
28
28
|
* (rampsControllerState) => rampsControllerState,
|
|
29
29
|
* );
|
|
30
30
|
*
|
|
31
|
-
* export const
|
|
31
|
+
* export const selectUserRegionRequest = createRequestSelector<
|
|
32
32
|
* RootState,
|
|
33
33
|
* string
|
|
34
|
-
* >(selectRampsControllerState, '
|
|
34
|
+
* >(selectRampsControllerState, 'updateUserRegion', []);
|
|
35
35
|
*
|
|
36
36
|
* // In hook - use directly with useSelector, no shallowEqual needed
|
|
37
|
-
* export function
|
|
38
|
-
* const { isFetching, error } = useSelector(
|
|
37
|
+
* export function useRampsUserRegion() {
|
|
38
|
+
* const { isFetching, error } = useSelector(selectUserRegionRequest);
|
|
39
39
|
* // ... rest of hook
|
|
40
40
|
* }
|
|
41
41
|
* ```
|
package/dist/selectors.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selectors.mjs","sourceRoot":"","sources":["../src/selectors.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,2BAAuB;AAkB/D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwDG;AACH,MAAM,UAAU,qBAAqB,CACnC,QAAqE,EACrE,MAAc,EACd,MAAiB;IAEjB,MAAM,QAAQ,GAAG,cAAc,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAEhD,IAAI,WAAqC,CAAC;IAC1C,IAAI,UAAU,GAAwC,IAAI,CAAC;IAE3D,OAAO,CAAC,KAAiB,EAAgC,EAAE;QACzD,MAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC,QAAQ,CAAC,CAAC;QAEtD,IAAI,OAAO,KAAK,WAAW,IAAI,UAAU,KAAK,IAAI,EAAE,CAAC;YACnD,OAAO,UAAU,CAAC;QACpB,CAAC;QAED,WAAW,GAAG,OAAO,CAAC;QACtB,UAAU,GAAG;YACX,IAAI,EAAG,OAAO,EAAE,IAAc,IAAI,IAAI;YACtC,UAAU,EAAE,OAAO,EAAE,MAAM,KAAK,aAAa,CAAC,OAAO;YACrD,KAAK,EAAE,OAAO,EAAE,KAAK,IAAI,IAAI;SAC9B,CAAC;QAEF,OAAO,UAAU,CAAC;IACpB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { RampsControllerState } from './RampsController';\nimport type { RequestState } from './RequestCache';\nimport { RequestStatus, createCacheKey } from './RequestCache';\n\n/**\n * Result shape returned by request selectors.\n *\n * This object is memoized - the same reference is returned when the underlying\n * request state hasn't changed, making it safe to use with React Redux's\n * `useSelector` without `shallowEqual`.\n */\nexport type RequestSelectorResult<TData> = {\n /** The data returned by the request, or null if not yet loaded or on error. */\n data: TData | null;\n /** Whether the request is currently in progress. */\n isFetching: boolean;\n /** Error message if the request failed, or null if successful or not yet attempted. */\n error: string | null;\n};\n\n/**\n * Creates a memoized selector for a controller method's request state.\n *\n * This selector tracks the loading, error, and data state for a specific\n * controller method call. It's optimized for use with React Redux's `useSelector`\n * hook - the selector returns the same object reference when the underlying\n * request state hasn't changed, so no `shallowEqual` is needed.\n *\n * The selector uses reference equality on the request object itself, so it\n * works correctly with arrays and objects without expensive deep equality checks.\n *\n * @param getState - Function that extracts RampsControllerState from the root state.\n * Typically a reselect selector like `selectRampsControllerState`.\n * @param method - The controller method name (e.g., '
|
|
1
|
+
{"version":3,"file":"selectors.mjs","sourceRoot":"","sources":["../src/selectors.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,2BAAuB;AAkB/D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwDG;AACH,MAAM,UAAU,qBAAqB,CACnC,QAAqE,EACrE,MAAc,EACd,MAAiB;IAEjB,MAAM,QAAQ,GAAG,cAAc,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAEhD,IAAI,WAAqC,CAAC;IAC1C,IAAI,UAAU,GAAwC,IAAI,CAAC;IAE3D,OAAO,CAAC,KAAiB,EAAgC,EAAE;QACzD,MAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC,QAAQ,CAAC,CAAC;QAEtD,IAAI,OAAO,KAAK,WAAW,IAAI,UAAU,KAAK,IAAI,EAAE,CAAC;YACnD,OAAO,UAAU,CAAC;QACpB,CAAC;QAED,WAAW,GAAG,OAAO,CAAC;QACtB,UAAU,GAAG;YACX,IAAI,EAAG,OAAO,EAAE,IAAc,IAAI,IAAI;YACtC,UAAU,EAAE,OAAO,EAAE,MAAM,KAAK,aAAa,CAAC,OAAO;YACrD,KAAK,EAAE,OAAO,EAAE,KAAK,IAAI,IAAI;SAC9B,CAAC;QAEF,OAAO,UAAU,CAAC;IACpB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { RampsControllerState } from './RampsController';\nimport type { RequestState } from './RequestCache';\nimport { RequestStatus, createCacheKey } from './RequestCache';\n\n/**\n * Result shape returned by request selectors.\n *\n * This object is memoized - the same reference is returned when the underlying\n * request state hasn't changed, making it safe to use with React Redux's\n * `useSelector` without `shallowEqual`.\n */\nexport type RequestSelectorResult<TData> = {\n /** The data returned by the request, or null if not yet loaded or on error. */\n data: TData | null;\n /** Whether the request is currently in progress. */\n isFetching: boolean;\n /** Error message if the request failed, or null if successful or not yet attempted. */\n error: string | null;\n};\n\n/**\n * Creates a memoized selector for a controller method's request state.\n *\n * This selector tracks the loading, error, and data state for a specific\n * controller method call. It's optimized for use with React Redux's `useSelector`\n * hook - the selector returns the same object reference when the underlying\n * request state hasn't changed, so no `shallowEqual` is needed.\n *\n * The selector uses reference equality on the request object itself, so it\n * works correctly with arrays and objects without expensive deep equality checks.\n *\n * @param getState - Function that extracts RampsControllerState from the root state.\n * Typically a reselect selector like `selectRampsControllerState`.\n * @param method - The controller method name (e.g., 'updateUserRegion').\n * @param params - The parameters passed to the method, used to generate the cache key.\n * Must match the params used when calling the controller method.\n * @returns A selector function that returns `{ data, isFetching, error }`.\n *\n * @example\n * ```ts\n * // In selectors file - create once at module level\n * import { createRequestSelector } from '@metamask/ramps-controller';\n * import { createSelector } from 'reselect';\n *\n * const selectRampsControllerState = createSelector(\n * (state: RootState) => state.engine.backgroundState.RampsController,\n * (rampsControllerState) => rampsControllerState,\n * );\n *\n * export const selectUserRegionRequest = createRequestSelector<\n * RootState,\n * string\n * >(selectRampsControllerState, 'updateUserRegion', []);\n *\n * // In hook - use directly with useSelector, no shallowEqual needed\n * export function useRampsUserRegion() {\n * const { isFetching, error } = useSelector(selectUserRegionRequest);\n * // ... rest of hook\n * }\n * ```\n *\n * @example\n * ```ts\n * // For methods with parameters\n * export const selectCryptoCurrenciesRequest = (region: string) =>\n * createRequestSelector<RootState, CryptoCurrency[]>(\n * selectRampsControllerState,\n * 'getCryptoCurrencies',\n * [region],\n * );\n *\n * // In component\n * const { data, isFetching, error } = useSelector(\n * selectCryptoCurrenciesRequest('US')\n * );\n * ```\n */\nexport function createRequestSelector<TRootState, TData>(\n getState: (rootState: TRootState) => RampsControllerState | undefined,\n method: string,\n params: unknown[],\n): (state: TRootState) => RequestSelectorResult<TData> {\n const cacheKey = createCacheKey(method, params);\n\n let lastRequest: RequestState | undefined;\n let lastResult: RequestSelectorResult<TData> | null = null;\n\n return (state: TRootState): RequestSelectorResult<TData> => {\n const request = getState(state)?.requests?.[cacheKey];\n\n if (request === lastRequest && lastResult !== null) {\n return lastResult;\n }\n\n lastRequest = request;\n lastResult = {\n data: (request?.data as TData) ?? null,\n isFetching: request?.status === RequestStatus.LOADING,\n error: request?.error ?? null,\n };\n\n return lastResult;\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/ramps-controller",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "A controller for managing cryptocurrency on/off ramps functionality",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
52
|
"@metamask/base-controller": "^9.0.0",
|
|
53
|
-
"@metamask/controller-utils": "^11.
|
|
53
|
+
"@metamask/controller-utils": "^11.18.0",
|
|
54
54
|
"@metamask/messenger": "^0.3.0"
|
|
55
55
|
},
|
|
56
56
|
"devDependencies": {
|