@metamask-previews/ramps-controller 30.0.0-preview-e9ac9ffe1 → 30.1.0-preview-70269bbdb

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.
@@ -9,6 +9,7 @@ import { PENDING_ORDER_STATUSES, TERMINAL_ORDER_STATUSES, } from './orderStatus.
9
9
  import { buildOwnershipMessage } from './ownership-message.js';
10
10
  import { mergePaymentMethodsById, pickPaymentMethod, } from './paymentMethodMerge.js';
11
11
  import { getProvidersServingAsset, normalizeRampsAssetId, providerServesAsset, } from './providerAvailability.js';
12
+ import { findFirstProviderById, getPreviouslyUsedProviders, } from './providerHistory.js';
12
13
  import { RAMPS_ERROR_CODES } from './rampsErrorCodes.js';
13
14
  import { RampsOrderStatus } from './RampsService.js';
14
15
  import { DEFAULT_REQUEST_CACHE_TTL, DEFAULT_REQUEST_CACHE_MAX_SIZE, createCacheKey, isCacheExpired, createLoadingState, createSuccessState, createErrorState, RequestStatus, } from './RequestCache.js';
@@ -440,6 +441,12 @@ const rampsControllerMetadata = {
440
441
  includeInStateLogs: true,
441
442
  usedInUi: true,
442
443
  },
444
+ userSelectedProviderId: {
445
+ persist: false,
446
+ includeInDebugSnapshot: true,
447
+ includeInStateLogs: true,
448
+ usedInUi: true,
449
+ },
443
450
  };
444
451
  /**
445
452
  * Creates a default resource state object.
@@ -489,6 +496,7 @@ export function getDefaultRampsControllerState() {
489
496
  vbaAutorampListFetchedAt: null,
490
497
  vbaCustomerAbilities: null,
491
498
  providerAutoSelected: false,
499
+ userSelectedProviderId: null,
492
500
  };
493
501
  }
494
502
  const DEPENDENT_RESOURCE_KEYS = [
@@ -537,6 +545,7 @@ function resetDependentResources(state, options) {
537
545
  resetResource(state, key, defaultState[key]);
538
546
  }
539
547
  state.providerAutoSelected = false;
548
+ state.userSelectedProviderId = null;
540
549
  }
541
550
  // === HELPER FUNCTIONS ===
542
551
  /**
@@ -626,6 +635,7 @@ const MESSENGER_EXPOSED_METHODS = [
626
635
  'setUserRegion',
627
636
  'setSelectedProvider',
628
637
  'setSelectedProviderForAsset',
638
+ 'selectProviderForAsset',
629
639
  'init',
630
640
  'getCountries',
631
641
  'getTokens',
@@ -1255,32 +1265,32 @@ export class RampsController extends BaseController {
1255
1265
  * @param options.autoSelected - When true, marks the provider as system-guessed
1256
1266
  * (soft selection). The UI will silently auto-switch on token conflict instead
1257
1267
  * of showing the "Token Not Available" modal. Defaults to false.
1268
+ * @param options.userSelected - When true, also records the provider as the
1269
+ * user's own pick ({@link RampsControllerState.userSelectedProviderId}).
1270
+ * Defaults to false. Passing `null` as the provider always clears the pick.
1258
1271
  */
1259
1272
  setSelectedProvider(providerOrId, options) {
1260
1273
  if (providerOrId === null) {
1261
1274
  this.update((state) => {
1262
1275
  state.providers.selected = null;
1263
1276
  state.providerAutoSelected = false;
1277
+ state.userSelectedProviderId = null;
1264
1278
  });
1265
1279
  return;
1266
1280
  }
1267
1281
  this.#requireRegion();
1268
1282
  // If a full Provider object is passed, store it directly (avoids
1269
1283
  // depending on state.providers.data being populated).
1270
- if (typeof providerOrId !== 'string') {
1271
- this.update((state) => {
1272
- state.providers.selected = providerOrId;
1273
- state.providerAutoSelected = options?.autoSelected ?? false;
1274
- });
1275
- return;
1276
- }
1277
- // ID string: look up from state
1278
- const providers = this.state.providers.data;
1279
- const provider = providers?.find((prov) => prov.id === providerOrId);
1284
+ const provider = typeof providerOrId === 'string'
1285
+ ? this.state.providers.data?.find((prov) => prov.id === providerOrId)
1286
+ : providerOrId;
1280
1287
  if (provider) {
1281
1288
  this.update((state) => {
1282
1289
  state.providers.selected = provider;
1283
1290
  state.providerAutoSelected = options?.autoSelected ?? false;
1291
+ if (options?.userSelected) {
1292
+ state.userSelectedProviderId = provider.id;
1293
+ }
1284
1294
  });
1285
1295
  }
1286
1296
  }
@@ -1330,16 +1340,80 @@ export class RampsController extends BaseController {
1330
1340
  if (compatible.length === 0) {
1331
1341
  return false;
1332
1342
  }
1333
- const preferredIds = this.#getPreferredProviderIdsFromOrders().map(normalizeHeadlessProviderId);
1334
- const preferred = preferredIds
1335
- .map((preferredId) => compatible.find((provider) => normalizeHeadlessProviderId(provider.id) === preferredId))
1336
- .find((provider) => provider !== undefined);
1343
+ const [preferred] = getPreviouslyUsedProviders({
1344
+ providers: compatible,
1345
+ orders: this.state.orders,
1346
+ });
1337
1347
  this.setSelectedProvider(preferred ?? compatible[0], {
1338
1348
  autoSelected: true,
1339
1349
  ...options,
1340
1350
  });
1341
1351
  return true;
1342
1352
  }
1353
+ /**
1354
+ * Selects the provider for the given asset and returns its id.
1355
+ *
1356
+ * Among the providers in `providers.data` that offer the asset (minus
1357
+ * `excludeProviderIds`), the first match wins:
1358
+ * 1. The user's own pick ({@link RampsControllerState.userSelectedProviderId}).
1359
+ * 2. The first provider in `aheadOfHistory`.
1360
+ * 3. The provider of the most recent completed buy, across all accounts,
1361
+ * from controller orders plus `extraHistory`.
1362
+ * 4. The first provider in API ranking order.
1363
+ *
1364
+ * With a `null` asset (no token chosen yet) every provider is a candidate
1365
+ * and step 2 is skipped, since that list only applies to assets its
1366
+ * providers offer.
1367
+ *
1368
+ * The selection is marked auto-selected unless it is the user's own pick.
1369
+ * The user's pick is kept when another provider is chosen, so it comes back
1370
+ * on the next asset it offers.
1371
+ *
1372
+ * @param assetId - CAIP-19 asset id the user is buying, or `null`.
1373
+ * @param options - Optional inputs.
1374
+ * @param options.aheadOfHistory - Provider ids that win over history.
1375
+ * @param options.extraHistory - Completed buys from outside controller state.
1376
+ * @param options.excludeProviderIds - Provider ids to leave out.
1377
+ * @returns The selected provider id, or `null` when providers are not loaded
1378
+ * or none offers the asset (the selection is left unchanged).
1379
+ */
1380
+ selectProviderForAsset(assetId, options) {
1381
+ const providers = this.state.providers.data;
1382
+ if (!providers?.length) {
1383
+ return null;
1384
+ }
1385
+ const excluded = new Set((options?.excludeProviderIds ?? []).map(normalizeHeadlessProviderId));
1386
+ const candidates = providers.filter((provider) => !excluded.has(normalizeHeadlessProviderId(provider.id)) &&
1387
+ (assetId === null || providerServesAsset(provider, assetId)));
1388
+ if (candidates.length === 0) {
1389
+ return null;
1390
+ }
1391
+ const { userSelectedProviderId } = this.state;
1392
+ const userPick = userSelectedProviderId
1393
+ ? findFirstProviderById(candidates, [userSelectedProviderId])
1394
+ : undefined;
1395
+ const aheadOfHistory = assetId === null ? [] : (options?.aheadOfHistory ?? []);
1396
+ const [previouslyUsed] = getPreviouslyUsedProviders({
1397
+ providers: candidates,
1398
+ orders: this.state.orders,
1399
+ extraHistory: options?.extraHistory,
1400
+ });
1401
+ const chosen = userPick ??
1402
+ findFirstProviderById(candidates, aheadOfHistory) ??
1403
+ previouslyUsed ??
1404
+ candidates[0];
1405
+ const autoSelected = chosen !== userPick;
1406
+ // Compared by reference so a stale copy of the same provider is replaced
1407
+ // once a fresh provider list has arrived.
1408
+ if (this.state.providers.selected !== chosen ||
1409
+ this.state.providerAutoSelected !== autoSelected) {
1410
+ this.update((state) => {
1411
+ state.providers.selected = chosen;
1412
+ state.providerAutoSelected = autoSelected;
1413
+ });
1414
+ }
1415
+ return chosen.id;
1416
+ }
1343
1417
  /**
1344
1418
  * Initializes the controller by fetching the user's region from geolocation.
1345
1419
  * This should be called once at app startup to set up the initial region.
@@ -2254,12 +2328,14 @@ export class RampsController extends BaseController {
2254
2328
  // `preferredProviderIds` when supplied, otherwise completed-order
2255
2329
  // history. Takes priority over Transak Native to preserve an existing
2256
2330
  // KYC relationship and avoid churn.
2257
- const preferred = preferredProviderIds ?? this.#getPreferredProviderIdsFromOrders();
2258
- for (const preferredId of preferred) {
2259
- const match = supporting.find((provider) => provider.id === preferredId);
2260
- if (match) {
2261
- return [match.id];
2262
- }
2331
+ const preferred = preferredProviderIds
2332
+ ? findFirstProviderById(supporting, preferredProviderIds)
2333
+ : getPreviouslyUsedProviders({
2334
+ providers: supporting,
2335
+ orders: this.state.orders,
2336
+ })[0];
2337
+ if (preferred) {
2338
+ return [preferred.id];
2263
2339
  }
2264
2340
  // 3. A native provider (e.g. Transak Native).
2265
2341
  const nativeProvider = supporting.find((provider) => provider.type === 'native');
@@ -2332,28 +2408,6 @@ export class RampsController extends BaseController {
2332
2408
  const selectedId = this.state.providers.selected?.id;
2333
2409
  return selectedId ? [selectedId] : [];
2334
2410
  }
2335
- /**
2336
- * Derives an ordered list of provider IDs from the user's completed-order
2337
- * history, most recently completed first, with duplicates removed.
2338
- *
2339
- * Reads only this controller's own normalized order state, so it carries no
2340
- * dependency on any client-specific order representation.
2341
- *
2342
- * @returns Provider IDs ordered by most recent completed order.
2343
- */
2344
- #getPreferredProviderIdsFromOrders() {
2345
- const orderedIds = [];
2346
- const completedOrders = this.state.orders
2347
- .filter((order) => order.status === RampsOrderStatus.Completed && order.provider?.id)
2348
- .sort((orderA, orderB) => orderB.createdAt - orderA.createdAt);
2349
- for (const order of completedOrders) {
2350
- const id = order.provider?.id;
2351
- if (id && !orderedIds.includes(id)) {
2352
- orderedIds.push(id);
2353
- }
2354
- }
2355
- return orderedIds;
2356
- }
2357
2411
  // === ORDER MANAGEMENT ===
2358
2412
  /**
2359
2413
  * Adds or updates a V2 order in controller state.
@@ -3274,8 +3328,14 @@ export class RampsController extends BaseController {
3274
3328
  }
3275
3329
  meta.lastTimeFetched = Date.now();
3276
3330
  this.#orderPollingMeta.set(order.providerOrderId, meta);
3331
+ // Publish only a transition that is now stored. A transition the
3332
+ // controller could not write (for example the order was removed while the
3333
+ // request was in flight) would otherwise be republished on every poll.
3334
+ const storedStatus = this.state.orders.find((existingOrder) => getInternalOrderCode(existingOrder) ===
3335
+ getInternalOrderCode(updatedOrder))?.status;
3277
3336
  if (previousStatus !== updatedOrder.status &&
3278
- previousStatus !== undefined) {
3337
+ previousStatus !== undefined &&
3338
+ storedStatus === updatedOrder.status) {
3279
3339
  this.messenger.publish('RampsController:orderStatusChanged', {
3280
3340
  order: updatedOrder,
3281
3341
  previousStatus,
@@ -3474,15 +3534,27 @@ export class RampsController extends BaseController {
3474
3534
  const hadOrderAtRequestStart = this.state.orders.some((existingOrder) => getInternalOrderCode(existingOrder) === orderCode);
3475
3535
  const order = await this.messenger.call('RampsService:getOrder', providerCode, orderCode, wallet);
3476
3536
  const healedWalletAddress = order.walletAddress || wallet;
3477
- const internalOrderCode = getInternalOrderCode({
3537
+ const requestedOrderCode = getInternalOrderCode(orderCode);
3538
+ const storedOrder = this.state.orders.find((existingOrder) => getInternalOrderCode(existingOrder) === requestedOrderCode);
3539
+ const fetchedOrderCode = getInternalOrderCode({
3478
3540
  id: order.id,
3479
3541
  providerOrderId: orderCode,
3480
3542
  });
3543
+ // The order was requested by the code it is stored under, so the response
3544
+ // is that order even when its canonical `id` carries a different code.
3545
+ // Keep the stored identity so the write below updates the stored row.
3546
+ // Re-keying it would leave the stored row at its old status, and polling
3547
+ // would republish the same transition on every cycle.
3548
+ const keepsStoredIdentity = storedOrder !== undefined && fetchedOrderCode !== requestedOrderCode;
3481
3549
  const healedOrder = {
3482
3550
  ...order,
3483
3551
  walletAddress: healedWalletAddress,
3484
- providerOrderId: internalOrderCode,
3552
+ ...(keepsStoredIdentity ? { id: storedOrder.id } : {}),
3553
+ providerOrderId: keepsStoredIdentity
3554
+ ? requestedOrderCode
3555
+ : fetchedOrderCode,
3485
3556
  };
3557
+ const internalOrderCode = getInternalOrderCode(healedOrder);
3486
3558
  const orderStillExists = this.state.orders.some((existingOrder) => getInternalOrderCode(existingOrder) === internalOrderCode);
3487
3559
  // A polling request can finish after removeOrder. Do not let that stale
3488
3560
  // response recreate the local order and overwrite its remote tombstone.