@metamask/ramps-controller 8.0.0 → 9.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/dist/RampsController.cjs +646 -116
  3. package/dist/RampsController.cjs.map +1 -1
  4. package/dist/RampsController.d.cts +284 -13
  5. package/dist/RampsController.d.cts.map +1 -1
  6. package/dist/RampsController.d.mts +284 -13
  7. package/dist/RampsController.d.mts.map +1 -1
  8. package/dist/RampsController.mjs +646 -116
  9. package/dist/RampsController.mjs.map +1 -1
  10. package/dist/RampsService-method-action-types.cjs.map +1 -1
  11. package/dist/RampsService-method-action-types.d.cts +32 -1
  12. package/dist/RampsService-method-action-types.d.cts.map +1 -1
  13. package/dist/RampsService-method-action-types.d.mts +32 -1
  14. package/dist/RampsService-method-action-types.d.mts.map +1 -1
  15. package/dist/RampsService-method-action-types.mjs.map +1 -1
  16. package/dist/RampsService.cjs +83 -1
  17. package/dist/RampsService.cjs.map +1 -1
  18. package/dist/RampsService.d.cts +126 -0
  19. package/dist/RampsService.d.cts.map +1 -1
  20. package/dist/RampsService.d.mts +126 -0
  21. package/dist/RampsService.d.mts.map +1 -1
  22. package/dist/RampsService.mjs +82 -0
  23. package/dist/RampsService.mjs.map +1 -1
  24. package/dist/RequestCache.cjs.map +1 -1
  25. package/dist/RequestCache.d.cts +2 -0
  26. package/dist/RequestCache.d.cts.map +1 -1
  27. package/dist/RequestCache.d.mts +2 -0
  28. package/dist/RequestCache.d.mts.map +1 -1
  29. package/dist/RequestCache.mjs.map +1 -1
  30. package/dist/TransakService-method-action-types.cjs +7 -0
  31. package/dist/TransakService-method-action-types.cjs.map +1 -0
  32. package/dist/TransakService-method-action-types.d.cts +106 -0
  33. package/dist/TransakService-method-action-types.d.cts.map +1 -0
  34. package/dist/TransakService-method-action-types.d.mts +106 -0
  35. package/dist/TransakService-method-action-types.d.mts.map +1 -0
  36. package/dist/TransakService-method-action-types.mjs +6 -0
  37. package/dist/TransakService-method-action-types.mjs.map +1 -0
  38. package/dist/TransakService.cjs +588 -0
  39. package/dist/TransakService.cjs.map +1 -0
  40. package/dist/TransakService.d.cts +329 -0
  41. package/dist/TransakService.d.cts.map +1 -0
  42. package/dist/TransakService.d.mts +329 -0
  43. package/dist/TransakService.d.mts.map +1 -0
  44. package/dist/TransakService.mjs +582 -0
  45. package/dist/TransakService.mjs.map +1 -0
  46. package/dist/index.cjs +7 -1
  47. package/dist/index.cjs.map +1 -1
  48. package/dist/index.d.cts +7 -4
  49. package/dist/index.d.cts.map +1 -1
  50. package/dist/index.d.mts +7 -4
  51. package/dist/index.d.mts.map +1 -1
  52. package/dist/index.mjs +2 -1
  53. package/dist/index.mjs.map +1 -1
  54. package/package.json +4 -4
@@ -10,7 +10,7 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
10
10
  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");
11
11
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
12
12
  };
13
- var _RampsController_instances, _RampsController_requestCacheTTL, _RampsController_requestCacheMaxSize, _RampsController_pendingRequests, _RampsController_pendingResourceCount, _RampsController_quotePollingInterval, _RampsController_quotePollingOptions, _RampsController_clearPendingResourceCountForDependentResources, _RampsController_removeRequestState, _RampsController_cleanupState, _RampsController_fireAndForget, _RampsController_restartPollingIfActive, _RampsController_updateResourceField, _RampsController_setResourceLoading, _RampsController_setResourceError, _RampsController_updateRequestState;
13
+ var _RampsController_instances, _RampsController_requestCacheTTL, _RampsController_requestCacheMaxSize, _RampsController_pendingRequests, _RampsController_pendingResourceCount, _RampsController_quotePollingInterval, _RampsController_quotePollingOptions, _RampsController_clearPendingResourceCountForDependentResources, _RampsController_abortDependentRequests, _RampsController_mutateRequests, _RampsController_removeRequestState, _RampsController_cleanupState, _RampsController_fireAndForget, _RampsController_restartPollingIfActive, _RampsController_requireRegion, _RampsController_isRegionCurrent, _RampsController_isTokenCurrent, _RampsController_isProviderCurrent, _RampsController_updateResourceField, _RampsController_setResourceLoading, _RampsController_setResourceError, _RampsController_updateRequestState, _RampsController_syncWidgetUrl, _RampsController_syncTransakAuthOnError;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.RampsController = exports.getDefaultRampsControllerState = exports.RAMPS_CONTROLLER_REQUIRED_SERVICE_ACTIONS = exports.controllerName = void 0;
16
16
  const base_controller_1 = require("@metamask/base-controller");
@@ -35,6 +35,32 @@ exports.RAMPS_CONTROLLER_REQUIRED_SERVICE_ACTIONS = [
35
35
  'RampsService:getPaymentMethods',
36
36
  'RampsService:getQuotes',
37
37
  'RampsService:getBuyWidgetUrl',
38
+ 'RampsService:getOrder',
39
+ 'RampsService:getOrderFromCallback',
40
+ 'TransakService:setApiKey',
41
+ 'TransakService:setAccessToken',
42
+ 'TransakService:clearAccessToken',
43
+ 'TransakService:sendUserOtp',
44
+ 'TransakService:verifyUserOtp',
45
+ 'TransakService:logout',
46
+ 'TransakService:getUserDetails',
47
+ 'TransakService:getBuyQuote',
48
+ 'TransakService:getKycRequirement',
49
+ 'TransakService:getAdditionalRequirements',
50
+ 'TransakService:createOrder',
51
+ 'TransakService:getOrder',
52
+ 'TransakService:getUserLimits',
53
+ 'TransakService:requestOtt',
54
+ 'TransakService:generatePaymentWidgetUrl',
55
+ 'TransakService:submitPurposeOfUsageForm',
56
+ 'TransakService:patchUser',
57
+ 'TransakService:submitSsnDetails',
58
+ 'TransakService:confirmPayment',
59
+ 'TransakService:getTranslation',
60
+ 'TransakService:getIdProofStatus',
61
+ 'TransakService:cancelOrder',
62
+ 'TransakService:cancelAllActiveOrders',
63
+ 'TransakService:getActiveOrders',
38
64
  ];
39
65
  /**
40
66
  * Default TTL for quotes requests (15 seconds).
@@ -81,12 +107,24 @@ const rampsControllerMetadata = {
81
107
  includeInStateLogs: false,
82
108
  usedInUi: true,
83
109
  },
110
+ widgetUrl: {
111
+ persist: false,
112
+ includeInDebugSnapshot: true,
113
+ includeInStateLogs: false,
114
+ usedInUi: true,
115
+ },
84
116
  requests: {
85
117
  persist: false,
86
118
  includeInDebugSnapshot: true,
87
119
  includeInStateLogs: false,
88
120
  usedInUi: true,
89
121
  },
122
+ nativeProviders: {
123
+ persist: false,
124
+ includeInDebugSnapshot: true,
125
+ includeInStateLogs: false,
126
+ usedInUi: true,
127
+ },
90
128
  };
91
129
  /**
92
130
  * Creates a default resource state object.
@@ -121,10 +159,47 @@ function getDefaultRampsControllerState() {
121
159
  tokens: createDefaultResourceState(null, null),
122
160
  paymentMethods: createDefaultResourceState([], null),
123
161
  quotes: createDefaultResourceState(null, null),
162
+ widgetUrl: createDefaultResourceState(null),
124
163
  requests: {},
164
+ nativeProviders: {
165
+ transak: {
166
+ isAuthenticated: false,
167
+ userDetails: createDefaultResourceState(null),
168
+ buyQuote: createDefaultResourceState(null),
169
+ kycRequirement: createDefaultResourceState(null),
170
+ },
171
+ },
125
172
  };
126
173
  }
127
174
  exports.getDefaultRampsControllerState = getDefaultRampsControllerState;
175
+ const DEPENDENT_RESOURCE_KEYS = [
176
+ 'providers',
177
+ 'tokens',
178
+ 'paymentMethods',
179
+ 'quotes',
180
+ ];
181
+ const DEPENDENT_RESOURCE_KEYS_SET = new Set(DEPENDENT_RESOURCE_KEYS);
182
+ function resetResource(state, resourceType, defaultResource) {
183
+ const def = defaultResource ?? getDefaultRampsControllerState()[resourceType];
184
+ const resource = state[resourceType];
185
+ resource.data = def.data;
186
+ resource.selected = def.selected;
187
+ resource.isLoading = def.isLoading;
188
+ resource.error = def.error;
189
+ }
190
+ /**
191
+ * Resets the widgetUrl resource to its default state.
192
+ * Mutates state in place; use from within controller update() for atomic updates.
193
+ *
194
+ * @param state - The state object to mutate.
195
+ */
196
+ function resetWidgetUrl(state) {
197
+ const def = getDefaultRampsControllerState().widgetUrl;
198
+ state.widgetUrl.data = def.data;
199
+ state.widgetUrl.selected = def.selected;
200
+ state.widgetUrl.isLoading = def.isLoading;
201
+ state.widgetUrl.error = def.error;
202
+ }
128
203
  /**
129
204
  * Resets region-dependent resources (userRegion, providers, tokens, paymentMethods, quotes).
130
205
  * Mutates state in place; use from within controller update() for atomic updates.
@@ -137,22 +212,11 @@ function resetDependentResources(state, options) {
137
212
  if (options?.clearUserRegionData) {
138
213
  state.userRegion = null;
139
214
  }
140
- state.providers.selected = null;
141
- state.providers.data = [];
142
- state.providers.isLoading = false;
143
- state.providers.error = null;
144
- state.tokens.selected = null;
145
- state.tokens.data = null;
146
- state.tokens.isLoading = false;
147
- state.tokens.error = null;
148
- state.paymentMethods.data = [];
149
- state.paymentMethods.selected = null;
150
- state.paymentMethods.isLoading = false;
151
- state.paymentMethods.error = null;
152
- state.quotes.data = null;
153
- state.quotes.selected = null;
154
- state.quotes.isLoading = false;
155
- state.quotes.error = null;
215
+ const defaultState = getDefaultRampsControllerState();
216
+ for (const key of DEPENDENT_RESOURCE_KEYS) {
217
+ resetResource(state, key, defaultState[key]);
218
+ }
219
+ resetWidgetUrl(state);
156
220
  }
157
221
  // === HELPER FUNCTIONS ===
158
222
  /**
@@ -276,31 +340,49 @@ class RampsController extends base_controller_1.BaseController {
276
340
  __classPrivateFieldSet(this, _RampsController_requestCacheMaxSize, requestCacheMaxSize, "f");
277
341
  }
278
342
  /**
279
- * Executes a request with caching and deduplication.
343
+ * Executes a request with caching, deduplication, and at most one in-flight
344
+ * request per resource type.
280
345
  *
281
- * If a request with the same cache key is already in flight, returns the
282
- * existing promise. If valid cached data exists, returns it without making
283
- * a new request.
346
+ * 1. **Same cache key in flight** – If a request with this cache key is
347
+ * already pending, returns that promise (deduplication; no second request).
284
348
  *
285
- * @param cacheKey - Unique identifier for this request.
286
- * @param fetcher - Function that performs the actual fetch. Receives an AbortSignal.
287
- * @param options - Options for cache behavior.
288
- * @returns The result of the request.
349
+ * 2. **Cache hit** – If valid, non-expired data exists in state.requests for
350
+ * this key and forceRefresh is not set, returns that data without fetching.
351
+ *
352
+ * 3. **New request** Creates an AbortController and fires the fetcher.
353
+ * If options.resourceType is set, tags the pending request with that
354
+ * resource type (so #abortDependentRequests can cancel it on region
355
+ * change or cleanup) and ref-counts resource-level loading state.
356
+ * On success or error, updates request state and resource error;
357
+ * in finally, clears resource loading only if this request was not
358
+ * aborted.
359
+ *
360
+ * @param cacheKey - Unique identifier for this request (e.g. from createCacheKey).
361
+ * @param fetcher - Async function that performs the fetch. Receives an AbortSignal
362
+ * that is aborted when this request is superseded by another for the same resource.
363
+ * @param options - Optional forceRefresh, ttl, and resourceType for loading/error state.
364
+ * @returns The result of the request (from cache, joined promise, or fetcher).
289
365
  */
290
366
  async executeRequest(cacheKey, fetcher, options) {
367
+ // Get TTL for verifying cache expiration
291
368
  const ttl = options?.ttl ?? __classPrivateFieldGet(this, _RampsController_requestCacheTTL, "f");
292
- // Check for existing pending request - join it instead of making a duplicate
369
+ // DEDUPLICATION:
370
+ // Check if a request is already in flight for this cache key
371
+ // If so, return the original promise for that request
293
372
  const pending = __classPrivateFieldGet(this, _RampsController_pendingRequests, "f").get(cacheKey);
294
373
  if (pending) {
295
374
  return pending.promise;
296
375
  }
376
+ // CACHE HIT:
377
+ // If cache is not expired, return the cached data
297
378
  if (!options?.forceRefresh) {
298
379
  const cached = this.state.requests[cacheKey];
299
380
  if (cached && !(0, RequestCache_1.isCacheExpired)(cached, ttl)) {
300
381
  return cached.data;
301
382
  }
302
383
  }
303
- // Create abort controller for this request
384
+ // Create a new abort controller for this request
385
+ // Record the time the request was started
304
386
  const abortController = new AbortController();
305
387
  const lastFetchedAt = Date.now();
306
388
  const { resourceType } = options ?? {};
@@ -319,15 +401,11 @@ class RampsController extends base_controller_1.BaseController {
319
401
  const promise = (async () => {
320
402
  try {
321
403
  const data = await fetcher(abortController.signal);
322
- // Don't update state if aborted
323
404
  if (abortController.signal.aborted) {
324
405
  throw new Error('Request was aborted');
325
406
  }
326
407
  __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_updateRequestState).call(this, cacheKey, (0, RequestCache_1.createSuccessState)(data, lastFetchedAt));
327
408
  if (resourceType) {
328
- // We need the extra logic because there are two situations where we’re allowed to clear the error:
329
- // No callback → always clear
330
- // Callback present → clear only when isResultCurrent() returns true.
331
409
  const isCurrent = !options?.isResultCurrent || options.isResultCurrent();
332
410
  if (isCurrent) {
333
411
  __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_setResourceError).call(this, resourceType, null);
@@ -336,7 +414,6 @@ class RampsController extends base_controller_1.BaseController {
336
414
  return data;
337
415
  }
338
416
  catch (error) {
339
- // Don't update state if aborted
340
417
  if (abortController.signal.aborted) {
341
418
  throw error;
342
419
  }
@@ -351,13 +428,12 @@ class RampsController extends base_controller_1.BaseController {
351
428
  throw error;
352
429
  }
353
430
  finally {
354
- // Only delete if this is still our entry (not replaced by a new request)
355
- const currentPending = __classPrivateFieldGet(this, _RampsController_pendingRequests, "f").get(cacheKey);
356
- if (currentPending?.abortController === abortController) {
431
+ if (__classPrivateFieldGet(this, _RampsController_pendingRequests, "f").get(cacheKey)?.abortController ===
432
+ abortController) {
357
433
  __classPrivateFieldGet(this, _RampsController_pendingRequests, "f").delete(cacheKey);
358
434
  }
359
435
  // Clear resource-level loading state only when no requests for this resource remain
360
- if (resourceType) {
436
+ if (resourceType && !abortController.signal.aborted) {
361
437
  const count = __classPrivateFieldGet(this, _RampsController_pendingResourceCount, "f").get(resourceType) ?? 0;
362
438
  const next = Math.max(0, count - 1);
363
439
  if (next === 0) {
@@ -370,8 +446,11 @@ class RampsController extends base_controller_1.BaseController {
370
446
  }
371
447
  }
372
448
  })();
373
- // Store pending request for deduplication
374
- __classPrivateFieldGet(this, _RampsController_pendingRequests, "f").set(cacheKey, { promise, abortController });
449
+ __classPrivateFieldGet(this, _RampsController_pendingRequests, "f").set(cacheKey, {
450
+ promise,
451
+ abortController,
452
+ resourceType,
453
+ });
375
454
  return promise;
376
455
  }
377
456
  /**
@@ -425,9 +504,8 @@ class RampsController extends base_controller_1.BaseController {
425
504
  !this.state.tokens.data ||
426
505
  this.state.providers.data.length === 0;
427
506
  if (regionChanged) {
507
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_abortDependentRequests).call(this);
428
508
  __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_clearPendingResourceCountForDependentResources).call(this);
429
- }
430
- if (regionChanged) {
431
509
  this.stopQuotePolling();
432
510
  }
433
511
  this.update((state) => {
@@ -468,15 +546,11 @@ class RampsController extends base_controller_1.BaseController {
468
546
  this.stopQuotePolling();
469
547
  this.update((state) => {
470
548
  state.providers.selected = null;
471
- state.paymentMethods.data = [];
472
- state.paymentMethods.selected = null;
549
+ resetResource(state, 'paymentMethods');
473
550
  });
474
551
  return;
475
552
  }
476
- const regionCode = this.state.userRegion?.regionCode;
477
- if (!regionCode) {
478
- throw new Error('Region is required. Cannot set selected provider without valid region information.');
479
- }
553
+ const regionCode = __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_requireRegion).call(this);
480
554
  const providers = this.state.providers.data;
481
555
  if (!providers || providers.length === 0) {
482
556
  throw new Error('Providers not loaded. Cannot set selected provider before providers are fetched.');
@@ -487,9 +561,9 @@ class RampsController extends base_controller_1.BaseController {
487
561
  }
488
562
  this.update((state) => {
489
563
  state.providers.selected = provider;
490
- state.paymentMethods.data = [];
491
- state.paymentMethods.selected = null;
564
+ resetResource(state, 'paymentMethods');
492
565
  state.quotes.selected = null;
566
+ resetWidgetUrl(state);
493
567
  });
494
568
  __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_fireAndForget).call(this, this.getPaymentMethods(regionCode, { provider: provider.id }).then(() => {
495
569
  // Restart quote polling after payment methods are fetched
@@ -517,10 +591,7 @@ class RampsController extends base_controller_1.BaseController {
517
591
  await this.setUserRegion(regionCode, options);
518
592
  }
519
593
  hydrateState(options) {
520
- const regionCode = this.state.userRegion?.regionCode;
521
- if (!regionCode) {
522
- throw new Error('Region code is required. Cannot hydrate state without valid region information.');
523
- }
594
+ const regionCode = __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_requireRegion).call(this);
524
595
  __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_fireAndForget).call(this, this.getTokens(regionCode, 'buy', options));
525
596
  __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_fireAndForget).call(this, this.getProviders(regionCode, options));
526
597
  }
@@ -538,7 +609,7 @@ class RampsController extends base_controller_1.BaseController {
538
609
  return this.messenger.call('RampsService:getCountries');
539
610
  }, { ...options, resourceType: 'countries' });
540
611
  this.update((state) => {
541
- state.countries.data = countries;
612
+ state.countries.data = Array.isArray(countries) ? [...countries] : [];
542
613
  });
543
614
  return countries;
544
615
  }
@@ -553,10 +624,7 @@ class RampsController extends base_controller_1.BaseController {
553
624
  * @returns The tokens response containing topTokens and allTokens.
554
625
  */
555
626
  async getTokens(region, action = 'buy', options) {
556
- const regionToUse = region ?? this.state.userRegion?.regionCode;
557
- if (!regionToUse) {
558
- throw new Error('Region is required. Either provide a region parameter or ensure userRegion is set in controller state.');
559
- }
627
+ const regionToUse = region ?? __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_requireRegion).call(this);
560
628
  const normalizedRegion = regionToUse.toLowerCase().trim();
561
629
  const cacheKey = (0, RequestCache_1.createCacheKey)('getTokens', [
562
630
  normalizedRegion,
@@ -570,8 +638,7 @@ class RampsController extends base_controller_1.BaseController {
570
638
  }, {
571
639
  ...options,
572
640
  resourceType: 'tokens',
573
- isResultCurrent: () => this.state.userRegion?.regionCode === undefined ||
574
- this.state.userRegion?.regionCode === normalizedRegion,
641
+ isResultCurrent: () => __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_isRegionCurrent).call(this, normalizedRegion),
575
642
  });
576
643
  this.update((state) => {
577
644
  const userRegionCode = state.userRegion?.regionCode;
@@ -594,15 +661,11 @@ class RampsController extends base_controller_1.BaseController {
594
661
  this.stopQuotePolling();
595
662
  this.update((state) => {
596
663
  state.tokens.selected = null;
597
- state.paymentMethods.data = [];
598
- state.paymentMethods.selected = null;
664
+ resetResource(state, 'paymentMethods');
599
665
  });
600
666
  return;
601
667
  }
602
- const regionCode = this.state.userRegion?.regionCode;
603
- if (!regionCode) {
604
- throw new Error('Region is required. Cannot set selected token without valid region information.');
605
- }
668
+ const regionCode = __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_requireRegion).call(this);
606
669
  const tokens = this.state.tokens.data;
607
670
  if (!tokens) {
608
671
  throw new Error('Tokens not loaded. Cannot set selected token before tokens are fetched.');
@@ -614,9 +677,9 @@ class RampsController extends base_controller_1.BaseController {
614
677
  }
615
678
  this.update((state) => {
616
679
  state.tokens.selected = token;
617
- state.paymentMethods.data = [];
618
- state.paymentMethods.selected = null;
680
+ resetResource(state, 'paymentMethods');
619
681
  state.quotes.selected = null;
682
+ resetWidgetUrl(state);
620
683
  });
621
684
  __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_fireAndForget).call(this, this.getPaymentMethods(regionCode, { assetId: token.assetId }).then(() => {
622
685
  __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_restartPollingIfActive).call(this);
@@ -636,10 +699,7 @@ class RampsController extends base_controller_1.BaseController {
636
699
  * @returns The providers response containing providers array.
637
700
  */
638
701
  async getProviders(region, options) {
639
- const regionToUse = region ?? this.state.userRegion?.regionCode;
640
- if (!regionToUse) {
641
- throw new Error('Region is required. Either provide a region parameter or ensure userRegion is set in controller state.');
642
- }
702
+ const regionToUse = region ?? __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_requireRegion).call(this);
643
703
  const normalizedRegion = regionToUse.toLowerCase().trim();
644
704
  const cacheKey = (0, RequestCache_1.createCacheKey)('getProviders', [
645
705
  normalizedRegion,
@@ -658,8 +718,7 @@ class RampsController extends base_controller_1.BaseController {
658
718
  }, {
659
719
  ...options,
660
720
  resourceType: 'providers',
661
- isResultCurrent: () => this.state.userRegion?.regionCode === undefined ||
662
- this.state.userRegion?.regionCode === normalizedRegion,
721
+ isResultCurrent: () => __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_isRegionCurrent).call(this, normalizedRegion),
663
722
  });
664
723
  this.update((state) => {
665
724
  const userRegionCode = state.userRegion?.regionCode;
@@ -681,13 +740,10 @@ class RampsController extends base_controller_1.BaseController {
681
740
  * @returns The payment methods response containing payments array.
682
741
  */
683
742
  async getPaymentMethods(region, options) {
684
- const regionCode = region ?? this.state.userRegion?.regionCode ?? null;
743
+ const regionCode = region ?? __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_requireRegion).call(this);
685
744
  const fiatToUse = options?.fiat ?? this.state.userRegion?.country?.currency ?? null;
686
745
  const assetIdToUse = options?.assetId ?? this.state.tokens.selected?.assetId ?? '';
687
746
  const providerToUse = options?.provider ?? this.state.providers.selected?.id ?? '';
688
- if (!regionCode) {
689
- throw new Error('Region is required. Either provide a region parameter or ensure userRegion is set in controller state.');
690
- }
691
747
  if (!fiatToUse) {
692
748
  throw new Error('Fiat currency is required. Either provide a fiat parameter or ensure userRegion is set in controller state.');
693
749
  }
@@ -710,10 +766,9 @@ class RampsController extends base_controller_1.BaseController {
710
766
  ...options,
711
767
  resourceType: 'paymentMethods',
712
768
  isResultCurrent: () => {
713
- const regionMatch = this.state.userRegion?.regionCode === undefined ||
714
- this.state.userRegion?.regionCode === normalizedRegion;
715
- const tokenMatch = (this.state.tokens.selected?.assetId ?? '') === assetIdToUse;
716
- const providerMatch = (this.state.providers.selected?.id ?? '') === providerToUse;
769
+ const regionMatch = __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_isRegionCurrent).call(this, normalizedRegion);
770
+ const tokenMatch = __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_isTokenCurrent).call(this, assetIdToUse);
771
+ const providerMatch = __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_isProviderCurrent).call(this, providerToUse);
717
772
  return regionMatch && tokenMatch && providerMatch;
718
773
  },
719
774
  });
@@ -783,7 +838,7 @@ class RampsController extends base_controller_1.BaseController {
783
838
  * @returns The quotes response containing success, sorted, error, and customActions.
784
839
  */
785
840
  async getQuotes(options) {
786
- const regionToUse = options.region ?? this.state.userRegion?.regionCode;
841
+ const regionToUse = options.region ?? __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_requireRegion).call(this);
787
842
  const fiatToUse = options.fiat ?? this.state.userRegion?.country?.currency;
788
843
  const paymentMethodsToUse = options.paymentMethods ??
789
844
  this.state.paymentMethods.data.map((pm) => pm.id);
@@ -791,9 +846,6 @@ class RampsController extends base_controller_1.BaseController {
791
846
  this.state.providers.data.map((provider) => provider.id);
792
847
  const action = options.action ?? 'buy';
793
848
  const assetIdToUse = options.assetId ?? this.state.tokens.selected?.assetId;
794
- if (!regionToUse) {
795
- throw new Error('Region is required. Either provide a region parameter or ensure userRegion is set in controller state.');
796
- }
797
849
  if (!fiatToUse) {
798
850
  throw new Error('Fiat currency is required. Either provide a fiat parameter or ensure userRegion is set in controller state.');
799
851
  }
@@ -844,8 +896,7 @@ class RampsController extends base_controller_1.BaseController {
844
896
  forceRefresh: options.forceRefresh,
845
897
  ttl: options.ttl ?? DEFAULT_QUOTES_TTL,
846
898
  resourceType: 'quotes',
847
- isResultCurrent: () => this.state.userRegion?.regionCode === undefined ||
848
- this.state.userRegion?.regionCode === normalizedRegion,
899
+ isResultCurrent: () => __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_isRegionCurrent).call(this, normalizedRegion),
849
900
  });
850
901
  this.update((state) => {
851
902
  const userRegionCode = state.userRegion?.regionCode;
@@ -861,21 +912,20 @@ class RampsController extends base_controller_1.BaseController {
861
912
  * If the response contains exactly one quote, it is auto-selected.
862
913
  * If multiple quotes are returned, the existing selection is preserved if still valid.
863
914
  *
915
+ * Returns early (no-op) if the selected payment method is not yet set,
916
+ * allowing callers to invoke this before payment-method selection is finalized.
917
+ *
864
918
  * @param options - Parameters for fetching quotes.
865
919
  * @param options.walletAddress - The destination wallet address.
866
920
  * @param options.amount - The amount (in fiat for buy, crypto for sell).
867
921
  * @param options.redirectUrl - Optional redirect URL after order completion.
868
- * @throws If required dependencies (region, token, provider, payment method) are not set.
922
+ * @throws If required dependencies (region, token, provider) are not set.
869
923
  */
870
924
  startQuotePolling(options) {
871
- // Validate required dependencies
872
- const regionCode = this.state.userRegion?.regionCode;
925
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_requireRegion).call(this);
873
926
  const token = this.state.tokens.selected;
874
927
  const provider = this.state.providers.selected;
875
928
  const paymentMethod = this.state.paymentMethods.selected;
876
- if (!regionCode) {
877
- throw new Error('Region is required. Cannot start quote polling without valid region information.');
878
- }
879
929
  if (!token) {
880
930
  throw new Error('Token is required. Cannot start quote polling without a selected token.');
881
931
  }
@@ -900,10 +950,12 @@ class RampsController extends base_controller_1.BaseController {
900
950
  providers: [provider.id],
901
951
  forceRefresh: true,
902
952
  }).then((response) => {
953
+ let newSelectedQuote = null;
903
954
  // Auto-select logic: only when exactly one quote is returned
904
955
  this.update((state) => {
905
956
  if (response.success.length === 1) {
906
- state.quotes.selected = response.success[0];
957
+ newSelectedQuote = response.success[0];
958
+ state.quotes.selected = newSelectedQuote;
907
959
  }
908
960
  else {
909
961
  // Keep existing selection if still valid, but update with fresh data
@@ -912,11 +964,12 @@ class RampsController extends base_controller_1.BaseController {
912
964
  const freshQuote = response.success.find((quote) => quote.provider === currentSelection.provider &&
913
965
  quote.quote.paymentMethod ===
914
966
  currentSelection.quote.paymentMethod);
915
- // Update with fresh quote data, or clear if no longer valid
916
- state.quotes.selected = freshQuote ?? null;
967
+ newSelectedQuote = freshQuote ?? null;
968
+ state.quotes.selected = newSelectedQuote;
917
969
  }
918
970
  }
919
971
  });
972
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncWidgetUrl).call(this, newSelectedQuote);
920
973
  return undefined;
921
974
  }));
922
975
  };
@@ -938,6 +991,7 @@ class RampsController extends base_controller_1.BaseController {
938
991
  }
939
992
  /**
940
993
  * Manually sets the selected quote.
994
+ * Automatically triggers a widget URL fetch for the new quote.
941
995
  *
942
996
  * @param quote - The quote to select, or null to clear the selection.
943
997
  */
@@ -945,6 +999,7 @@ class RampsController extends base_controller_1.BaseController {
945
999
  this.update((state) => {
946
1000
  state.quotes.selected = quote;
947
1001
  });
1002
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncWidgetUrl).call(this, quote);
948
1003
  }
949
1004
  /**
950
1005
  * Cleans up controller resources.
@@ -962,6 +1017,8 @@ class RampsController extends base_controller_1.BaseController {
962
1017
  *
963
1018
  * @param quote - The quote to fetch the widget URL from.
964
1019
  * @returns Promise resolving to the widget URL string, or null if not available.
1020
+ * @deprecated Read `state.widgetUrl` instead. The widget URL is now automatically
1021
+ * fetched and stored in state whenever the selected quote changes.
965
1022
  */
966
1023
  async getWidgetUrl(quote) {
967
1024
  const buyUrl = quote.quote?.buyURL;
@@ -972,34 +1029,459 @@ class RampsController extends base_controller_1.BaseController {
972
1029
  const buyWidget = await this.messenger.call('RampsService:getBuyWidgetUrl', buyUrl);
973
1030
  return buyWidget.url ?? null;
974
1031
  }
975
- catch (error) {
976
- console.error('Error fetching widget URL:', error);
1032
+ catch {
977
1033
  return null;
978
1034
  }
979
1035
  }
1036
+ /**
1037
+ * Fetches an order from the unified V2 API endpoint.
1038
+ * Returns a normalized RampsOrder for all provider types (aggregator and native).
1039
+ *
1040
+ * @param providerCode - The provider code (e.g., "transak", "transak-native", "moonpay").
1041
+ * @param orderCode - The order identifier.
1042
+ * @param wallet - The wallet address associated with the order.
1043
+ * @returns The unified order data.
1044
+ */
1045
+ async getOrder(providerCode, orderCode, wallet) {
1046
+ return await this.messenger.call('RampsService:getOrder', providerCode, orderCode, wallet);
1047
+ }
1048
+ /**
1049
+ * Extracts an order from a provider callback URL.
1050
+ * Sends the callback URL to the V2 backend for provider-specific parsing,
1051
+ * then fetches the full order. This is the V2 equivalent of the aggregator
1052
+ * SDK's `getOrderFromCallback`.
1053
+ *
1054
+ * @param providerCode - The provider code (e.g., "transak", "moonpay").
1055
+ * @param callbackUrl - The full callback URL the provider redirected to.
1056
+ * @param wallet - The wallet address associated with the order.
1057
+ * @returns The unified order data.
1058
+ */
1059
+ async getOrderFromCallback(providerCode, callbackUrl, wallet) {
1060
+ return await this.messenger.call('RampsService:getOrderFromCallback', providerCode, callbackUrl, wallet);
1061
+ }
1062
+ /**
1063
+ * Sets the Transak API key used for all Transak API requests.
1064
+ *
1065
+ * @param apiKey - The Transak API key.
1066
+ */
1067
+ transakSetApiKey(apiKey) {
1068
+ this.messenger.call('TransakService:setApiKey', apiKey);
1069
+ }
1070
+ /**
1071
+ * Sets the Transak access token and marks the user as authenticated.
1072
+ *
1073
+ * @param token - The access token received from Transak auth.
1074
+ */
1075
+ transakSetAccessToken(token) {
1076
+ this.messenger.call('TransakService:setAccessToken', token);
1077
+ this.transakSetAuthenticated(true);
1078
+ }
1079
+ /**
1080
+ * Clears the Transak access token and marks the user as unauthenticated.
1081
+ */
1082
+ transakClearAccessToken() {
1083
+ this.messenger.call('TransakService:clearAccessToken');
1084
+ this.transakSetAuthenticated(false);
1085
+ }
1086
+ /**
1087
+ * Updates the Transak authentication flag in controller state.
1088
+ *
1089
+ * @param isAuthenticated - Whether the user is authenticated with Transak.
1090
+ */
1091
+ transakSetAuthenticated(isAuthenticated) {
1092
+ this.update((state) => {
1093
+ state.nativeProviders.transak.isAuthenticated = isAuthenticated;
1094
+ });
1095
+ }
1096
+ /**
1097
+ * Resets all Transak state back to defaults (unauthenticated, no data).
1098
+ */
1099
+ transakResetState() {
1100
+ this.messenger.call('TransakService:clearAccessToken');
1101
+ this.update((state) => {
1102
+ state.nativeProviders.transak =
1103
+ getDefaultRampsControllerState().nativeProviders.transak;
1104
+ });
1105
+ }
1106
+ /**
1107
+ * Sends a one-time password to the user's email for Transak authentication.
1108
+ *
1109
+ * @param email - The user's email address.
1110
+ * @returns The OTP response containing a state token for verification.
1111
+ */
1112
+ async transakSendUserOtp(email) {
1113
+ return this.messenger.call('TransakService:sendUserOtp', email);
1114
+ }
1115
+ /**
1116
+ * Verifies a one-time password and authenticates the user with Transak.
1117
+ * Updates the controller's authentication state on success.
1118
+ *
1119
+ * @param email - The user's email address.
1120
+ * @param verificationCode - The OTP code entered by the user.
1121
+ * @param stateToken - The state token from the sendUserOtp response.
1122
+ * @returns The access token for subsequent authenticated requests.
1123
+ */
1124
+ async transakVerifyUserOtp(email, verificationCode, stateToken) {
1125
+ const token = await this.messenger.call('TransakService:verifyUserOtp', email, verificationCode, stateToken);
1126
+ this.transakSetAuthenticated(true);
1127
+ return token;
1128
+ }
1129
+ /**
1130
+ * Logs the user out of Transak. Clears authentication state and user details
1131
+ * regardless of whether the API call succeeds or fails.
1132
+ *
1133
+ * @returns A message indicating the logout result.
1134
+ */
1135
+ async transakLogout() {
1136
+ try {
1137
+ const result = await this.messenger.call('TransakService:logout');
1138
+ return result;
1139
+ }
1140
+ finally {
1141
+ this.transakClearAccessToken();
1142
+ this.update((state) => {
1143
+ state.nativeProviders.transak.userDetails.data = null;
1144
+ });
1145
+ }
1146
+ }
1147
+ /**
1148
+ * Fetches the authenticated user's details from Transak.
1149
+ * Updates the userDetails resource state with loading/success/error states.
1150
+ *
1151
+ * @returns The user's profile and KYC details.
1152
+ */
1153
+ async transakGetUserDetails() {
1154
+ this.update((state) => {
1155
+ state.nativeProviders.transak.userDetails.isLoading = true;
1156
+ state.nativeProviders.transak.userDetails.error = null;
1157
+ });
1158
+ try {
1159
+ const details = await this.messenger.call('TransakService:getUserDetails');
1160
+ this.update((state) => {
1161
+ state.nativeProviders.transak.userDetails.data = details;
1162
+ state.nativeProviders.transak.userDetails.isLoading = false;
1163
+ });
1164
+ return details;
1165
+ }
1166
+ catch (error) {
1167
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1168
+ const errorMessage = error?.message ?? 'Unknown error';
1169
+ this.update((state) => {
1170
+ state.nativeProviders.transak.userDetails.isLoading = false;
1171
+ state.nativeProviders.transak.userDetails.error = errorMessage;
1172
+ });
1173
+ throw error;
1174
+ }
1175
+ }
1176
+ /**
1177
+ * Fetches a buy quote from Transak for the given parameters.
1178
+ * Updates the buyQuote resource state with loading/success/error states.
1179
+ *
1180
+ * @param fiatCurrency - The fiat currency code (e.g., "USD").
1181
+ * @param cryptoCurrency - The cryptocurrency identifier.
1182
+ * @param network - The blockchain network identifier.
1183
+ * @param paymentMethod - The payment method identifier.
1184
+ * @param fiatAmount - The fiat amount as a string.
1185
+ * @returns The buy quote with pricing and fee details.
1186
+ */
1187
+ async transakGetBuyQuote(fiatCurrency, cryptoCurrency, network, paymentMethod, fiatAmount) {
1188
+ this.update((state) => {
1189
+ state.nativeProviders.transak.buyQuote.isLoading = true;
1190
+ state.nativeProviders.transak.buyQuote.error = null;
1191
+ });
1192
+ try {
1193
+ const quote = await this.messenger.call('TransakService:getBuyQuote', fiatCurrency, cryptoCurrency, network, paymentMethod, fiatAmount);
1194
+ this.update((state) => {
1195
+ state.nativeProviders.transak.buyQuote.data = quote;
1196
+ state.nativeProviders.transak.buyQuote.isLoading = false;
1197
+ });
1198
+ return quote;
1199
+ }
1200
+ catch (error) {
1201
+ const errorMessage = error?.message ?? 'Unknown error';
1202
+ this.update((state) => {
1203
+ state.nativeProviders.transak.buyQuote.isLoading = false;
1204
+ state.nativeProviders.transak.buyQuote.error = errorMessage;
1205
+ });
1206
+ throw error;
1207
+ }
1208
+ }
1209
+ /**
1210
+ * Fetches the KYC requirement for a given quote.
1211
+ * Updates the kycRequirement resource state with loading/success/error states.
1212
+ *
1213
+ * @param quoteId - The quote ID to check KYC requirements for.
1214
+ * @returns The KYC requirement status and whether the user can place an order.
1215
+ */
1216
+ async transakGetKycRequirement(quoteId) {
1217
+ this.update((state) => {
1218
+ state.nativeProviders.transak.kycRequirement.isLoading = true;
1219
+ state.nativeProviders.transak.kycRequirement.error = null;
1220
+ });
1221
+ try {
1222
+ const requirement = await this.messenger.call('TransakService:getKycRequirement', quoteId);
1223
+ this.update((state) => {
1224
+ state.nativeProviders.transak.kycRequirement.data = requirement;
1225
+ state.nativeProviders.transak.kycRequirement.isLoading = false;
1226
+ });
1227
+ return requirement;
1228
+ }
1229
+ catch (error) {
1230
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1231
+ const errorMessage = error?.message ?? 'Unknown error';
1232
+ this.update((state) => {
1233
+ state.nativeProviders.transak.kycRequirement.isLoading = false;
1234
+ state.nativeProviders.transak.kycRequirement.error = errorMessage;
1235
+ });
1236
+ throw error;
1237
+ }
1238
+ }
1239
+ /**
1240
+ * Fetches additional KYC requirements (e.g., ID proof, address proof) for a quote.
1241
+ *
1242
+ * @param quoteId - The quote ID to check additional requirements for.
1243
+ * @returns The list of additional forms required.
1244
+ */
1245
+ async transakGetAdditionalRequirements(quoteId) {
1246
+ try {
1247
+ return await this.messenger.call('TransakService:getAdditionalRequirements', quoteId);
1248
+ }
1249
+ catch (error) {
1250
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1251
+ throw error;
1252
+ }
1253
+ }
1254
+ /**
1255
+ * Creates a new order on Transak. If an existing order conflicts (HTTP 409),
1256
+ * active orders are cancelled and the creation is retried.
1257
+ *
1258
+ * @param quoteId - The quote ID to create an order from.
1259
+ * @param walletAddress - The destination wallet address.
1260
+ * @param paymentMethodId - The payment method to use.
1261
+ * @returns The created deposit order.
1262
+ */
1263
+ async transakCreateOrder(quoteId, walletAddress, paymentMethodId) {
1264
+ try {
1265
+ return await this.messenger.call('TransakService:createOrder', quoteId, walletAddress, paymentMethodId);
1266
+ }
1267
+ catch (error) {
1268
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1269
+ throw error;
1270
+ }
1271
+ }
1272
+ /**
1273
+ * Fetches an existing order from Transak by order ID.
1274
+ *
1275
+ * @param orderId - The order ID (deposit format or raw Transak format).
1276
+ * @param wallet - The wallet address associated with the order.
1277
+ * @param paymentDetails - Optional payment details to attach to the order.
1278
+ * @returns The deposit order details.
1279
+ */
1280
+ async transakGetOrder(orderId, wallet, paymentDetails) {
1281
+ return this.messenger.call('TransakService:getOrder', orderId, wallet, paymentDetails);
1282
+ }
1283
+ /**
1284
+ * Fetches the user's spending limits for a given currency and payment method.
1285
+ *
1286
+ * @param fiatCurrency - The fiat currency code.
1287
+ * @param paymentMethod - The payment method identifier.
1288
+ * @param kycType - The KYC level type.
1289
+ * @returns The user's limits, spending, and remaining amounts.
1290
+ */
1291
+ async transakGetUserLimits(fiatCurrency, paymentMethod, kycType) {
1292
+ try {
1293
+ return await this.messenger.call('TransakService:getUserLimits', fiatCurrency, paymentMethod, kycType);
1294
+ }
1295
+ catch (error) {
1296
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1297
+ throw error;
1298
+ }
1299
+ }
1300
+ /**
1301
+ * Requests a one-time token (OTT) for the Transak payment widget.
1302
+ *
1303
+ * @returns The OTT response containing the token.
1304
+ */
1305
+ async transakRequestOtt() {
1306
+ try {
1307
+ return await this.messenger.call('TransakService:requestOtt');
1308
+ }
1309
+ catch (error) {
1310
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1311
+ throw error;
1312
+ }
1313
+ }
1314
+ /**
1315
+ * Generates a URL for the Transak payment widget with pre-filled parameters.
1316
+ *
1317
+ * @param ottToken - The one-time token for widget authentication.
1318
+ * @param quote - The buy quote to pre-fill in the widget.
1319
+ * @param walletAddress - The destination wallet address.
1320
+ * @param extraParams - Optional additional URL parameters.
1321
+ * @returns The fully constructed widget URL string.
1322
+ */
1323
+ transakGeneratePaymentWidgetUrl(ottToken, quote, walletAddress, extraParams) {
1324
+ return this.messenger.call('TransakService:generatePaymentWidgetUrl', ottToken, quote, walletAddress, extraParams);
1325
+ }
1326
+ /**
1327
+ * Submits the user's purpose of usage form for KYC compliance.
1328
+ *
1329
+ * @param purpose - Array of purpose strings selected by the user.
1330
+ * @returns A promise that resolves when the form is submitted.
1331
+ */
1332
+ async transakSubmitPurposeOfUsageForm(purpose) {
1333
+ try {
1334
+ return await this.messenger.call('TransakService:submitPurposeOfUsageForm', purpose);
1335
+ }
1336
+ catch (error) {
1337
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1338
+ throw error;
1339
+ }
1340
+ }
1341
+ /**
1342
+ * Updates the user's personal or address details on Transak.
1343
+ *
1344
+ * @param data - The user data fields to update.
1345
+ * @returns The API response data.
1346
+ */
1347
+ async transakPatchUser(data) {
1348
+ try {
1349
+ return await this.messenger.call('TransakService:patchUser', data);
1350
+ }
1351
+ catch (error) {
1352
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1353
+ throw error;
1354
+ }
1355
+ }
1356
+ /**
1357
+ * Submits the user's SSN for identity verification.
1358
+ *
1359
+ * @param ssn - The Social Security Number.
1360
+ * @param quoteId - The quote ID associated with the order requiring SSN.
1361
+ * @returns The API response data.
1362
+ */
1363
+ async transakSubmitSsnDetails(ssn, quoteId) {
1364
+ try {
1365
+ return await this.messenger.call('TransakService:submitSsnDetails', ssn, quoteId);
1366
+ }
1367
+ catch (error) {
1368
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1369
+ throw error;
1370
+ }
1371
+ }
1372
+ /**
1373
+ * Confirms payment for an order after the user has completed payment.
1374
+ *
1375
+ * @param orderId - The order ID to confirm payment for.
1376
+ * @param paymentMethodId - The payment method used.
1377
+ * @returns Whether the payment confirmation was successful.
1378
+ */
1379
+ async transakConfirmPayment(orderId, paymentMethodId) {
1380
+ try {
1381
+ return await this.messenger.call('TransakService:confirmPayment', orderId, paymentMethodId);
1382
+ }
1383
+ catch (error) {
1384
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1385
+ throw error;
1386
+ }
1387
+ }
1388
+ /**
1389
+ * Translates generic ramps identifiers to Transak-specific identifiers.
1390
+ *
1391
+ * @param request - The translation request with optional identifiers to translate.
1392
+ * @returns The translated Transak-specific identifiers.
1393
+ */
1394
+ async transakGetTranslation(request) {
1395
+ return this.messenger.call('TransakService:getTranslation', request);
1396
+ }
1397
+ /**
1398
+ * Checks the status of an ID proof submission for KYC.
1399
+ *
1400
+ * @param workFlowRunId - The workflow run ID to check status for.
1401
+ * @returns The current ID proof status.
1402
+ */
1403
+ async transakGetIdProofStatus(workFlowRunId) {
1404
+ try {
1405
+ return await this.messenger.call('TransakService:getIdProofStatus', workFlowRunId);
1406
+ }
1407
+ catch (error) {
1408
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1409
+ throw error;
1410
+ }
1411
+ }
1412
+ /**
1413
+ * Cancels a specific Transak order.
1414
+ *
1415
+ * @param depositOrderId - The deposit order ID to cancel.
1416
+ * @returns A promise that resolves when the order is cancelled.
1417
+ */
1418
+ async transakCancelOrder(depositOrderId) {
1419
+ try {
1420
+ return await this.messenger.call('TransakService:cancelOrder', depositOrderId);
1421
+ }
1422
+ catch (error) {
1423
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1424
+ throw error;
1425
+ }
1426
+ }
1427
+ /**
1428
+ * Cancels all active Transak orders. Individual cancellation failures
1429
+ * are collected and returned rather than thrown.
1430
+ *
1431
+ * @returns An array of errors from any failed cancellations (empty if all succeeded).
1432
+ */
1433
+ async transakCancelAllActiveOrders() {
1434
+ try {
1435
+ return await this.messenger.call('TransakService:cancelAllActiveOrders');
1436
+ }
1437
+ catch (error) {
1438
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1439
+ throw error;
1440
+ }
1441
+ }
1442
+ /**
1443
+ * Fetches all active Transak orders for the authenticated user.
1444
+ *
1445
+ * @returns The list of active orders.
1446
+ */
1447
+ async transakGetActiveOrders() {
1448
+ try {
1449
+ return await this.messenger.call('TransakService:getActiveOrders');
1450
+ }
1451
+ catch (error) {
1452
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_syncTransakAuthOnError).call(this, error);
1453
+ throw error;
1454
+ }
1455
+ }
980
1456
  }
981
1457
  exports.RampsController = RampsController;
982
1458
  _RampsController_requestCacheTTL = new WeakMap(), _RampsController_requestCacheMaxSize = new WeakMap(), _RampsController_pendingRequests = new WeakMap(), _RampsController_pendingResourceCount = new WeakMap(), _RampsController_quotePollingInterval = new WeakMap(), _RampsController_quotePollingOptions = new WeakMap(), _RampsController_instances = new WeakSet(), _RampsController_clearPendingResourceCountForDependentResources = function _RampsController_clearPendingResourceCountForDependentResources() {
983
- const types = [
984
- 'providers',
985
- 'tokens',
986
- 'paymentMethods',
987
- 'quotes',
988
- ];
989
- for (const resourceType of types) {
1459
+ for (const resourceType of DEPENDENT_RESOURCE_KEYS) {
990
1460
  __classPrivateFieldGet(this, _RampsController_pendingResourceCount, "f").delete(resourceType);
991
1461
  }
992
- }, _RampsController_removeRequestState = function _RampsController_removeRequestState(cacheKey) {
1462
+ }, _RampsController_abortDependentRequests = function _RampsController_abortDependentRequests() {
1463
+ for (const [cacheKey, pending] of __classPrivateFieldGet(this, _RampsController_pendingRequests, "f").entries()) {
1464
+ if (pending.resourceType &&
1465
+ DEPENDENT_RESOURCE_KEYS_SET.has(pending.resourceType)) {
1466
+ pending.abortController.abort();
1467
+ __classPrivateFieldGet(this, _RampsController_pendingRequests, "f").delete(cacheKey);
1468
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_removeRequestState).call(this, cacheKey);
1469
+ }
1470
+ }
1471
+ }, _RampsController_mutateRequests = function _RampsController_mutateRequests(fn) {
993
1472
  this.update((state) => {
994
1473
  const requests = state.requests;
1474
+ fn(requests);
1475
+ });
1476
+ }, _RampsController_removeRequestState = function _RampsController_removeRequestState(cacheKey) {
1477
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_mutateRequests).call(this, (requests) => {
995
1478
  delete requests[cacheKey];
996
1479
  });
997
1480
  }, _RampsController_cleanupState = function _RampsController_cleanupState() {
998
1481
  this.stopQuotePolling();
1482
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_abortDependentRequests).call(this);
999
1483
  __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_clearPendingResourceCountForDependentResources).call(this);
1000
- this.update((state) => resetDependentResources(state, {
1001
- clearUserRegionData: true,
1002
- }));
1484
+ this.update((state) => resetDependentResources(state, { clearUserRegionData: true }));
1003
1485
  }, _RampsController_fireAndForget = function _RampsController_fireAndForget(promise) {
1004
1486
  promise.catch((_error) => undefined);
1005
1487
  }, _RampsController_restartPollingIfActive = function _RampsController_restartPollingIfActive() {
@@ -1014,6 +1496,21 @@ _RampsController_requestCacheTTL = new WeakMap(), _RampsController_requestCacheM
1014
1496
  // when dependencies are available
1015
1497
  }
1016
1498
  }
1499
+ }, _RampsController_requireRegion = function _RampsController_requireRegion() {
1500
+ const regionCode = this.state.userRegion?.regionCode;
1501
+ if (!regionCode) {
1502
+ throw new Error('Region is required. Cannot proceed without valid region information.');
1503
+ }
1504
+ return regionCode;
1505
+ }, _RampsController_isRegionCurrent = function _RampsController_isRegionCurrent(normalizedRegion) {
1506
+ const current = this.state.userRegion?.regionCode;
1507
+ return current === undefined || current === normalizedRegion;
1508
+ }, _RampsController_isTokenCurrent = function _RampsController_isTokenCurrent(normalizedAssetId) {
1509
+ const current = this.state.tokens.selected?.assetId ?? '';
1510
+ return current === normalizedAssetId;
1511
+ }, _RampsController_isProviderCurrent = function _RampsController_isProviderCurrent(normalizedProviderId) {
1512
+ const current = this.state.providers.selected?.id ?? '';
1513
+ return current === normalizedProviderId;
1017
1514
  }, _RampsController_updateResourceField = function _RampsController_updateResourceField(resourceType, field, value) {
1018
1515
  this.update((state) => {
1019
1516
  const resource = state[resourceType];
@@ -1028,11 +1525,8 @@ _RampsController_requestCacheTTL = new WeakMap(), _RampsController_requestCacheM
1028
1525
  }, _RampsController_updateRequestState = function _RampsController_updateRequestState(cacheKey, requestState) {
1029
1526
  const maxSize = __classPrivateFieldGet(this, _RampsController_requestCacheMaxSize, "f");
1030
1527
  const ttl = __classPrivateFieldGet(this, _RampsController_requestCacheTTL, "f");
1031
- this.update((state) => {
1032
- const requests = state.requests;
1528
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_mutateRequests).call(this, (requests) => {
1033
1529
  requests[cacheKey] = requestState;
1034
- // Evict expired entries based on TTL
1035
- // Only evict SUCCESS states that have exceeded their TTL
1036
1530
  const keys = Object.keys(requests);
1037
1531
  for (const key of keys) {
1038
1532
  const entry = requests[key];
@@ -1041,16 +1535,13 @@ _RampsController_requestCacheTTL = new WeakMap(), _RampsController_requestCacheM
1041
1535
  delete requests[key];
1042
1536
  }
1043
1537
  }
1044
- // Evict oldest entries if cache still exceeds max size
1045
1538
  const remainingKeys = Object.keys(requests);
1046
1539
  if (remainingKeys.length > maxSize) {
1047
- // Sort by timestamp (oldest first)
1048
1540
  const sortedKeys = remainingKeys.sort((a, b) => {
1049
1541
  const aTime = requests[a]?.timestamp ?? 0;
1050
1542
  const bTime = requests[b]?.timestamp ?? 0;
1051
1543
  return aTime - bTime;
1052
1544
  });
1053
- // Remove oldest entries until we're under the limit
1054
1545
  const entriesToRemove = remainingKeys.length - maxSize;
1055
1546
  for (let i = 0; i < entriesToRemove; i++) {
1056
1547
  const keyToRemove = sortedKeys[i];
@@ -1060,5 +1551,44 @@ _RampsController_requestCacheTTL = new WeakMap(), _RampsController_requestCacheM
1060
1551
  }
1061
1552
  }
1062
1553
  });
1554
+ }, _RampsController_syncWidgetUrl = function _RampsController_syncWidgetUrl(quote) {
1555
+ const buyUrl = quote?.quote?.buyURL;
1556
+ if (!buyUrl) {
1557
+ this.update((state) => {
1558
+ resetWidgetUrl(state);
1559
+ });
1560
+ return;
1561
+ }
1562
+ if (this.state.widgetUrl.data === null) {
1563
+ this.update((state) => {
1564
+ state.widgetUrl.isLoading = true;
1565
+ state.widgetUrl.error = null;
1566
+ });
1567
+ }
1568
+ __classPrivateFieldGet(this, _RampsController_instances, "m", _RampsController_fireAndForget).call(this, this.messenger
1569
+ .call('RampsService:getBuyWidgetUrl', buyUrl)
1570
+ .then((buyWidget) => {
1571
+ this.update((state) => {
1572
+ state.widgetUrl.data = buyWidget;
1573
+ state.widgetUrl.isLoading = false;
1574
+ state.widgetUrl.error = null;
1575
+ });
1576
+ return undefined;
1577
+ })
1578
+ .catch((error) => {
1579
+ this.update((state) => {
1580
+ state.widgetUrl.isLoading = false;
1581
+ state.widgetUrl.error =
1582
+ error instanceof Error
1583
+ ? error.message
1584
+ : 'Failed to fetch widget URL';
1585
+ });
1586
+ }));
1587
+ }, _RampsController_syncTransakAuthOnError = function _RampsController_syncTransakAuthOnError(error) {
1588
+ if (error instanceof Error &&
1589
+ 'httpStatus' in error &&
1590
+ error.httpStatus === 401) {
1591
+ this.transakSetAuthenticated(false);
1592
+ }
1063
1593
  };
1064
1594
  //# sourceMappingURL=RampsController.cjs.map