@metamask-previews/ramps-controller 3.0.0-preview-a4747b2b → 4.0.0-preview-4a66b658
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 +6 -1
- package/dist/RampsController.cjs +80 -2
- package/dist/RampsController.cjs.map +1 -1
- package/dist/RampsController.d.cts +26 -2
- package/dist/RampsController.d.cts.map +1 -1
- package/dist/RampsController.d.mts +26 -2
- package/dist/RampsController.d.mts.map +1 -1
- package/dist/RampsController.mjs +80 -2
- 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 +17 -1
- package/dist/RampsService-method-action-types.d.cts.map +1 -1
- package/dist/RampsService-method-action-types.d.mts +17 -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 +56 -0
- package/dist/RampsService.cjs.map +1 -1
- package/dist/RampsService.d.cts +20 -0
- package/dist/RampsService.d.cts.map +1 -1
- package/dist/RampsService.d.mts +20 -0
- package/dist/RampsService.d.mts.map +1 -1
- package/dist/RampsService.mjs +56 -0
- package/dist/RampsService.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [4.0.0]
|
|
11
|
+
|
|
10
12
|
### Added
|
|
11
13
|
|
|
12
14
|
- Add `preferredProvider` state and `setPreferredProvider()` method to RampsController ([#7617](https://github.com/MetaMask/core/pull/7617))
|
|
@@ -15,6 +17,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
15
17
|
|
|
16
18
|
- Add `defaultAmount` and `quickAmounts` fields to the `Country` type ([#7645](https://github.com/MetaMask/core/pull/7645))
|
|
17
19
|
|
|
20
|
+
- Add `providers` state and `getProviders()` method to RampsController. Providers are automatically fetched on init and when the region changes ([#7652](https://github.com/MetaMask/core/pull/7652))
|
|
21
|
+
|
|
18
22
|
### Changed
|
|
19
23
|
|
|
20
24
|
- **BREAKING:** Change `userRegion` from `string | null` to `UserRegion | null`. Access region code via `userRegion.regionCode`. ([#7646](https://github.com/MetaMask/core/pull/7646))
|
|
@@ -75,7 +79,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
75
79
|
- Add `OnRampService` for interacting with the OnRamp API
|
|
76
80
|
- Add geolocation detection via IP address lookup
|
|
77
81
|
|
|
78
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/ramps-controller@
|
|
82
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/ramps-controller@4.0.0...HEAD
|
|
83
|
+
[4.0.0]: https://github.com/MetaMask/core/compare/@metamask/ramps-controller@3.0.0...@metamask/ramps-controller@4.0.0
|
|
79
84
|
[3.0.0]: https://github.com/MetaMask/core/compare/@metamask/ramps-controller@2.1.0...@metamask/ramps-controller@3.0.0
|
|
80
85
|
[2.1.0]: https://github.com/MetaMask/core/compare/@metamask/ramps-controller@2.0.0...@metamask/ramps-controller@2.1.0
|
|
81
86
|
[2.0.0]: https://github.com/MetaMask/core/compare/@metamask/ramps-controller@1.0.0...@metamask/ramps-controller@2.0.0
|
package/dist/RampsController.cjs
CHANGED
|
@@ -38,6 +38,12 @@ const rampsControllerMetadata = {
|
|
|
38
38
|
includeInStateLogs: true,
|
|
39
39
|
usedInUi: true,
|
|
40
40
|
},
|
|
41
|
+
providers: {
|
|
42
|
+
persist: true,
|
|
43
|
+
includeInDebugSnapshot: true,
|
|
44
|
+
includeInStateLogs: true,
|
|
45
|
+
usedInUi: true,
|
|
46
|
+
},
|
|
41
47
|
tokens: {
|
|
42
48
|
persist: true,
|
|
43
49
|
includeInDebugSnapshot: true,
|
|
@@ -63,6 +69,7 @@ function getDefaultRampsControllerState() {
|
|
|
63
69
|
return {
|
|
64
70
|
userRegion: null,
|
|
65
71
|
preferredProvider: null,
|
|
72
|
+
providers: [],
|
|
66
73
|
tokens: null,
|
|
67
74
|
requests: {},
|
|
68
75
|
};
|
|
@@ -268,11 +275,12 @@ class RampsController extends base_controller_1.BaseController {
|
|
|
268
275
|
if (this.state.userRegion && !options?.forceRefresh) {
|
|
269
276
|
return this.state.userRegion;
|
|
270
277
|
}
|
|
271
|
-
// When forceRefresh is true, clear the existing region and
|
|
278
|
+
// When forceRefresh is true, clear the existing region, tokens, and providers before fetching
|
|
272
279
|
if (options?.forceRefresh) {
|
|
273
280
|
this.update((state) => {
|
|
274
281
|
state.userRegion = null;
|
|
275
282
|
state.tokens = null;
|
|
283
|
+
state.providers = [];
|
|
276
284
|
});
|
|
277
285
|
}
|
|
278
286
|
const cacheKey = (0, RequestCache_1.createCacheKey)('updateUserRegion', []);
|
|
@@ -284,6 +292,7 @@ class RampsController extends base_controller_1.BaseController {
|
|
|
284
292
|
this.update((state) => {
|
|
285
293
|
state.userRegion = null;
|
|
286
294
|
state.tokens = null;
|
|
295
|
+
state.providers = [];
|
|
287
296
|
});
|
|
288
297
|
return null;
|
|
289
298
|
}
|
|
@@ -295,17 +304,28 @@ class RampsController extends base_controller_1.BaseController {
|
|
|
295
304
|
this.update((state) => {
|
|
296
305
|
const regionChanged = state.userRegion?.regionCode !== userRegion.regionCode;
|
|
297
306
|
state.userRegion = userRegion;
|
|
298
|
-
// Clear tokens when region changes
|
|
307
|
+
// Clear tokens and providers when region changes
|
|
299
308
|
if (regionChanged) {
|
|
300
309
|
state.tokens = null;
|
|
310
|
+
state.providers = [];
|
|
301
311
|
}
|
|
302
312
|
});
|
|
313
|
+
// Fetch providers for the new region
|
|
314
|
+
if (userRegion.regionCode) {
|
|
315
|
+
try {
|
|
316
|
+
await this.getProviders(userRegion.regionCode, options);
|
|
317
|
+
}
|
|
318
|
+
catch {
|
|
319
|
+
// Provider fetch failed - error state will be available via selectors
|
|
320
|
+
}
|
|
321
|
+
}
|
|
303
322
|
return userRegion;
|
|
304
323
|
}
|
|
305
324
|
// Region not found in countries data
|
|
306
325
|
this.update((state) => {
|
|
307
326
|
state.userRegion = null;
|
|
308
327
|
state.tokens = null;
|
|
328
|
+
state.providers = [];
|
|
309
329
|
});
|
|
310
330
|
return null;
|
|
311
331
|
}
|
|
@@ -315,6 +335,7 @@ class RampsController extends base_controller_1.BaseController {
|
|
|
315
335
|
this.update((state) => {
|
|
316
336
|
state.userRegion = null;
|
|
317
337
|
state.tokens = null;
|
|
338
|
+
state.providers = [];
|
|
318
339
|
});
|
|
319
340
|
return null;
|
|
320
341
|
}
|
|
@@ -336,13 +357,22 @@ class RampsController extends base_controller_1.BaseController {
|
|
|
336
357
|
this.update((state) => {
|
|
337
358
|
state.userRegion = userRegion;
|
|
338
359
|
state.tokens = null;
|
|
360
|
+
state.providers = [];
|
|
339
361
|
});
|
|
362
|
+
// Fetch providers for the new region
|
|
363
|
+
try {
|
|
364
|
+
await this.getProviders(userRegion.regionCode, options);
|
|
365
|
+
}
|
|
366
|
+
catch {
|
|
367
|
+
// Provider fetch failed - error state will be available via selectors
|
|
368
|
+
}
|
|
340
369
|
return userRegion;
|
|
341
370
|
}
|
|
342
371
|
// Region not found in countries data
|
|
343
372
|
this.update((state) => {
|
|
344
373
|
state.userRegion = null;
|
|
345
374
|
state.tokens = null;
|
|
375
|
+
state.providers = [];
|
|
346
376
|
});
|
|
347
377
|
throw new Error(`Region "${normalizedRegion}" not found in countries data. Cannot set user region without valid country information.`);
|
|
348
378
|
}
|
|
@@ -356,6 +386,7 @@ class RampsController extends base_controller_1.BaseController {
|
|
|
356
386
|
this.update((state) => {
|
|
357
387
|
state.userRegion = null;
|
|
358
388
|
state.tokens = null;
|
|
389
|
+
state.providers = [];
|
|
359
390
|
});
|
|
360
391
|
throw new Error('Failed to fetch countries data. Cannot set user region without valid country information.');
|
|
361
392
|
}
|
|
@@ -394,6 +425,12 @@ class RampsController extends base_controller_1.BaseController {
|
|
|
394
425
|
catch {
|
|
395
426
|
// Token fetch failed - error state will be available via selectors
|
|
396
427
|
}
|
|
428
|
+
try {
|
|
429
|
+
await this.getProviders(userRegion.regionCode, options);
|
|
430
|
+
}
|
|
431
|
+
catch {
|
|
432
|
+
// Provider fetch failed - error state will be available via selectors
|
|
433
|
+
}
|
|
397
434
|
}
|
|
398
435
|
}
|
|
399
436
|
/**
|
|
@@ -436,6 +473,47 @@ class RampsController extends base_controller_1.BaseController {
|
|
|
436
473
|
});
|
|
437
474
|
return tokens;
|
|
438
475
|
}
|
|
476
|
+
/**
|
|
477
|
+
* Fetches the list of providers for a given region.
|
|
478
|
+
* The providers are saved in the controller state once fetched.
|
|
479
|
+
*
|
|
480
|
+
* @param region - The region code (e.g., "us", "fr", "us-ny"). If not provided, uses the user's region from controller state.
|
|
481
|
+
* @param options - Options for cache behavior and query filters.
|
|
482
|
+
* @param options.provider - Provider ID(s) to filter by.
|
|
483
|
+
* @param options.crypto - Crypto currency ID(s) to filter by.
|
|
484
|
+
* @param options.fiat - Fiat currency ID(s) to filter by.
|
|
485
|
+
* @param options.payments - Payment method ID(s) to filter by.
|
|
486
|
+
* @returns The providers response containing providers array.
|
|
487
|
+
*/
|
|
488
|
+
async getProviders(region, options) {
|
|
489
|
+
const regionToUse = region ?? this.state.userRegion?.regionCode;
|
|
490
|
+
if (!regionToUse) {
|
|
491
|
+
throw new Error('Region is required. Either provide a region parameter or ensure userRegion is set in controller state.');
|
|
492
|
+
}
|
|
493
|
+
const normalizedRegion = regionToUse.toLowerCase().trim();
|
|
494
|
+
const cacheKey = (0, RequestCache_1.createCacheKey)('getProviders', [
|
|
495
|
+
normalizedRegion,
|
|
496
|
+
options?.provider,
|
|
497
|
+
options?.crypto,
|
|
498
|
+
options?.fiat,
|
|
499
|
+
options?.payments,
|
|
500
|
+
]);
|
|
501
|
+
const { providers } = await this.executeRequest(cacheKey, async () => {
|
|
502
|
+
return this.messenger.call('RampsService:getProviders', normalizedRegion, {
|
|
503
|
+
provider: options?.provider,
|
|
504
|
+
crypto: options?.crypto,
|
|
505
|
+
fiat: options?.fiat,
|
|
506
|
+
payments: options?.payments,
|
|
507
|
+
});
|
|
508
|
+
}, options);
|
|
509
|
+
this.update((state) => {
|
|
510
|
+
const userRegionCode = state.userRegion?.regionCode;
|
|
511
|
+
if (userRegionCode === undefined || userRegionCode === normalizedRegion) {
|
|
512
|
+
state.providers = providers;
|
|
513
|
+
}
|
|
514
|
+
});
|
|
515
|
+
return { providers };
|
|
516
|
+
}
|
|
439
517
|
}
|
|
440
518
|
exports.RampsController = RampsController;
|
|
441
519
|
_RampsController_requestCacheTTL = new WeakMap(), _RampsController_requestCacheMaxSize = new WeakMap(), _RampsController_pendingRequests = new WeakMap(), _RampsController_instances = new WeakSet(), _RampsController_removeRequestState = function _RampsController_removeRequestState(cacheKey) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RampsController.cjs","sourceRoot":"","sources":["../src/RampsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,+DAA2D;AAgB3D,qDAQwB;AAExB,kBAAkB;AAElB;;;;GAIG;AACU,QAAA,cAAc,GAAG,iBAAiB,CAAC;AAkDhD;;GAEG;AACH,MAAM,uBAAuB,GAAG;IAC9B,UAAU,EAAE;QACV,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,kBAAkB,EAAE,IAAI;QACxB,QAAQ,EAAE,IAAI;KACf;IACD,iBAAiB,EAAE;QACjB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,kBAAkB,EAAE,IAAI;QACxB,QAAQ,EAAE,IAAI;KACf;IACD,MAAM,EAAE;QACN,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,kBAAkB,EAAE,IAAI;QACxB,QAAQ,EAAE,IAAI;KACf;IACD,QAAQ,EAAE;QACR,OAAO,EAAE,KAAK;QACd,sBAAsB,E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AAI,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAEnC,IAAI,IAAI,CAAC,MAAM,GAAG,OAAO,EAAE,CAAC;YAC1B,mCAAmC;YACnC,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;gBACpC,MAAM,KAAK,GAAG,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,IAAI,CAAC,CAAC;gBAC1C,MAAM,KAAK,GAAG,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,IAAI,CAAC,CAAC;gBAC1C,OAAO,KAAK,GAAG,KAAK,CAAC;YACvB,CAAC,CAAC,CAAC;YAEH,oDAAoD;YACpD,MAAM,eAAe,GAAG,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC;YAC9C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,eAAe,EAAE,CAAC,EAAE,EAAE,CAAC;gBACzC,MAAM,WAAW,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;gBAClC,IAAI,WAAW,EAAE,CAAC;oBAChB,OAAO,QAAQ,CAAC,WAAW,CAAC,CAAC;gBAC/B,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { Json } from '@metamask/utils';\n\nimport type { Country, TokensResponse, Provider, State } from './RampsService';\nimport type {\n RampsServiceGetGeolocationAction,\n RampsServiceGetCountriesAction,\n RampsServiceGetTokensAction,\n} from './RampsService-method-action-types';\nimport type {\n RequestCache as RequestCacheType,\n RequestState,\n ExecuteRequestOptions,\n PendingRequest,\n} from './RequestCache';\nimport {\n DEFAULT_REQUEST_CACHE_TTL,\n DEFAULT_REQUEST_CACHE_MAX_SIZE,\n createCacheKey,\n isCacheExpired,\n createLoadingState,\n createSuccessState,\n createErrorState,\n} from './RequestCache';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link RampsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'RampsController';\n\n// === STATE ===\n\n/**\n * Represents the user's selected region with full country and state objects.\n */\nexport type UserRegion = {\n /**\n * The country object for the selected region.\n */\n country: Country;\n /**\n * The state object if a state was selected, null if only country was selected.\n */\n state: State | null;\n /**\n * The region code string (e.g., \"us-ut\" or \"fr\") used for API calls.\n */\n regionCode: string;\n};\n\n/**\n * Describes the shape of the state object for {@link RampsController}.\n */\nexport type RampsControllerState = {\n /**\n * The user's selected region with full country and state objects.\n * Initially set via geolocation fetch, but can be manually changed by the user.\n * Once set (either via geolocation or manual selection), it will not be overwritten\n * by subsequent geolocation fetches.\n */\n userRegion: UserRegion | null;\n /**\n * The user's preferred provider.\n * Can be manually set by the user.\n */\n preferredProvider: Provider | null;\n /**\n * Tokens fetched for the current region and action.\n * Contains topTokens and allTokens arrays.\n */\n tokens: TokensResponse | null;\n /**\n * Cache of request states, keyed by cache key.\n * This stores loading, success, and error states for API requests.\n */\n requests: RequestCacheType;\n};\n\n/**\n * The metadata for each property in {@link RampsControllerState}.\n */\nconst rampsControllerMetadata = {\n userRegion: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n preferredProvider: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n tokens: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n requests: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: false,\n usedInUi: true,\n },\n} satisfies StateMetadata<RampsControllerState>;\n\n/**\n * Constructs the default {@link RampsController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link RampsController} state.\n */\nexport function getDefaultRampsControllerState(): RampsControllerState {\n return {\n userRegion: null,\n preferredProvider: null,\n tokens: null,\n requests: {},\n };\n}\n\n// === MESSENGER ===\n\n/**\n * Retrieves the state of the {@link RampsController}.\n */\nexport type RampsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n RampsControllerState\n>;\n\n/**\n * Actions that {@link RampsControllerMessenger} exposes to other consumers.\n */\nexport type RampsControllerActions = RampsControllerGetStateAction;\n\n/**\n * Actions from other messengers that {@link RampsController} calls.\n */\ntype AllowedActions =\n | RampsServiceGetGeolocationAction\n | RampsServiceGetCountriesAction\n | RampsServiceGetTokensAction;\n\n/**\n * Published when the state of {@link RampsController} changes.\n */\nexport type RampsControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n RampsControllerState\n>;\n\n/**\n * Events that {@link RampsControllerMessenger} exposes to other consumers.\n */\nexport type RampsControllerEvents = RampsControllerStateChangeEvent;\n\n/**\n * Events from other messengers that {@link RampsController} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link RampsController}.\n */\nexport type RampsControllerMessenger = Messenger<\n typeof controllerName,\n RampsControllerActions | AllowedActions,\n RampsControllerEvents | AllowedEvents\n>;\n\n/**\n * Configuration options for the RampsController.\n */\nexport type RampsControllerOptions = {\n /** The messenger suited for this controller. */\n messenger: RampsControllerMessenger;\n /** The desired state with which to initialize this controller. */\n state?: Partial<RampsControllerState>;\n /** Time to live for cached requests in milliseconds. Defaults to 15 minutes. */\n requestCacheTTL?: number;\n /** Maximum number of entries in the request cache. Defaults to 250. */\n requestCacheMaxSize?: number;\n};\n\n// === HELPER FUNCTIONS ===\n\n/**\n * Finds a country and state from a region code string.\n *\n * @param regionCode - The region code (e.g., \"us-ca\" or \"us\").\n * @param countries - Array of countries to search.\n * @returns UserRegion object with country and state, or null if not found.\n */\nfunction findRegionFromCode(\n regionCode: string,\n countries: Country[],\n): UserRegion | null {\n const normalizedCode = regionCode.toLowerCase().trim();\n const parts = normalizedCode.split('-');\n const countryCode = parts[0];\n const stateCode = parts[1];\n\n const country = countries.find((countryItem) => {\n if (countryItem.isoCode?.toLowerCase() === countryCode) {\n return true;\n }\n if (countryItem.id) {\n const id = countryItem.id.toLowerCase();\n if (id.startsWith('/regions/')) {\n const extractedCode = id.replace('/regions/', '').split('/')[0];\n return extractedCode === countryCode;\n }\n return id === countryCode || id.endsWith(`/${countryCode}`);\n }\n return false;\n });\n\n if (!country) {\n return null;\n }\n\n let state: State | null = null;\n if (stateCode && country.states) {\n state =\n country.states.find((stateItem) => {\n if (stateItem.stateId?.toLowerCase() === stateCode) {\n return true;\n }\n if (stateItem.id) {\n const stateId = stateItem.id.toLowerCase();\n if (\n stateId.includes(`-${stateCode}`) ||\n stateId.endsWith(`/${stateCode}`)\n ) {\n return true;\n }\n }\n return false;\n }) ?? null;\n }\n\n return {\n country,\n state,\n regionCode: normalizedCode,\n };\n}\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * Manages cryptocurrency on/off ramps functionality.\n */\nexport class RampsController extends BaseController<\n typeof controllerName,\n RampsControllerState,\n RampsControllerMessenger\n> {\n /**\n * Default TTL for cached requests.\n */\n readonly #requestCacheTTL: number;\n\n /**\n * Maximum number of entries in the request cache.\n */\n readonly #requestCacheMaxSize: number;\n\n /**\n * Map of pending requests for deduplication.\n * Key is the cache key, value is the pending request with abort controller.\n */\n readonly #pendingRequests: Map<string, PendingRequest> = new Map();\n\n /**\n * Constructs a new {@link RampsController}.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this controller.\n * @param args.state - The desired state with which to initialize this\n * controller. Missing properties will be filled in with defaults.\n * @param args.requestCacheTTL - Time to live for cached requests in milliseconds.\n * @param args.requestCacheMaxSize - Maximum number of entries in the request cache.\n */\n constructor({\n messenger,\n state = {},\n requestCacheTTL = DEFAULT_REQUEST_CACHE_TTL,\n requestCacheMaxSize = DEFAULT_REQUEST_CACHE_MAX_SIZE,\n }: RampsControllerOptions) {\n super({\n messenger,\n metadata: rampsControllerMetadata,\n name: controllerName,\n state: {\n ...getDefaultRampsControllerState(),\n ...state,\n // Always reset requests cache on initialization (non-persisted)\n requests: {},\n },\n });\n\n this.#requestCacheTTL = requestCacheTTL;\n this.#requestCacheMaxSize = requestCacheMaxSize;\n }\n\n /**\n * Executes a request with caching and deduplication.\n *\n * If a request with the same cache key is already in flight, returns the\n * existing promise. If valid cached data exists, returns it without making\n * a new request.\n *\n * @param cacheKey - Unique identifier for this request.\n * @param fetcher - Function that performs the actual fetch. Receives an AbortSignal.\n * @param options - Options for cache behavior.\n * @returns The result of the request.\n */\n async executeRequest<TResult>(\n cacheKey: string,\n fetcher: (signal: AbortSignal) => Promise<TResult>,\n options?: ExecuteRequestOptions,\n ): Promise<TResult> {\n const ttl = options?.ttl ?? this.#requestCacheTTL;\n\n // Check for existing pending request - join it instead of making a duplicate\n const pending = this.#pendingRequests.get(cacheKey);\n if (pending) {\n return pending.promise as Promise<TResult>;\n }\n\n // Check cache validity (unless force refresh)\n if (!options?.forceRefresh) {\n const cached = this.state.requests[cacheKey];\n if (cached && !isCacheExpired(cached, ttl)) {\n return cached.data as TResult;\n }\n }\n\n // Create abort controller for this request\n const abortController = new AbortController();\n const lastFetchedAt = Date.now();\n\n // Update state to loading\n this.#updateRequestState(cacheKey, createLoadingState());\n\n // Create the fetch promise\n const promise = (async (): Promise<TResult> => {\n try {\n const data = await fetcher(abortController.signal);\n\n // Don't update state if aborted\n if (abortController.signal.aborted) {\n throw new Error('Request was aborted');\n }\n\n this.#updateRequestState(\n cacheKey,\n createSuccessState(data as Json, lastFetchedAt),\n );\n return data;\n } catch (error) {\n // Don't update state if aborted\n if (abortController.signal.aborted) {\n throw error;\n }\n\n const errorMessage = (error as Error)?.message;\n\n this.#updateRequestState(\n cacheKey,\n createErrorState(errorMessage ?? 'Unknown error', lastFetchedAt),\n );\n throw error;\n } finally {\n // Only delete if this is still our entry (not replaced by a new request)\n const currentPending = this.#pendingRequests.get(cacheKey);\n if (currentPending?.abortController === abortController) {\n this.#pendingRequests.delete(cacheKey);\n }\n }\n })();\n\n // Store pending request for deduplication\n this.#pendingRequests.set(cacheKey, { promise, abortController });\n\n return promise;\n }\n\n /**\n * Aborts a pending request if one exists.\n *\n * @param cacheKey - The cache key of the request to abort.\n * @returns True if a request was aborted.\n */\n abortRequest(cacheKey: string): boolean {\n const pending = this.#pendingRequests.get(cacheKey);\n if (pending) {\n pending.abortController.abort();\n this.#pendingRequests.delete(cacheKey);\n this.#removeRequestState(cacheKey);\n return true;\n }\n return false;\n }\n\n /**\n * Removes a request state from the cache.\n *\n * @param cacheKey - The cache key to remove.\n */\n #removeRequestState(cacheKey: string): void {\n this.update((state) => {\n const requests = state.requests as unknown as Record<\n string,\n RequestState | undefined\n >;\n delete requests[cacheKey];\n });\n }\n\n /**\n * Gets the state of a specific cached request.\n *\n * @param cacheKey - The cache key to look up.\n * @returns The request state, or undefined if not cached.\n */\n getRequestState(cacheKey: string): RequestState | undefined {\n return this.state.requests[cacheKey];\n }\n\n /**\n * Updates the state for a specific request.\n *\n * @param cacheKey - The cache key.\n * @param requestState - The new state for the request.\n */\n #updateRequestState(cacheKey: string, requestState: RequestState): void {\n const maxSize = this.#requestCacheMaxSize;\n\n this.update((state) => {\n const requests = state.requests as unknown as Record<\n string,\n RequestState | undefined\n >;\n requests[cacheKey] = requestState;\n\n // Evict oldest entries if cache exceeds max size\n const keys = Object.keys(requests);\n\n if (keys.length > maxSize) {\n // Sort by timestamp (oldest first)\n const sortedKeys = keys.sort((a, b) => {\n const aTime = requests[a]?.timestamp ?? 0;\n const bTime = requests[b]?.timestamp ?? 0;\n return aTime - bTime;\n });\n\n // Remove oldest entries until we're under the limit\n const entriesToRemove = keys.length - maxSize;\n for (let i = 0; i < entriesToRemove; i++) {\n const keyToRemove = sortedKeys[i];\n if (keyToRemove) {\n delete requests[keyToRemove];\n }\n }\n }\n });\n }\n\n /**\n * Updates the user's region by fetching geolocation.\n * This method calls the RampsService to get the geolocation.\n *\n * @param options - Options for cache behavior.\n * @returns The user region object.\n */\n async updateUserRegion(\n options?: ExecuteRequestOptions,\n ): Promise<UserRegion | null> {\n // If a userRegion already exists and forceRefresh is not requested,\n // return it immediately without fetching geolocation.\n // This ensures that once a region is set (either via geolocation or manual selection),\n // it will not be overwritten by subsequent geolocation fetches.\n if (this.state.userRegion && !options?.forceRefresh) {\n return this.state.userRegion;\n }\n\n // When forceRefresh is true, clear the existing region and tokens before fetching\n if (options?.forceRefresh) {\n this.update((state) => {\n state.userRegion = null;\n state.tokens = null;\n });\n }\n\n const cacheKey = createCacheKey('updateUserRegion', []);\n\n const regionCode = await this.executeRequest(\n cacheKey,\n async () => {\n const result = await this.messenger.call('RampsService:getGeolocation');\n return result;\n },\n options,\n );\n\n if (!regionCode) {\n this.update((state) => {\n state.userRegion = null;\n state.tokens = null;\n });\n return null;\n }\n\n const normalizedRegion = regionCode.toLowerCase().trim();\n\n try {\n const countries = await this.getCountries('buy', options);\n const userRegion = findRegionFromCode(normalizedRegion, countries);\n\n if (userRegion) {\n this.update((state) => {\n const regionChanged =\n state.userRegion?.regionCode !== userRegion.regionCode;\n state.userRegion = userRegion;\n // Clear tokens when region changes\n if (regionChanged) {\n state.tokens = null;\n }\n });\n\n return userRegion;\n }\n\n // Region not found in countries data\n this.update((state) => {\n state.userRegion = null;\n state.tokens = null;\n });\n\n return null;\n } catch {\n // If countries fetch fails, we can't create a valid UserRegion\n // Return null to indicate we don't have valid country data\n this.update((state) => {\n state.userRegion = null;\n state.tokens = null;\n });\n\n return null;\n }\n }\n\n /**\n * Sets the user's region manually (without fetching geolocation).\n * This allows users to override the detected region.\n *\n * @param region - The region code to set (e.g., \"US-CA\").\n * @param options - Options for cache behavior.\n * @returns The user region object.\n */\n async setUserRegion(\n region: string,\n options?: ExecuteRequestOptions,\n ): Promise<UserRegion> {\n const normalizedRegion = region.toLowerCase().trim();\n\n try {\n const countries = await this.getCountries('buy', options);\n const userRegion = findRegionFromCode(normalizedRegion, countries);\n\n if (userRegion) {\n this.update((state) => {\n state.userRegion = userRegion;\n state.tokens = null;\n });\n return userRegion;\n }\n\n // Region not found in countries data\n this.update((state) => {\n state.userRegion = null;\n state.tokens = null;\n });\n throw new Error(\n `Region \"${normalizedRegion}\" not found in countries data. Cannot set user region without valid country information.`,\n );\n } catch (error) {\n // If the error is \"not found\", re-throw it\n // Otherwise, it's from countries fetch failure\n if (error instanceof Error && error.message.includes('not found')) {\n throw error;\n }\n // Countries fetch failed\n this.update((state) => {\n state.userRegion = null;\n state.tokens = null;\n });\n throw new Error(\n 'Failed to fetch countries data. Cannot set user region without valid country information.',\n );\n }\n }\n\n /**\n * Sets the user's preferred provider.\n * This allows users to set their preferred ramp provider.\n *\n * @param provider - The provider object to set.\n */\n setPreferredProvider(provider: Provider | null): void {\n this.update((state) => {\n state.preferredProvider = provider;\n });\n }\n\n /**\n * Initializes the controller by fetching the user's region from geolocation.\n * This should be called once at app startup to set up the initial region.\n * After the region is set, tokens are fetched and saved to state.\n *\n * If a userRegion already exists (from persistence or manual selection),\n * this method will skip geolocation fetch and only fetch tokens if needed.\n *\n * @param options - Options for cache behavior.\n * @returns Promise that resolves when initialization is complete.\n */\n async init(options?: ExecuteRequestOptions): Promise<void> {\n const userRegion = await this.updateUserRegion(options).catch(() => {\n // User region fetch failed - error state will be available via selectors\n return null;\n });\n\n if (userRegion) {\n try {\n await this.getTokens(userRegion.regionCode, 'buy', options);\n } catch {\n // Token fetch failed - error state will be available via selectors\n }\n }\n }\n\n /**\n * Fetches the list of supported countries for a given ramp action.\n *\n * @param action - The ramp action type ('buy' or 'sell').\n * @param options - Options for cache behavior.\n * @returns An array of countries.\n */\n async getCountries(\n action: 'buy' | 'sell' = 'buy',\n options?: ExecuteRequestOptions,\n ): Promise<Country[]> {\n const cacheKey = createCacheKey('getCountries', [action]);\n\n return this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call('RampsService:getCountries', action);\n },\n options,\n );\n }\n\n /**\n * Fetches the list of available tokens for a given region and action.\n * The tokens are saved in the controller state once fetched.\n *\n * @param region - The region code (e.g., \"us\", \"fr\", \"us-ny\"). If not provided, uses the user's region from controller state.\n * @param action - The ramp action type ('buy' or 'sell').\n * @param options - Options for cache behavior.\n * @returns The tokens response containing topTokens and allTokens.\n */\n async getTokens(\n region?: string,\n action: 'buy' | 'sell' = 'buy',\n options?: ExecuteRequestOptions,\n ): Promise<TokensResponse> {\n const regionToUse = region ?? this.state.userRegion?.regionCode;\n\n if (!regionToUse) {\n throw new Error(\n 'Region is required. Either provide a region parameter or ensure userRegion is set in controller state.',\n );\n }\n\n const normalizedRegion = regionToUse.toLowerCase().trim();\n const cacheKey = createCacheKey('getTokens', [normalizedRegion, action]);\n\n const tokens = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call(\n 'RampsService:getTokens',\n normalizedRegion,\n action,\n );\n },\n options,\n );\n\n this.update((state) => {\n const userRegionCode = state.userRegion?.regionCode;\n\n if (userRegionCode === undefined || userRegionCode === normalizedRegion) {\n state.tokens = tokens;\n }\n });\n\n return tokens;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"RampsController.cjs","sourceRoot":"","sources":["../src/RampsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,+DAA2D;AAiB3D,qDAQwB;AAExB,kBAAkB;AAElB;;;;GAIG;AACU,QAAA,cAAc,GAAG,iBAAiB,CAAC;AAsDhD;;GAEG;AACH,MAAM,uBAAuB,GAAG;IAC9B,UAAU,EAAE;QACV,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,kBAAkB,EAAE,IAAI;QACxB,QAAQ,EAAE,IAAI;KACf;IACD,iBAAiB,EAAE;QACjB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,kBAAkB,EAAE,IAAI;QACxB,QAAQ,EAAE,IAAI;KACf;IACD,SAAS,EAAE;QACT,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE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G,OAAO,EAAE,CAAC;YAC1B,mCAAmC;YACnC,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;gBACpC,MAAM,KAAK,GAAG,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,IAAI,CAAC,CAAC;gBAC1C,MAAM,KAAK,GAAG,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,IAAI,CAAC,CAAC;gBAC1C,OAAO,KAAK,GAAG,KAAK,CAAC;YACvB,CAAC,CAAC,CAAC;YAEH,oDAAoD;YACpD,MAAM,eAAe,GAAG,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC;YAC9C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,eAAe,EAAE,CAAC,EAAE,EAAE,CAAC;gBACzC,MAAM,WAAW,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;gBAClC,IAAI,WAAW,EAAE,CAAC;oBAChB,OAAO,QAAQ,CAAC,WAAW,CAAC,CAAC;gBAC/B,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { Json } from '@metamask/utils';\n\nimport type { Country, TokensResponse, Provider, State } from './RampsService';\nimport type {\n RampsServiceGetGeolocationAction,\n RampsServiceGetCountriesAction,\n RampsServiceGetTokensAction,\n RampsServiceGetProvidersAction,\n} from './RampsService-method-action-types';\nimport type {\n RequestCache as RequestCacheType,\n RequestState,\n ExecuteRequestOptions,\n PendingRequest,\n} from './RequestCache';\nimport {\n DEFAULT_REQUEST_CACHE_TTL,\n DEFAULT_REQUEST_CACHE_MAX_SIZE,\n createCacheKey,\n isCacheExpired,\n createLoadingState,\n createSuccessState,\n createErrorState,\n} from './RequestCache';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link RampsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'RampsController';\n\n// === STATE ===\n\n/**\n * Represents the user's selected region with full country and state objects.\n */\nexport type UserRegion = {\n /**\n * The country object for the selected region.\n */\n country: Country;\n /**\n * The state object if a state was selected, null if only country was selected.\n */\n state: State | null;\n /**\n * The region code string (e.g., \"us-ut\" or \"fr\") used for API calls.\n */\n regionCode: string;\n};\n\n/**\n * Describes the shape of the state object for {@link RampsController}.\n */\nexport type RampsControllerState = {\n /**\n * The user's selected region with full country and state objects.\n * Initially set via geolocation fetch, but can be manually changed by the user.\n * Once set (either via geolocation or manual selection), it will not be overwritten\n * by subsequent geolocation fetches.\n */\n userRegion: UserRegion | null;\n /**\n * The user's preferred provider.\n * Can be manually set by the user.\n */\n preferredProvider: Provider | null;\n /**\n * List of providers available for the current region.\n */\n providers: Provider[];\n /**\n * Tokens fetched for the current region and action.\n * Contains topTokens and allTokens arrays.\n */\n tokens: TokensResponse | null;\n /**\n * Cache of request states, keyed by cache key.\n * This stores loading, success, and error states for API requests.\n */\n requests: RequestCacheType;\n};\n\n/**\n * The metadata for each property in {@link RampsControllerState}.\n */\nconst rampsControllerMetadata = {\n userRegion: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n preferredProvider: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n providers: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n tokens: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: true,\n },\n requests: {\n persist: false,\n includeInDebugSnapshot: true,\n includeInStateLogs: false,\n usedInUi: true,\n },\n} satisfies StateMetadata<RampsControllerState>;\n\n/**\n * Constructs the default {@link RampsController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link RampsController} state.\n */\nexport function getDefaultRampsControllerState(): RampsControllerState {\n return {\n userRegion: null,\n preferredProvider: null,\n providers: [],\n tokens: null,\n requests: {},\n };\n}\n\n// === MESSENGER ===\n\n/**\n * Retrieves the state of the {@link RampsController}.\n */\nexport type RampsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n RampsControllerState\n>;\n\n/**\n * Actions that {@link RampsControllerMessenger} exposes to other consumers.\n */\nexport type RampsControllerActions = RampsControllerGetStateAction;\n\n/**\n * Actions from other messengers that {@link RampsController} calls.\n */\ntype AllowedActions =\n | RampsServiceGetGeolocationAction\n | RampsServiceGetCountriesAction\n | RampsServiceGetTokensAction\n | RampsServiceGetProvidersAction;\n\n/**\n * Published when the state of {@link RampsController} changes.\n */\nexport type RampsControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n RampsControllerState\n>;\n\n/**\n * Events that {@link RampsControllerMessenger} exposes to other consumers.\n */\nexport type RampsControllerEvents = RampsControllerStateChangeEvent;\n\n/**\n * Events from other messengers that {@link RampsController} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link RampsController}.\n */\nexport type RampsControllerMessenger = Messenger<\n typeof controllerName,\n RampsControllerActions | AllowedActions,\n RampsControllerEvents | AllowedEvents\n>;\n\n/**\n * Configuration options for the RampsController.\n */\nexport type RampsControllerOptions = {\n /** The messenger suited for this controller. */\n messenger: RampsControllerMessenger;\n /** The desired state with which to initialize this controller. */\n state?: Partial<RampsControllerState>;\n /** Time to live for cached requests in milliseconds. Defaults to 15 minutes. */\n requestCacheTTL?: number;\n /** Maximum number of entries in the request cache. Defaults to 250. */\n requestCacheMaxSize?: number;\n};\n\n// === HELPER FUNCTIONS ===\n\n/**\n * Finds a country and state from a region code string.\n *\n * @param regionCode - The region code (e.g., \"us-ca\" or \"us\").\n * @param countries - Array of countries to search.\n * @returns UserRegion object with country and state, or null if not found.\n */\nfunction findRegionFromCode(\n regionCode: string,\n countries: Country[],\n): UserRegion | null {\n const normalizedCode = regionCode.toLowerCase().trim();\n const parts = normalizedCode.split('-');\n const countryCode = parts[0];\n const stateCode = parts[1];\n\n const country = countries.find((countryItem) => {\n if (countryItem.isoCode?.toLowerCase() === countryCode) {\n return true;\n }\n if (countryItem.id) {\n const id = countryItem.id.toLowerCase();\n if (id.startsWith('/regions/')) {\n const extractedCode = id.replace('/regions/', '').split('/')[0];\n return extractedCode === countryCode;\n }\n return id === countryCode || id.endsWith(`/${countryCode}`);\n }\n return false;\n });\n\n if (!country) {\n return null;\n }\n\n let state: State | null = null;\n if (stateCode && country.states) {\n state =\n country.states.find((stateItem) => {\n if (stateItem.stateId?.toLowerCase() === stateCode) {\n return true;\n }\n if (stateItem.id) {\n const stateId = stateItem.id.toLowerCase();\n if (\n stateId.includes(`-${stateCode}`) ||\n stateId.endsWith(`/${stateCode}`)\n ) {\n return true;\n }\n }\n return false;\n }) ?? null;\n }\n\n return {\n country,\n state,\n regionCode: normalizedCode,\n };\n}\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * Manages cryptocurrency on/off ramps functionality.\n */\nexport class RampsController extends BaseController<\n typeof controllerName,\n RampsControllerState,\n RampsControllerMessenger\n> {\n /**\n * Default TTL for cached requests.\n */\n readonly #requestCacheTTL: number;\n\n /**\n * Maximum number of entries in the request cache.\n */\n readonly #requestCacheMaxSize: number;\n\n /**\n * Map of pending requests for deduplication.\n * Key is the cache key, value is the pending request with abort controller.\n */\n readonly #pendingRequests: Map<string, PendingRequest> = new Map();\n\n /**\n * Constructs a new {@link RampsController}.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this controller.\n * @param args.state - The desired state with which to initialize this\n * controller. Missing properties will be filled in with defaults.\n * @param args.requestCacheTTL - Time to live for cached requests in milliseconds.\n * @param args.requestCacheMaxSize - Maximum number of entries in the request cache.\n */\n constructor({\n messenger,\n state = {},\n requestCacheTTL = DEFAULT_REQUEST_CACHE_TTL,\n requestCacheMaxSize = DEFAULT_REQUEST_CACHE_MAX_SIZE,\n }: RampsControllerOptions) {\n super({\n messenger,\n metadata: rampsControllerMetadata,\n name: controllerName,\n state: {\n ...getDefaultRampsControllerState(),\n ...state,\n // Always reset requests cache on initialization (non-persisted)\n requests: {},\n },\n });\n\n this.#requestCacheTTL = requestCacheTTL;\n this.#requestCacheMaxSize = requestCacheMaxSize;\n }\n\n /**\n * Executes a request with caching and deduplication.\n *\n * If a request with the same cache key is already in flight, returns the\n * existing promise. If valid cached data exists, returns it without making\n * a new request.\n *\n * @param cacheKey - Unique identifier for this request.\n * @param fetcher - Function that performs the actual fetch. Receives an AbortSignal.\n * @param options - Options for cache behavior.\n * @returns The result of the request.\n */\n async executeRequest<TResult>(\n cacheKey: string,\n fetcher: (signal: AbortSignal) => Promise<TResult>,\n options?: ExecuteRequestOptions,\n ): Promise<TResult> {\n const ttl = options?.ttl ?? this.#requestCacheTTL;\n\n // Check for existing pending request - join it instead of making a duplicate\n const pending = this.#pendingRequests.get(cacheKey);\n if (pending) {\n return pending.promise as Promise<TResult>;\n }\n\n // Check cache validity (unless force refresh)\n if (!options?.forceRefresh) {\n const cached = this.state.requests[cacheKey];\n if (cached && !isCacheExpired(cached, ttl)) {\n return cached.data as TResult;\n }\n }\n\n // Create abort controller for this request\n const abortController = new AbortController();\n const lastFetchedAt = Date.now();\n\n // Update state to loading\n this.#updateRequestState(cacheKey, createLoadingState());\n\n // Create the fetch promise\n const promise = (async (): Promise<TResult> => {\n try {\n const data = await fetcher(abortController.signal);\n\n // Don't update state if aborted\n if (abortController.signal.aborted) {\n throw new Error('Request was aborted');\n }\n\n this.#updateRequestState(\n cacheKey,\n createSuccessState(data as Json, lastFetchedAt),\n );\n return data;\n } catch (error) {\n // Don't update state if aborted\n if (abortController.signal.aborted) {\n throw error;\n }\n\n const errorMessage = (error as Error)?.message;\n\n this.#updateRequestState(\n cacheKey,\n createErrorState(errorMessage ?? 'Unknown error', lastFetchedAt),\n );\n throw error;\n } finally {\n // Only delete if this is still our entry (not replaced by a new request)\n const currentPending = this.#pendingRequests.get(cacheKey);\n if (currentPending?.abortController === abortController) {\n this.#pendingRequests.delete(cacheKey);\n }\n }\n })();\n\n // Store pending request for deduplication\n this.#pendingRequests.set(cacheKey, { promise, abortController });\n\n return promise;\n }\n\n /**\n * Aborts a pending request if one exists.\n *\n * @param cacheKey - The cache key of the request to abort.\n * @returns True if a request was aborted.\n */\n abortRequest(cacheKey: string): boolean {\n const pending = this.#pendingRequests.get(cacheKey);\n if (pending) {\n pending.abortController.abort();\n this.#pendingRequests.delete(cacheKey);\n this.#removeRequestState(cacheKey);\n return true;\n }\n return false;\n }\n\n /**\n * Removes a request state from the cache.\n *\n * @param cacheKey - The cache key to remove.\n */\n #removeRequestState(cacheKey: string): void {\n this.update((state) => {\n const requests = state.requests as unknown as Record<\n string,\n RequestState | undefined\n >;\n delete requests[cacheKey];\n });\n }\n\n /**\n * Gets the state of a specific cached request.\n *\n * @param cacheKey - The cache key to look up.\n * @returns The request state, or undefined if not cached.\n */\n getRequestState(cacheKey: string): RequestState | undefined {\n return this.state.requests[cacheKey];\n }\n\n /**\n * Updates the state for a specific request.\n *\n * @param cacheKey - The cache key.\n * @param requestState - The new state for the request.\n */\n #updateRequestState(cacheKey: string, requestState: RequestState): void {\n const maxSize = this.#requestCacheMaxSize;\n\n this.update((state) => {\n const requests = state.requests as unknown as Record<\n string,\n RequestState | undefined\n >;\n requests[cacheKey] = requestState;\n\n // Evict oldest entries if cache exceeds max size\n const keys = Object.keys(requests);\n\n if (keys.length > maxSize) {\n // Sort by timestamp (oldest first)\n const sortedKeys = keys.sort((a, b) => {\n const aTime = requests[a]?.timestamp ?? 0;\n const bTime = requests[b]?.timestamp ?? 0;\n return aTime - bTime;\n });\n\n // Remove oldest entries until we're under the limit\n const entriesToRemove = keys.length - maxSize;\n for (let i = 0; i < entriesToRemove; i++) {\n const keyToRemove = sortedKeys[i];\n if (keyToRemove) {\n delete requests[keyToRemove];\n }\n }\n }\n });\n }\n\n /**\n * Updates the user's region by fetching geolocation.\n * This method calls the RampsService to get the geolocation.\n *\n * @param options - Options for cache behavior.\n * @returns The user region object.\n */\n async updateUserRegion(\n options?: ExecuteRequestOptions,\n ): Promise<UserRegion | null> {\n // If a userRegion already exists and forceRefresh is not requested,\n // return it immediately without fetching geolocation.\n // This ensures that once a region is set (either via geolocation or manual selection),\n // it will not be overwritten by subsequent geolocation fetches.\n if (this.state.userRegion && !options?.forceRefresh) {\n return this.state.userRegion;\n }\n\n // When forceRefresh is true, clear the existing region, tokens, and providers before fetching\n if (options?.forceRefresh) {\n this.update((state) => {\n state.userRegion = null;\n state.tokens = null;\n state.providers = [];\n });\n }\n\n const cacheKey = createCacheKey('updateUserRegion', []);\n\n const regionCode = await this.executeRequest(\n cacheKey,\n async () => {\n const result = await this.messenger.call('RampsService:getGeolocation');\n return result;\n },\n options,\n );\n\n if (!regionCode) {\n this.update((state) => {\n state.userRegion = null;\n state.tokens = null;\n state.providers = [];\n });\n return null;\n }\n\n const normalizedRegion = regionCode.toLowerCase().trim();\n\n try {\n const countries = await this.getCountries('buy', options);\n const userRegion = findRegionFromCode(normalizedRegion, countries);\n\n if (userRegion) {\n this.update((state) => {\n const regionChanged =\n state.userRegion?.regionCode !== userRegion.regionCode;\n state.userRegion = userRegion;\n // Clear tokens and providers when region changes\n if (regionChanged) {\n state.tokens = null;\n state.providers = [];\n }\n });\n\n // Fetch providers for the new region\n if (userRegion.regionCode) {\n try {\n await this.getProviders(userRegion.regionCode, options);\n } catch {\n // Provider fetch failed - error state will be available via selectors\n }\n }\n\n return userRegion;\n }\n\n // Region not found in countries data\n this.update((state) => {\n state.userRegion = null;\n state.tokens = null;\n state.providers = [];\n });\n\n return null;\n } catch {\n // If countries fetch fails, we can't create a valid UserRegion\n // Return null to indicate we don't have valid country data\n this.update((state) => {\n state.userRegion = null;\n state.tokens = null;\n state.providers = [];\n });\n\n return null;\n }\n }\n\n /**\n * Sets the user's region manually (without fetching geolocation).\n * This allows users to override the detected region.\n *\n * @param region - The region code to set (e.g., \"US-CA\").\n * @param options - Options for cache behavior.\n * @returns The user region object.\n */\n async setUserRegion(\n region: string,\n options?: ExecuteRequestOptions,\n ): Promise<UserRegion> {\n const normalizedRegion = region.toLowerCase().trim();\n\n try {\n const countries = await this.getCountries('buy', options);\n const userRegion = findRegionFromCode(normalizedRegion, countries);\n\n if (userRegion) {\n this.update((state) => {\n state.userRegion = userRegion;\n state.tokens = null;\n state.providers = [];\n });\n\n // Fetch providers for the new region\n try {\n await this.getProviders(userRegion.regionCode, options);\n } catch {\n // Provider fetch failed - error state will be available via selectors\n }\n\n return userRegion;\n }\n\n // Region not found in countries data\n this.update((state) => {\n state.userRegion = null;\n state.tokens = null;\n state.providers = [];\n });\n throw new Error(\n `Region \"${normalizedRegion}\" not found in countries data. Cannot set user region without valid country information.`,\n );\n } catch (error) {\n // If the error is \"not found\", re-throw it\n // Otherwise, it's from countries fetch failure\n if (error instanceof Error && error.message.includes('not found')) {\n throw error;\n }\n // Countries fetch failed\n this.update((state) => {\n state.userRegion = null;\n state.tokens = null;\n state.providers = [];\n });\n throw new Error(\n 'Failed to fetch countries data. Cannot set user region without valid country information.',\n );\n }\n }\n\n /**\n * Sets the user's preferred provider.\n * This allows users to set their preferred ramp provider.\n *\n * @param provider - The provider object to set.\n */\n setPreferredProvider(provider: Provider | null): void {\n this.update((state) => {\n state.preferredProvider = provider;\n });\n }\n\n /**\n * Initializes the controller by fetching the user's region from geolocation.\n * This should be called once at app startup to set up the initial region.\n * After the region is set, tokens are fetched and saved to state.\n *\n * If a userRegion already exists (from persistence or manual selection),\n * this method will skip geolocation fetch and only fetch tokens if needed.\n *\n * @param options - Options for cache behavior.\n * @returns Promise that resolves when initialization is complete.\n */\n async init(options?: ExecuteRequestOptions): Promise<void> {\n const userRegion = await this.updateUserRegion(options).catch(() => {\n // User region fetch failed - error state will be available via selectors\n return null;\n });\n\n if (userRegion) {\n try {\n await this.getTokens(userRegion.regionCode, 'buy', options);\n } catch {\n // Token fetch failed - error state will be available via selectors\n }\n\n try {\n await this.getProviders(userRegion.regionCode, options);\n } catch {\n // Provider fetch failed - error state will be available via selectors\n }\n }\n }\n\n /**\n * Fetches the list of supported countries for a given ramp action.\n *\n * @param action - The ramp action type ('buy' or 'sell').\n * @param options - Options for cache behavior.\n * @returns An array of countries.\n */\n async getCountries(\n action: 'buy' | 'sell' = 'buy',\n options?: ExecuteRequestOptions,\n ): Promise<Country[]> {\n const cacheKey = createCacheKey('getCountries', [action]);\n\n return this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call('RampsService:getCountries', action);\n },\n options,\n );\n }\n\n /**\n * Fetches the list of available tokens for a given region and action.\n * The tokens are saved in the controller state once fetched.\n *\n * @param region - The region code (e.g., \"us\", \"fr\", \"us-ny\"). If not provided, uses the user's region from controller state.\n * @param action - The ramp action type ('buy' or 'sell').\n * @param options - Options for cache behavior.\n * @returns The tokens response containing topTokens and allTokens.\n */\n async getTokens(\n region?: string,\n action: 'buy' | 'sell' = 'buy',\n options?: ExecuteRequestOptions,\n ): Promise<TokensResponse> {\n const regionToUse = region ?? this.state.userRegion?.regionCode;\n\n if (!regionToUse) {\n throw new Error(\n 'Region is required. Either provide a region parameter or ensure userRegion is set in controller state.',\n );\n }\n\n const normalizedRegion = regionToUse.toLowerCase().trim();\n const cacheKey = createCacheKey('getTokens', [normalizedRegion, action]);\n\n const tokens = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call(\n 'RampsService:getTokens',\n normalizedRegion,\n action,\n );\n },\n options,\n );\n\n this.update((state) => {\n const userRegionCode = state.userRegion?.regionCode;\n\n if (userRegionCode === undefined || userRegionCode === normalizedRegion) {\n state.tokens = tokens;\n }\n });\n\n return tokens;\n }\n\n /**\n * Fetches the list of providers for a given region.\n * The providers are saved in the controller state once fetched.\n *\n * @param region - The region code (e.g., \"us\", \"fr\", \"us-ny\"). If not provided, uses the user's region from controller state.\n * @param options - Options for cache behavior and query filters.\n * @param options.provider - Provider ID(s) to filter by.\n * @param options.crypto - Crypto currency ID(s) to filter by.\n * @param options.fiat - Fiat currency ID(s) to filter by.\n * @param options.payments - Payment method ID(s) to filter by.\n * @returns The providers response containing providers array.\n */\n async getProviders(\n region?: string,\n options?: ExecuteRequestOptions & {\n provider?: string | string[];\n crypto?: string | string[];\n fiat?: string | string[];\n payments?: string | string[];\n },\n ): Promise<{ providers: Provider[] }> {\n const regionToUse = region ?? this.state.userRegion?.regionCode;\n\n if (!regionToUse) {\n throw new Error(\n 'Region is required. Either provide a region parameter or ensure userRegion is set in controller state.',\n );\n }\n\n const normalizedRegion = regionToUse.toLowerCase().trim();\n const cacheKey = createCacheKey('getProviders', [\n normalizedRegion,\n options?.provider,\n options?.crypto,\n options?.fiat,\n options?.payments,\n ]);\n\n const { providers } = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call(\n 'RampsService:getProviders',\n normalizedRegion,\n {\n provider: options?.provider,\n crypto: options?.crypto,\n fiat: options?.fiat,\n payments: options?.payments,\n },\n );\n },\n options,\n );\n\n this.update((state) => {\n const userRegionCode = state.userRegion?.regionCode;\n\n if (userRegionCode === undefined || userRegionCode === normalizedRegion) {\n state.providers = providers;\n }\n });\n\n return { providers };\n }\n}\n"]}
|
|
@@ -2,7 +2,7 @@ import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@meta
|
|
|
2
2
|
import { BaseController } from "@metamask/base-controller";
|
|
3
3
|
import type { Messenger } from "@metamask/messenger";
|
|
4
4
|
import type { Country, TokensResponse, Provider, State } from "./RampsService.cjs";
|
|
5
|
-
import type { RampsServiceGetGeolocationAction, RampsServiceGetCountriesAction, RampsServiceGetTokensAction } from "./RampsService-method-action-types.cjs";
|
|
5
|
+
import type { RampsServiceGetGeolocationAction, RampsServiceGetCountriesAction, RampsServiceGetTokensAction, RampsServiceGetProvidersAction } from "./RampsService-method-action-types.cjs";
|
|
6
6
|
import type { RequestCache as RequestCacheType, RequestState, ExecuteRequestOptions } from "./RequestCache.cjs";
|
|
7
7
|
/**
|
|
8
8
|
* The name of the {@link RampsController}, used to namespace the
|
|
@@ -43,6 +43,10 @@ export type RampsControllerState = {
|
|
|
43
43
|
* Can be manually set by the user.
|
|
44
44
|
*/
|
|
45
45
|
preferredProvider: Provider | null;
|
|
46
|
+
/**
|
|
47
|
+
* List of providers available for the current region.
|
|
48
|
+
*/
|
|
49
|
+
providers: Provider[];
|
|
46
50
|
/**
|
|
47
51
|
* Tokens fetched for the current region and action.
|
|
48
52
|
* Contains topTokens and allTokens arrays.
|
|
@@ -74,7 +78,7 @@ export type RampsControllerActions = RampsControllerGetStateAction;
|
|
|
74
78
|
/**
|
|
75
79
|
* Actions from other messengers that {@link RampsController} calls.
|
|
76
80
|
*/
|
|
77
|
-
type AllowedActions = RampsServiceGetGeolocationAction | RampsServiceGetCountriesAction | RampsServiceGetTokensAction;
|
|
81
|
+
type AllowedActions = RampsServiceGetGeolocationAction | RampsServiceGetCountriesAction | RampsServiceGetTokensAction | RampsServiceGetProvidersAction;
|
|
78
82
|
/**
|
|
79
83
|
* Published when the state of {@link RampsController} changes.
|
|
80
84
|
*/
|
|
@@ -202,6 +206,26 @@ export declare class RampsController extends BaseController<typeof controllerNam
|
|
|
202
206
|
* @returns The tokens response containing topTokens and allTokens.
|
|
203
207
|
*/
|
|
204
208
|
getTokens(region?: string, action?: 'buy' | 'sell', options?: ExecuteRequestOptions): Promise<TokensResponse>;
|
|
209
|
+
/**
|
|
210
|
+
* Fetches the list of providers for a given region.
|
|
211
|
+
* The providers are saved in the controller state once fetched.
|
|
212
|
+
*
|
|
213
|
+
* @param region - The region code (e.g., "us", "fr", "us-ny"). If not provided, uses the user's region from controller state.
|
|
214
|
+
* @param options - Options for cache behavior and query filters.
|
|
215
|
+
* @param options.provider - Provider ID(s) to filter by.
|
|
216
|
+
* @param options.crypto - Crypto currency ID(s) to filter by.
|
|
217
|
+
* @param options.fiat - Fiat currency ID(s) to filter by.
|
|
218
|
+
* @param options.payments - Payment method ID(s) to filter by.
|
|
219
|
+
* @returns The providers response containing providers array.
|
|
220
|
+
*/
|
|
221
|
+
getProviders(region?: string, options?: ExecuteRequestOptions & {
|
|
222
|
+
provider?: string | string[];
|
|
223
|
+
crypto?: string | string[];
|
|
224
|
+
fiat?: string | string[];
|
|
225
|
+
payments?: string | string[];
|
|
226
|
+
}): Promise<{
|
|
227
|
+
providers: Provider[];
|
|
228
|
+
}>;
|
|
205
229
|
}
|
|
206
230
|
export {};
|
|
207
231
|
//# sourceMappingURL=RampsController.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RampsController.d.cts","sourceRoot":"","sources":["../src/RampsController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAGrD,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,KAAK,EAAE,2BAAuB;AAC/E,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC9B,2BAA2B,
|
|
1
|
+
{"version":3,"file":"RampsController.d.cts","sourceRoot":"","sources":["../src/RampsController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAGrD,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,KAAK,EAAE,2BAAuB;AAC/E,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC9B,2BAA2B,EAC3B,8BAA8B,EAC/B,+CAA2C;AAC5C,OAAO,KAAK,EACV,YAAY,IAAI,gBAAgB,EAChC,YAAY,EACZ,qBAAqB,EAEtB,2BAAuB;AAa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,IAAI,CAAC;IAqB1D;;;;;;OAMG;IACG,YAAY,CAChB,MAAM,GAAE,KAAK,GAAG,MAAc,EAC9B,OAAO,CAAC,EAAE,qBAAqB,GAC9B,OAAO,CAAC,OAAO,EAAE,CAAC;IAYrB;;;;;;;;OAQG;IACG,SAAS,CACb,MAAM,CAAC,EAAE,MAAM,EACf,MAAM,GAAE,KAAK,GAAG,MAAc,EAC9B,OAAO,CAAC,EAAE,qBAAqB,GAC9B,OAAO,CAAC,cAAc,CAAC;IAmC1B;;;;;;;;;;;OAWG;IACG,YAAY,CAChB,MAAM,CAAC,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,qBAAqB,GAAG;QAChC,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;QAC7B,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;QAC3B,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;QACzB,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;KAC9B,GACA,OAAO,CAAC;QAAE,SAAS,EAAE,QAAQ,EAAE,CAAA;KAAE,CAAC;CA6CtC"}
|
|
@@ -2,7 +2,7 @@ import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@meta
|
|
|
2
2
|
import { BaseController } from "@metamask/base-controller";
|
|
3
3
|
import type { Messenger } from "@metamask/messenger";
|
|
4
4
|
import type { Country, TokensResponse, Provider, State } from "./RampsService.mjs";
|
|
5
|
-
import type { RampsServiceGetGeolocationAction, RampsServiceGetCountriesAction, RampsServiceGetTokensAction } from "./RampsService-method-action-types.mjs";
|
|
5
|
+
import type { RampsServiceGetGeolocationAction, RampsServiceGetCountriesAction, RampsServiceGetTokensAction, RampsServiceGetProvidersAction } from "./RampsService-method-action-types.mjs";
|
|
6
6
|
import type { RequestCache as RequestCacheType, RequestState, ExecuteRequestOptions } from "./RequestCache.mjs";
|
|
7
7
|
/**
|
|
8
8
|
* The name of the {@link RampsController}, used to namespace the
|
|
@@ -43,6 +43,10 @@ export type RampsControllerState = {
|
|
|
43
43
|
* Can be manually set by the user.
|
|
44
44
|
*/
|
|
45
45
|
preferredProvider: Provider | null;
|
|
46
|
+
/**
|
|
47
|
+
* List of providers available for the current region.
|
|
48
|
+
*/
|
|
49
|
+
providers: Provider[];
|
|
46
50
|
/**
|
|
47
51
|
* Tokens fetched for the current region and action.
|
|
48
52
|
* Contains topTokens and allTokens arrays.
|
|
@@ -74,7 +78,7 @@ export type RampsControllerActions = RampsControllerGetStateAction;
|
|
|
74
78
|
/**
|
|
75
79
|
* Actions from other messengers that {@link RampsController} calls.
|
|
76
80
|
*/
|
|
77
|
-
type AllowedActions = RampsServiceGetGeolocationAction | RampsServiceGetCountriesAction | RampsServiceGetTokensAction;
|
|
81
|
+
type AllowedActions = RampsServiceGetGeolocationAction | RampsServiceGetCountriesAction | RampsServiceGetTokensAction | RampsServiceGetProvidersAction;
|
|
78
82
|
/**
|
|
79
83
|
* Published when the state of {@link RampsController} changes.
|
|
80
84
|
*/
|
|
@@ -202,6 +206,26 @@ export declare class RampsController extends BaseController<typeof controllerNam
|
|
|
202
206
|
* @returns The tokens response containing topTokens and allTokens.
|
|
203
207
|
*/
|
|
204
208
|
getTokens(region?: string, action?: 'buy' | 'sell', options?: ExecuteRequestOptions): Promise<TokensResponse>;
|
|
209
|
+
/**
|
|
210
|
+
* Fetches the list of providers for a given region.
|
|
211
|
+
* The providers are saved in the controller state once fetched.
|
|
212
|
+
*
|
|
213
|
+
* @param region - The region code (e.g., "us", "fr", "us-ny"). If not provided, uses the user's region from controller state.
|
|
214
|
+
* @param options - Options for cache behavior and query filters.
|
|
215
|
+
* @param options.provider - Provider ID(s) to filter by.
|
|
216
|
+
* @param options.crypto - Crypto currency ID(s) to filter by.
|
|
217
|
+
* @param options.fiat - Fiat currency ID(s) to filter by.
|
|
218
|
+
* @param options.payments - Payment method ID(s) to filter by.
|
|
219
|
+
* @returns The providers response containing providers array.
|
|
220
|
+
*/
|
|
221
|
+
getProviders(region?: string, options?: ExecuteRequestOptions & {
|
|
222
|
+
provider?: string | string[];
|
|
223
|
+
crypto?: string | string[];
|
|
224
|
+
fiat?: string | string[];
|
|
225
|
+
payments?: string | string[];
|
|
226
|
+
}): Promise<{
|
|
227
|
+
providers: Provider[];
|
|
228
|
+
}>;
|
|
205
229
|
}
|
|
206
230
|
export {};
|
|
207
231
|
//# sourceMappingURL=RampsController.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RampsController.d.mts","sourceRoot":"","sources":["../src/RampsController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAGrD,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,KAAK,EAAE,2BAAuB;AAC/E,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC9B,2BAA2B,
|
|
1
|
+
{"version":3,"file":"RampsController.d.mts","sourceRoot":"","sources":["../src/RampsController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAGrD,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,KAAK,EAAE,2BAAuB;AAC/E,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC9B,2BAA2B,EAC3B,8BAA8B,EAC/B,+CAA2C;AAC5C,OAAO,KAAK,EACV,YAAY,IAAI,gBAAgB,EAChC,YAAY,EACZ,qBAAqB,EAEtB,2BAAuB;AAaxB;;;;GAIG;AACH,eAAO,MAAM,cAAc,oBAAoB,CAAC;AAIhD;;GAEG;AACH,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