@metamask/ramps-controller 2.0.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 +31 -1
- package/dist/RampsController.cjs +324 -9
- package/dist/RampsController.cjs.map +1 -1
- package/dist/RampsController.d.cts +117 -12
- package/dist/RampsController.d.cts.map +1 -1
- package/dist/RampsController.d.mts +117 -12
- package/dist/RampsController.d.mts.map +1 -1
- package/dist/RampsController.mjs +324 -9
- 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 +33 -1
- package/dist/RampsService-method-action-types.d.cts.map +1 -1
- package/dist/RampsService-method-action-types.d.mts +33 -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 +126 -24
- package/dist/RampsService.cjs.map +1 -1
- package/dist/RampsService.d.cts +178 -1
- package/dist/RampsService.d.cts.map +1 -1
- package/dist/RampsService.d.mts +178 -1
- package/dist/RampsService.d.mts.map +1 -1
- package/dist/RampsService.mjs +122 -23
- package/dist/RampsService.mjs.map +1 -1
- package/dist/RequestCache.cjs +98 -0
- package/dist/RequestCache.cjs.map +1 -0
- package/dist/RequestCache.d.cts +93 -0
- package/dist/RequestCache.d.cts.map +1 -0
- package/dist/RequestCache.d.mts +93 -0
- package/dist/RequestCache.d.mts.map +1 -0
- package/dist/RequestCache.mjs +90 -0
- package/dist/RequestCache.mjs.map +1 -0
- package/dist/index.cjs +14 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -4
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +8 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3 -1
- package/dist/index.mjs.map +1 -1
- package/dist/selectors.cjs +81 -0
- package/dist/selectors.cjs.map +1 -0
- package/dist/selectors.d.cts +75 -0
- package/dist/selectors.d.cts.map +1 -0
- package/dist/selectors.d.mts +75 -0
- package/dist/selectors.d.mts.map +1 -0
- package/dist/selectors.mjs +77 -0
- package/dist/selectors.mjs.map +1 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [3.0.0]
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Add `getTokens()` method to RampsController for fetching available tokens by region and action ([#7607](https://github.com/MetaMask/core/pull/7607))
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- **BREAKING:** Rename `geolocation` to `userRegion` and `updateGeolocation()` to `updateUserRegion()` in RampsController ([#7563](https://github.com/MetaMask/core/pull/7563))
|
|
19
|
+
|
|
20
|
+
- Bump `@metamask/controller-utils` from `^11.17.0` to `^11.18.0` ([#7583](https://github.com/MetaMask/core/pull/7583))
|
|
21
|
+
|
|
22
|
+
## [2.1.0]
|
|
23
|
+
|
|
24
|
+
### Added
|
|
25
|
+
|
|
26
|
+
- Add eligibility state ([#7539](https://github.com/MetaMask/core/pull/7539))
|
|
27
|
+
|
|
28
|
+
- Add `createRequestSelector` utility function for creating memoized selectors for RampsController request states ([#7554](https://github.com/MetaMask/core/pull/7554))
|
|
29
|
+
|
|
30
|
+
- Add request caching infrastructure with TTL, deduplication, and abort support ([#7536](https://github.com/MetaMask/core/pull/7536))
|
|
31
|
+
|
|
32
|
+
- Add `init()` and `setUserRegion()` methods to RampsController ([#7563](https://github.com/MetaMask/core/pull/7563))
|
|
33
|
+
|
|
34
|
+
### Changed
|
|
35
|
+
|
|
36
|
+
- Bump `@metamask/controller-utils` from `^11.16.0` to `^11.17.0` ([#7534](https://github.com/MetaMask/core/pull/7534))
|
|
37
|
+
|
|
10
38
|
## [2.0.0]
|
|
11
39
|
|
|
12
40
|
### Changed
|
|
@@ -27,6 +55,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
27
55
|
- Add `OnRampService` for interacting with the OnRamp API
|
|
28
56
|
- Add geolocation detection via IP address lookup
|
|
29
57
|
|
|
30
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/ramps-controller@
|
|
58
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/ramps-controller@3.0.0...HEAD
|
|
59
|
+
[3.0.0]: https://github.com/MetaMask/core/compare/@metamask/ramps-controller@2.1.0...@metamask/ramps-controller@3.0.0
|
|
60
|
+
[2.1.0]: https://github.com/MetaMask/core/compare/@metamask/ramps-controller@2.0.0...@metamask/ramps-controller@2.1.0
|
|
31
61
|
[2.0.0]: https://github.com/MetaMask/core/compare/@metamask/ramps-controller@1.0.0...@metamask/ramps-controller@2.0.0
|
|
32
62
|
[1.0.0]: https://github.com/MetaMask/core/releases/tag/@metamask/ramps-controller@1.0.0
|
package/dist/RampsController.cjs
CHANGED
|
@@ -1,7 +1,20 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
+
};
|
|
8
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
+
};
|
|
13
|
+
var _RampsController_instances, _RampsController_requestCacheTTL, _RampsController_requestCacheMaxSize, _RampsController_pendingRequests, _RampsController_removeRequestState, _RampsController_updateRequestState;
|
|
2
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
15
|
exports.RampsController = exports.getDefaultRampsControllerState = exports.controllerName = void 0;
|
|
4
16
|
const base_controller_1 = require("@metamask/base-controller");
|
|
17
|
+
const RequestCache_1 = require("./RequestCache.cjs");
|
|
5
18
|
// === GENERAL ===
|
|
6
19
|
/**
|
|
7
20
|
* The name of the {@link RampsController}, used to namespace the
|
|
@@ -13,12 +26,30 @@ exports.controllerName = 'RampsController';
|
|
|
13
26
|
* The metadata for each property in {@link RampsControllerState}.
|
|
14
27
|
*/
|
|
15
28
|
const rampsControllerMetadata = {
|
|
16
|
-
|
|
29
|
+
userRegion: {
|
|
30
|
+
persist: true,
|
|
31
|
+
includeInDebugSnapshot: true,
|
|
32
|
+
includeInStateLogs: true,
|
|
33
|
+
usedInUi: true,
|
|
34
|
+
},
|
|
35
|
+
eligibility: {
|
|
17
36
|
persist: true,
|
|
18
37
|
includeInDebugSnapshot: true,
|
|
19
38
|
includeInStateLogs: true,
|
|
20
39
|
usedInUi: true,
|
|
21
40
|
},
|
|
41
|
+
tokens: {
|
|
42
|
+
persist: true,
|
|
43
|
+
includeInDebugSnapshot: true,
|
|
44
|
+
includeInStateLogs: true,
|
|
45
|
+
usedInUi: true,
|
|
46
|
+
},
|
|
47
|
+
requests: {
|
|
48
|
+
persist: false,
|
|
49
|
+
includeInDebugSnapshot: true,
|
|
50
|
+
includeInStateLogs: false,
|
|
51
|
+
usedInUi: true,
|
|
52
|
+
},
|
|
22
53
|
};
|
|
23
54
|
/**
|
|
24
55
|
* Constructs the default {@link RampsController} state. This allows
|
|
@@ -30,7 +61,10 @@ const rampsControllerMetadata = {
|
|
|
30
61
|
*/
|
|
31
62
|
function getDefaultRampsControllerState() {
|
|
32
63
|
return {
|
|
33
|
-
|
|
64
|
+
userRegion: null,
|
|
65
|
+
eligibility: null,
|
|
66
|
+
tokens: null,
|
|
67
|
+
requests: {},
|
|
34
68
|
};
|
|
35
69
|
}
|
|
36
70
|
exports.getDefaultRampsControllerState = getDefaultRampsControllerState;
|
|
@@ -46,8 +80,10 @@ class RampsController extends base_controller_1.BaseController {
|
|
|
46
80
|
* @param args.messenger - The messenger suited for this controller.
|
|
47
81
|
* @param args.state - The desired state with which to initialize this
|
|
48
82
|
* controller. Missing properties will be filled in with defaults.
|
|
83
|
+
* @param args.requestCacheTTL - Time to live for cached requests in milliseconds.
|
|
84
|
+
* @param args.requestCacheMaxSize - Maximum number of entries in the request cache.
|
|
49
85
|
*/
|
|
50
|
-
constructor({ messenger, state = {}, }) {
|
|
86
|
+
constructor({ messenger, state = {}, requestCacheTTL = RequestCache_1.DEFAULT_REQUEST_CACHE_TTL, requestCacheMaxSize = RequestCache_1.DEFAULT_REQUEST_CACHE_MAX_SIZE, }) {
|
|
51
87
|
super({
|
|
52
88
|
messenger,
|
|
53
89
|
metadata: rampsControllerMetadata,
|
|
@@ -55,20 +91,299 @@ class RampsController extends base_controller_1.BaseController {
|
|
|
55
91
|
state: {
|
|
56
92
|
...getDefaultRampsControllerState(),
|
|
57
93
|
...state,
|
|
94
|
+
// Always reset requests cache on initialization (non-persisted)
|
|
95
|
+
requests: {},
|
|
58
96
|
},
|
|
59
97
|
});
|
|
98
|
+
_RampsController_instances.add(this);
|
|
99
|
+
/**
|
|
100
|
+
* Default TTL for cached requests.
|
|
101
|
+
*/
|
|
102
|
+
_RampsController_requestCacheTTL.set(this, void 0);
|
|
103
|
+
/**
|
|
104
|
+
* Maximum number of entries in the request cache.
|
|
105
|
+
*/
|
|
106
|
+
_RampsController_requestCacheMaxSize.set(this, void 0);
|
|
107
|
+
/**
|
|
108
|
+
* Map of pending requests for deduplication.
|
|
109
|
+
* Key is the cache key, value is the pending request with abort controller.
|
|
110
|
+
*/
|
|
111
|
+
_RampsController_pendingRequests.set(this, new Map());
|
|
112
|
+
__classPrivateFieldSet(this, _RampsController_requestCacheTTL, requestCacheTTL, "f");
|
|
113
|
+
__classPrivateFieldSet(this, _RampsController_requestCacheMaxSize, requestCacheMaxSize, "f");
|
|
60
114
|
}
|
|
61
115
|
/**
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
116
|
+
* Executes a request with caching and deduplication.
|
|
117
|
+
*
|
|
118
|
+
* If a request with the same cache key is already in flight, returns the
|
|
119
|
+
* existing promise. If valid cached data exists, returns it without making
|
|
120
|
+
* a new request.
|
|
121
|
+
*
|
|
122
|
+
* @param cacheKey - Unique identifier for this request.
|
|
123
|
+
* @param fetcher - Function that performs the actual fetch. Receives an AbortSignal.
|
|
124
|
+
* @param options - Options for cache behavior.
|
|
125
|
+
* @returns The result of the request.
|
|
126
|
+
*/
|
|
127
|
+
async executeRequest(cacheKey, fetcher, options) {
|
|
128
|
+
const ttl = options?.ttl ?? __classPrivateFieldGet(this, _RampsController_requestCacheTTL, "f");
|
|
129
|
+
// Check for existing pending request - join it instead of making a duplicate
|
|
130
|
+
const pending = __classPrivateFieldGet(this, _RampsController_pendingRequests, "f").get(cacheKey);
|
|
131
|
+
if (pending) {
|
|
132
|
+
return pending.promise;
|
|
133
|
+
}
|
|
134
|
+
// Check cache validity (unless force refresh)
|
|
135
|
+
if (!options?.forceRefresh) {
|
|
136
|
+
const cached = this.state.requests[cacheKey];
|
|
137
|
+
if (cached && !(0, RequestCache_1.isCacheExpired)(cached, ttl)) {
|
|
138
|
+
return cached.data;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
// Create abort controller for this request
|
|
142
|
+
const abortController = new AbortController();
|
|
143
|
+
const lastFetchedAt = Date.now();
|
|
144
|
+
// Update state to loading
|
|
145
|
+
__classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_updateRequestState).call(this, cacheKey, (0, RequestCache_1.createLoadingState)());
|
|
146
|
+
// Create the fetch promise
|
|
147
|
+
const promise = (async () => {
|
|
148
|
+
try {
|
|
149
|
+
const data = await fetcher(abortController.signal);
|
|
150
|
+
// Don't update state if aborted
|
|
151
|
+
if (abortController.signal.aborted) {
|
|
152
|
+
throw new Error('Request was aborted');
|
|
153
|
+
}
|
|
154
|
+
__classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_updateRequestState).call(this, cacheKey, (0, RequestCache_1.createSuccessState)(data, lastFetchedAt));
|
|
155
|
+
return data;
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
// Don't update state if aborted
|
|
159
|
+
if (abortController.signal.aborted) {
|
|
160
|
+
throw error;
|
|
161
|
+
}
|
|
162
|
+
const errorMessage = error?.message;
|
|
163
|
+
__classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_updateRequestState).call(this, cacheKey, (0, RequestCache_1.createErrorState)(errorMessage ?? 'Unknown error', lastFetchedAt));
|
|
164
|
+
throw error;
|
|
165
|
+
}
|
|
166
|
+
finally {
|
|
167
|
+
// Only delete if this is still our entry (not replaced by a new request)
|
|
168
|
+
const currentPending = __classPrivateFieldGet(this, _RampsController_pendingRequests, "f").get(cacheKey);
|
|
169
|
+
if (currentPending?.abortController === abortController) {
|
|
170
|
+
__classPrivateFieldGet(this, _RampsController_pendingRequests, "f").delete(cacheKey);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
})();
|
|
174
|
+
// Store pending request for deduplication
|
|
175
|
+
__classPrivateFieldGet(this, _RampsController_pendingRequests, "f").set(cacheKey, { promise, abortController });
|
|
176
|
+
return promise;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Aborts a pending request if one exists.
|
|
180
|
+
*
|
|
181
|
+
* @param cacheKey - The cache key of the request to abort.
|
|
182
|
+
* @returns True if a request was aborted.
|
|
183
|
+
*/
|
|
184
|
+
abortRequest(cacheKey) {
|
|
185
|
+
const pending = __classPrivateFieldGet(this, _RampsController_pendingRequests, "f").get(cacheKey);
|
|
186
|
+
if (pending) {
|
|
187
|
+
pending.abortController.abort();
|
|
188
|
+
__classPrivateFieldGet(this, _RampsController_pendingRequests, "f").delete(cacheKey);
|
|
189
|
+
__classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_removeRequestState).call(this, cacheKey);
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
return false;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Gets the state of a specific cached request.
|
|
196
|
+
*
|
|
197
|
+
* @param cacheKey - The cache key to look up.
|
|
198
|
+
* @returns The request state, or undefined if not cached.
|
|
199
|
+
*/
|
|
200
|
+
getRequestState(cacheKey) {
|
|
201
|
+
return this.state.requests[cacheKey];
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Updates the user's region by fetching geolocation and eligibility.
|
|
205
|
+
* This method calls the RampsService to get the geolocation,
|
|
206
|
+
* then automatically fetches eligibility for that region.
|
|
207
|
+
*
|
|
208
|
+
* @param options - Options for cache behavior.
|
|
209
|
+
* @returns The user region string.
|
|
65
210
|
*/
|
|
66
|
-
async
|
|
67
|
-
const
|
|
211
|
+
async updateUserRegion(options) {
|
|
212
|
+
const cacheKey = (0, RequestCache_1.createCacheKey)('updateUserRegion', []);
|
|
213
|
+
const userRegion = await this.executeRequest(cacheKey, async () => {
|
|
214
|
+
const result = await this.messenger.call('RampsService:getGeolocation');
|
|
215
|
+
return result;
|
|
216
|
+
}, options);
|
|
217
|
+
const normalizedRegion = userRegion
|
|
218
|
+
? userRegion.toLowerCase().trim()
|
|
219
|
+
: userRegion;
|
|
68
220
|
this.update((state) => {
|
|
69
|
-
state.
|
|
221
|
+
state.userRegion = normalizedRegion;
|
|
222
|
+
state.tokens = null;
|
|
70
223
|
});
|
|
224
|
+
if (normalizedRegion) {
|
|
225
|
+
try {
|
|
226
|
+
await this.updateEligibility(normalizedRegion, options);
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
this.update((state) => {
|
|
230
|
+
const currentUserRegion = state.userRegion?.toLowerCase().trim();
|
|
231
|
+
if (currentUserRegion === normalizedRegion) {
|
|
232
|
+
state.eligibility = null;
|
|
233
|
+
state.tokens = null;
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return normalizedRegion;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Sets the user's region manually (without fetching geolocation).
|
|
242
|
+
* This allows users to override the detected region.
|
|
243
|
+
*
|
|
244
|
+
* @param region - The region code to set (e.g., "US-CA").
|
|
245
|
+
* @param options - Options for cache behavior when fetching eligibility.
|
|
246
|
+
* @returns The eligibility information for the region.
|
|
247
|
+
*/
|
|
248
|
+
async setUserRegion(region, options) {
|
|
249
|
+
const normalizedRegion = region.toLowerCase().trim();
|
|
250
|
+
this.update((state) => {
|
|
251
|
+
state.userRegion = normalizedRegion;
|
|
252
|
+
state.tokens = null;
|
|
253
|
+
});
|
|
254
|
+
try {
|
|
255
|
+
return await this.updateEligibility(normalizedRegion, options);
|
|
256
|
+
}
|
|
257
|
+
catch (error) {
|
|
258
|
+
// Eligibility fetch failed, but user region was successfully set.
|
|
259
|
+
// Don't let eligibility errors prevent user region state from being updated.
|
|
260
|
+
// Clear eligibility state to avoid showing stale data from a previous location.
|
|
261
|
+
// Only clear if the region still matches to avoid race conditions where a newer
|
|
262
|
+
// region change has already succeeded.
|
|
263
|
+
this.update((state) => {
|
|
264
|
+
const currentUserRegion = state.userRegion?.toLowerCase().trim();
|
|
265
|
+
if (currentUserRegion === normalizedRegion) {
|
|
266
|
+
state.eligibility = null;
|
|
267
|
+
state.tokens = null;
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
throw error;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Initializes the controller by fetching the user's region from geolocation.
|
|
275
|
+
* This should be called once at app startup to set up the initial region.
|
|
276
|
+
* After the region is set and eligibility is determined, tokens are fetched
|
|
277
|
+
* and saved to state.
|
|
278
|
+
*
|
|
279
|
+
* @param options - Options for cache behavior.
|
|
280
|
+
* @returns Promise that resolves when initialization is complete.
|
|
281
|
+
*/
|
|
282
|
+
async init(options) {
|
|
283
|
+
const userRegion = await this.updateUserRegion(options).catch(() => {
|
|
284
|
+
// User region fetch failed - error state will be available via selectors
|
|
285
|
+
return null;
|
|
286
|
+
});
|
|
287
|
+
if (userRegion) {
|
|
288
|
+
try {
|
|
289
|
+
await this.getTokens(userRegion, 'buy', options);
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
// Token fetch failed - error state will be available via selectors
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Updates the eligibility information for a given region.
|
|
298
|
+
*
|
|
299
|
+
* @param isoCode - The ISO code for the region (e.g., "us", "fr", "us-ny").
|
|
300
|
+
* @param options - Options for cache behavior.
|
|
301
|
+
* @returns The eligibility information.
|
|
302
|
+
*/
|
|
303
|
+
async updateEligibility(isoCode, options) {
|
|
304
|
+
const normalizedIsoCode = isoCode.toLowerCase().trim();
|
|
305
|
+
const cacheKey = (0, RequestCache_1.createCacheKey)('updateEligibility', [normalizedIsoCode]);
|
|
306
|
+
const eligibility = await this.executeRequest(cacheKey, async () => {
|
|
307
|
+
return this.messenger.call('RampsService:getEligibility', normalizedIsoCode);
|
|
308
|
+
}, options);
|
|
309
|
+
this.update((state) => {
|
|
310
|
+
const userRegion = state.userRegion?.toLowerCase().trim();
|
|
311
|
+
if (userRegion === undefined || userRegion === normalizedIsoCode) {
|
|
312
|
+
state.eligibility = eligibility;
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
return eligibility;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Fetches the list of supported countries for a given ramp action.
|
|
319
|
+
*
|
|
320
|
+
* @param action - The ramp action type ('buy' or 'sell').
|
|
321
|
+
* @param options - Options for cache behavior.
|
|
322
|
+
* @returns An array of countries with their eligibility information.
|
|
323
|
+
*/
|
|
324
|
+
async getCountries(action = 'buy', options) {
|
|
325
|
+
const cacheKey = (0, RequestCache_1.createCacheKey)('getCountries', [action]);
|
|
326
|
+
return this.executeRequest(cacheKey, async () => {
|
|
327
|
+
return this.messenger.call('RampsService:getCountries', action);
|
|
328
|
+
}, options);
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Fetches the list of available tokens for a given region and action.
|
|
332
|
+
* The tokens are saved in the controller state once fetched.
|
|
333
|
+
*
|
|
334
|
+
* @param region - The region code (e.g., "us", "fr", "us-ny"). If not provided, uses the user's region from controller state.
|
|
335
|
+
* @param action - The ramp action type ('buy' or 'sell').
|
|
336
|
+
* @param options - Options for cache behavior.
|
|
337
|
+
* @returns The tokens response containing topTokens and allTokens.
|
|
338
|
+
*/
|
|
339
|
+
async getTokens(region, action = 'buy', options) {
|
|
340
|
+
const regionToUse = region ?? this.state.userRegion;
|
|
341
|
+
if (!regionToUse) {
|
|
342
|
+
throw new Error('Region is required. Either provide a region parameter or ensure userRegion is set in controller state.');
|
|
343
|
+
}
|
|
344
|
+
const normalizedRegion = regionToUse.toLowerCase().trim();
|
|
345
|
+
const cacheKey = (0, RequestCache_1.createCacheKey)('getTokens', [normalizedRegion, action]);
|
|
346
|
+
const tokens = await this.executeRequest(cacheKey, async () => {
|
|
347
|
+
return this.messenger.call('RampsService:getTokens', normalizedRegion, action);
|
|
348
|
+
}, options);
|
|
349
|
+
this.update((state) => {
|
|
350
|
+
const userRegion = state.userRegion?.toLowerCase().trim();
|
|
351
|
+
if (userRegion === undefined || userRegion === normalizedRegion) {
|
|
352
|
+
state.tokens = tokens;
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
return tokens;
|
|
71
356
|
}
|
|
72
357
|
}
|
|
73
358
|
exports.RampsController = RampsController;
|
|
359
|
+
_RampsController_requestCacheTTL = new WeakMap(), _RampsController_requestCacheMaxSize = new WeakMap(), _RampsController_pendingRequests = new WeakMap(), _RampsController_instances = new WeakSet(), _RampsController_removeRequestState = function _RampsController_removeRequestState(cacheKey) {
|
|
360
|
+
this.update((state) => {
|
|
361
|
+
const requests = state.requests;
|
|
362
|
+
delete requests[cacheKey];
|
|
363
|
+
});
|
|
364
|
+
}, _RampsController_updateRequestState = function _RampsController_updateRequestState(cacheKey, requestState) {
|
|
365
|
+
const maxSize = __classPrivateFieldGet(this, _RampsController_requestCacheMaxSize, "f");
|
|
366
|
+
this.update((state) => {
|
|
367
|
+
const requests = state.requests;
|
|
368
|
+
requests[cacheKey] = requestState;
|
|
369
|
+
// Evict oldest entries if cache exceeds max size
|
|
370
|
+
const keys = Object.keys(requests);
|
|
371
|
+
if (keys.length > maxSize) {
|
|
372
|
+
// Sort by timestamp (oldest first)
|
|
373
|
+
const sortedKeys = keys.sort((a, b) => {
|
|
374
|
+
const aTime = requests[a]?.timestamp ?? 0;
|
|
375
|
+
const bTime = requests[b]?.timestamp ?? 0;
|
|
376
|
+
return aTime - bTime;
|
|
377
|
+
});
|
|
378
|
+
// Remove oldest entries until we're under the limit
|
|
379
|
+
const entriesToRemove = keys.length - maxSize;
|
|
380
|
+
for (let i = 0; i < entriesToRemove; i++) {
|
|
381
|
+
const keyToRemove = sortedKeys[i];
|
|
382
|
+
if (keyToRemove) {
|
|
383
|
+
delete requests[keyToRemove];
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
};
|
|
74
389
|
//# sourceMappingURL=RampsController.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RampsController.cjs","sourceRoot":"","sources":["../src/RampsController.ts"],"names":[],"mappings":";;;AAKA,+DAA2D;AAK3D,kBAAkB;AAElB;;;;GAIG;AACU,QAAA,cAAc,GAAG,iBAAiB,CAAC;AAchD;;GAEG;AACH,MAAM,uBAAuB,GAAG;IAC9B,WAAW,EAAE;QACX,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,kBAAkB,EAAE,IAAI;QACxB,QAAQ,EAAE,IAAI;KACf;CAC4C,CAAC;AAEhD;;;;;;;GAOG;AACH,SAAgB,8BAA8B;IAC5C,OAAO;QACL,WAAW,EAAE,IAAI;KAClB,CAAC;AACJ,CAAC;AAJD,wEAIC;AAkDD,gCAAgC;AAEhC;;GAEG;AACH,MAAa,eAAgB,SAAQ,gCAIpC;IACC;;;;;;;OAOG;IACH,YAAY,EACV,SAAS,EACT,KAAK,GAAG,EAAE,GAIX;QACC,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE,uBAAuB;YACjC,IAAI,EAAE,sBAAc;YACpB,KAAK,EAAE;gBACL,GAAG,8BAA8B,EAAE;gBACnC,GAAG,KAAK;aACT;SACF,CAAC,CAAC;IACL,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,iBAAiB;QACrB,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAC3C,6BAA6B,CAC9B,CAAC;QAEF,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,WAAW,GAAG,WAAW,CAAC;QAClC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA7CD,0CA6CC","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';\n\nimport type { RampsServiceGetGeolocationAction } from './RampsService-method-action-types';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link RampsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'RampsController';\n\n// === STATE ===\n\n/**\n * Describes the shape of the state object for {@link RampsController}.\n */\nexport type RampsControllerState = {\n /**\n * The user's country code determined by geolocation.\n */\n geolocation: string | null;\n};\n\n/**\n * The metadata for each property in {@link RampsControllerState}.\n */\nconst rampsControllerMetadata = {\n geolocation: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\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 geolocation: null,\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 = RampsServiceGetGeolocationAction;\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// === 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 * 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 */\n constructor({\n messenger,\n state = {},\n }: {\n messenger: RampsControllerMessenger;\n state?: Partial<RampsControllerState>;\n }) {\n super({\n messenger,\n metadata: rampsControllerMetadata,\n name: controllerName,\n state: {\n ...getDefaultRampsControllerState(),\n ...state,\n },\n });\n }\n\n /**\n * Updates the user's geolocation.\n * This method calls the RampsService to get the geolocation\n * and stores the result in state.\n */\n async updateGeolocation(): Promise<void> {\n const geolocation = await this.messenger.call(\n 'RampsService:getGeolocation',\n );\n\n this.update((state) => {\n state.geolocation = geolocation;\n });\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;AA6BhD;;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,WAAW,EAAE;QACX,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,EAAE,IAAI;QAC5B,kBAAkB,EAAE,KAAK;QACzB,QAAQ,EAAE,IAAI;KACf;CAC4C,CAAC;AAEhD;;;;;;;GAOG;AACH,SAAgB,8BAA8B;IAC5C,OAAO;QACL,UAAU,EAAE,IAAI;QAChB,WAAW,EAAE,IAAI;QACjB,MAAM,EAAE,IAAI;QACZ,QAAQ,EAAE,EAAE;KACb,CAAC;AACJ,CAAC;AAPD,wEAOC;AAoED,gCAA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I,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, Eligibility, TokensResponse } from './RampsService';\nimport type {\n RampsServiceGetGeolocationAction,\n RampsServiceGetCountriesAction,\n RampsServiceGetEligibilityAction,\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 * Describes the shape of the state object for {@link RampsController}.\n */\nexport type RampsControllerState = {\n /**\n * The user's selected region code (e.g., \"US-CA\").\n * Initially set via geolocation fetch, but can be manually changed by the user.\n */\n userRegion: string | null;\n /**\n * Eligibility information for the user's current region.\n */\n eligibility: Eligibility | 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 eligibility: {\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 eligibility: 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 | RampsServiceGetEligibilityAction\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// === 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 and eligibility.\n * This method calls the RampsService to get the geolocation,\n * then automatically fetches eligibility for that region.\n *\n * @param options - Options for cache behavior.\n * @returns The user region string.\n */\n async updateUserRegion(options?: ExecuteRequestOptions): Promise<string> {\n const cacheKey = createCacheKey('updateUserRegion', []);\n\n const userRegion = 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 const normalizedRegion = userRegion\n ? userRegion.toLowerCase().trim()\n : userRegion;\n\n this.update((state) => {\n state.userRegion = normalizedRegion;\n state.tokens = null;\n });\n\n if (normalizedRegion) {\n try {\n await this.updateEligibility(normalizedRegion, options);\n } catch {\n this.update((state) => {\n const currentUserRegion = state.userRegion?.toLowerCase().trim();\n if (currentUserRegion === normalizedRegion) {\n state.eligibility = null;\n state.tokens = null;\n }\n });\n }\n }\n\n return normalizedRegion;\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 when fetching eligibility.\n * @returns The eligibility information for the region.\n */\n async setUserRegion(\n region: string,\n options?: ExecuteRequestOptions,\n ): Promise<Eligibility> {\n const normalizedRegion = region.toLowerCase().trim();\n\n this.update((state) => {\n state.userRegion = normalizedRegion;\n state.tokens = null;\n });\n\n try {\n return await this.updateEligibility(normalizedRegion, options);\n } catch (error) {\n // Eligibility fetch failed, but user region was successfully set.\n // Don't let eligibility errors prevent user region state from being updated.\n // Clear eligibility state to avoid showing stale data from a previous location.\n // Only clear if the region still matches to avoid race conditions where a newer\n // region change has already succeeded.\n this.update((state) => {\n const currentUserRegion = state.userRegion?.toLowerCase().trim();\n if (currentUserRegion === normalizedRegion) {\n state.eligibility = null;\n state.tokens = null;\n }\n });\n throw error;\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 and eligibility is determined, tokens are fetched\n * and saved to state.\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, 'buy', options);\n } catch {\n // Token fetch failed - error state will be available via selectors\n }\n }\n }\n\n /**\n * Updates the eligibility information for a given region.\n *\n * @param isoCode - The ISO code for the region (e.g., \"us\", \"fr\", \"us-ny\").\n * @param options - Options for cache behavior.\n * @returns The eligibility information.\n */\n async updateEligibility(\n isoCode: string,\n options?: ExecuteRequestOptions,\n ): Promise<Eligibility> {\n const normalizedIsoCode = isoCode.toLowerCase().trim();\n const cacheKey = createCacheKey('updateEligibility', [normalizedIsoCode]);\n\n const eligibility = await this.executeRequest(\n cacheKey,\n async () => {\n return this.messenger.call(\n 'RampsService:getEligibility',\n normalizedIsoCode,\n );\n },\n options,\n );\n\n this.update((state) => {\n const userRegion = state.userRegion?.toLowerCase().trim();\n\n if (userRegion === undefined || userRegion === normalizedIsoCode) {\n state.eligibility = eligibility;\n }\n });\n\n return eligibility;\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 with their eligibility information.\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;\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 userRegion = state.userRegion?.toLowerCase().trim();\n\n if (userRegion === undefined || userRegion === normalizedRegion) {\n state.tokens = tokens;\n }\n });\n\n return tokens;\n }\n}\n"]}
|