-
-
Notifications
You must be signed in to change notification settings - Fork 288
Expand file tree
/
Copy pathRampsController.test.ts
More file actions
11036 lines (10053 loc) · 346 KB
/
Copy pathRampsController.test.ts
File metadata and controls
11036 lines (10053 loc) · 346 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { deriveStateFromMetadata } from '@metamask/base-controller';
import { BrokenCircuitError } from '@metamask/controller-utils';
import { Messenger, MOCK_ANY_NAMESPACE } from '@metamask/messenger';
import type {
MockAnyNamespace,
MessengerActions,
MessengerEvents,
} from '@metamask/messenger';
import * as fs from 'fs';
import * as path from 'path';
import type {
RampsControllerMessenger,
RampsControllerState,
ResourceState,
UserRegion,
} from './RampsController';
import {
normalizeProviderCode,
RampsController,
getDefaultRampsControllerState,
RAMPS_CONTROLLER_REQUIRED_SERVICE_ACTIONS,
} from './RampsController';
import { RAMPS_ERROR_CODES } from './rampsErrorCodes';
import type {
Country,
TokensResponse,
Provider,
State,
PaymentMethod,
PaymentMethodsResponse,
QuotesResponse,
Quote,
RampsToken,
RampsOrder,
} from './RampsService';
import { RampsOrderStatus } from './RampsService';
import type {
RampsServiceGetGeolocationAction,
RampsServiceGetCountriesAction,
RampsServiceGetTokensAction,
RampsServiceGetProvidersAction,
RampsServiceGetPaymentMethodsAction,
RampsServiceGetQuotesAction,
RampsServiceGetBuyWidgetUrlAction,
} from './RampsService-method-action-types';
import { RequestStatus } from './RequestCache';
import type {
TransakAccessToken,
TransakUserDetails,
TransakBuyQuote,
TransakKycRequirement,
TransakAdditionalRequirementsResponse,
TransakDepositOrder,
TransakUserLimits,
TransakOttResponse,
TransakQuoteTranslation,
TransakTranslationRequest,
TransakIdProofStatus,
TransakOrder,
TransakOrderPaymentMethod,
PatchUserRequestBody,
} from './TransakService';
describe('RampsController', () => {
const circuitBreakerOpenErrorMessage =
'Execution prevented because the circuit breaker is open';
describe('normalizeProviderCode', () => {
it('strips /providers/ prefix', () => {
expect(normalizeProviderCode('/providers/transak')).toBe('transak');
expect(normalizeProviderCode('/providers/transak-staging')).toBe(
'transak-staging',
);
});
it('returns string unchanged when no prefix', () => {
expect(normalizeProviderCode('transak')).toBe('transak');
expect(normalizeProviderCode('')).toBe('');
});
});
describe('RAMPS_CONTROLLER_REQUIRED_SERVICE_ACTIONS', () => {
it('includes every RampsService action that RampsController calls', async () => {
expect.hasAssertions();
const controllerPath = path.join(__dirname, 'RampsController.ts');
const source = await fs.promises.readFile(controllerPath, 'utf-8');
const callPattern =
/messenger\.call\s*\(\s*['"]((RampsService|TransakService):[^'"]+)['"]/gu;
const calledActions = new Set<string>();
let match: RegExpExecArray | null;
while ((match = callPattern.exec(source)) !== null) {
calledActions.add(match[1]);
}
const requiredSet = new Set(
RAMPS_CONTROLLER_REQUIRED_SERVICE_ACTIONS as readonly string[],
);
const missing = [...calledActions].filter((a) => !requiredSet.has(a));
const extra = [...requiredSet].filter((a) => !calledActions.has(a));
expect(missing).toHaveLength(0);
expect(extra).toHaveLength(0);
});
});
describe('constructor', () => {
it('uses default state when no state is provided', async () => {
await withController(({ controller }) => {
expect(controller.state).toMatchInlineSnapshot(`
{
"countries": {
"data": [],
"error": null,
"isLoading": false,
"selected": null,
},
"nativeProviders": {
"transak": {
"buyQuote": {
"data": null,
"error": null,
"isLoading": false,
"selected": null,
},
"isAuthenticated": false,
"kycRequirement": {
"data": null,
"error": null,
"isLoading": false,
"selected": null,
},
"userDetails": {
"data": null,
"error": null,
"isLoading": false,
"selected": null,
},
},
},
"orders": [],
"paymentMethods": {
"data": [],
"error": null,
"isLoading": false,
"selected": null,
},
"providerAutoSelected": false,
"providers": {
"data": [],
"error": null,
"isLoading": false,
"selected": null,
},
"requests": {},
"tokens": {
"data": null,
"error": null,
"isLoading": false,
"selected": null,
},
"userRegion": null,
}
`);
});
});
it('accepts initial state', async () => {
const givenState = {
userRegion: createMockUserRegion('us-ca'),
};
await withController(
{ options: { state: givenState } },
({ controller }) => {
expect(controller.state.userRegion?.regionCode).toBe('us-ca');
expect(controller.state.providers.selected).toBeNull();
expect(controller.state.tokens.data).toBeNull();
expect(controller.state.requests).toStrictEqual({});
},
);
});
it('fills in missing initial state with defaults', async () => {
await withController({ options: { state: {} } }, ({ controller }) => {
expect(controller.state).toMatchInlineSnapshot(`
{
"countries": {
"data": [],
"error": null,
"isLoading": false,
"selected": null,
},
"nativeProviders": {
"transak": {
"buyQuote": {
"data": null,
"error": null,
"isLoading": false,
"selected": null,
},
"isAuthenticated": false,
"kycRequirement": {
"data": null,
"error": null,
"isLoading": false,
"selected": null,
},
"userDetails": {
"data": null,
"error": null,
"isLoading": false,
"selected": null,
},
},
},
"orders": [],
"paymentMethods": {
"data": [],
"error": null,
"isLoading": false,
"selected": null,
},
"providerAutoSelected": false,
"providers": {
"data": [],
"error": null,
"isLoading": false,
"selected": null,
},
"requests": {},
"tokens": {
"data": null,
"error": null,
"isLoading": false,
"selected": null,
},
"userRegion": null,
}
`);
});
});
it('always resets requests cache on initialization', async () => {
const givenState = {
userRegion: createMockUserRegion('us-ca'),
requests: {
someKey: {
status: RequestStatus.SUCCESS,
data: 'cached',
error: null,
timestamp: Date.now(),
lastFetchedAt: Date.now(),
},
},
};
await withController(
{ options: { state: givenState } },
({ controller }) => {
expect(controller.state.requests).toStrictEqual({});
},
);
});
});
describe('messenger action handlers', () => {
it('handles RampsController:setSelectedToken', async () => {
const mockToken: RampsToken = {
assetId: 'eip155:1/erc20:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
chainId: 'eip155:1',
name: 'USD Coin',
symbol: 'USDC',
decimals: 6,
iconUrl: 'https://example.com/usdc.png',
tokenSupported: true,
};
const mockTokensResponse: TokensResponse = {
topTokens: [mockToken],
allTokens: [mockToken],
};
await withController(
{
options: {
state: {
userRegion: createMockUserRegion('us-ca'),
tokens: createResourceState(mockTokensResponse, null),
},
},
},
({ controller, messenger, rootMessenger }) => {
rootMessenger.registerActionHandler(
'RampsService:getPaymentMethods',
async () => ({ payments: [] }),
);
messenger.call('RampsController:setSelectedToken', mockToken.assetId);
expect(controller.state.tokens.selected).toStrictEqual(mockToken);
},
);
});
it('handles RampsController:getQuotes', async () => {
const mockQuotesResponse: QuotesResponse = {
success: [
{
provider: '/providers/moonpay',
quote: {
amountIn: 100,
amountOut: '0.05',
paymentMethod: '/payments/debit-credit-card',
amountOutInFiat: 98,
},
metadata: {
reliability: 95,
tags: {
isBestRate: true,
isMostReliable: false,
},
},
},
],
sorted: [
{
sortBy: 'price',
ids: ['/providers/moonpay'],
},
],
error: [],
customActions: [],
};
await withController(async ({ messenger, rootMessenger }) => {
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
async () => mockQuotesResponse,
);
const quotes = await messenger.call('RampsController:getQuotes', {
action: 'buy',
amount: 100,
assetId: 'eip155:1/slip44:60',
fiat: 'USD',
paymentMethods: ['/payments/debit-credit-card'],
providers: ['/providers/moonpay'],
region: 'US',
walletAddress: '0x1234567890abcdef1234567890abcdef12345678',
});
expect(quotes).toStrictEqual(mockQuotesResponse);
});
});
it('handles RampsController:getOrder', async () => {
const mockOrder = {
id: '/providers/transak-staging/orders/abc-123',
isOnlyLink: false,
provider: {
id: '/providers/transak-staging',
name: 'Transak (Staging)',
environmentType: 'STAGING',
description: 'Test provider description',
hqAddress: '123 Test St',
links: [],
logos: { light: '', dark: '', height: 24, width: 77 },
},
success: true,
cryptoAmount: 0.05,
fiatAmount: 100,
cryptoCurrency: { symbol: 'ETH', decimals: 18 },
fiatCurrency: { symbol: 'USD', decimals: 2, denomSymbol: '$' },
providerOrderId: 'abc-123',
providerOrderLink: 'https://transak.com/order/abc-123',
createdAt: 1700000000000,
paymentMethod: { id: '/payments/debit-credit-card', name: 'Card' },
totalFeesFiat: 5,
txHash: '',
walletAddress: '0xabc',
status: RampsOrderStatus.Completed,
network: { chainId: '1', name: 'Ethereum Mainnet' },
canBeUpdated: false,
idHasExpired: false,
excludeFromPurchases: false,
timeDescriptionPending: '',
orderType: 'BUY',
exchangeRate: 2000,
};
await withController(async ({ messenger, rootMessenger }) => {
rootMessenger.registerActionHandler(
'RampsService:getOrder',
async () => mockOrder,
);
const order = await messenger.call(
'RampsController:getOrder',
'transak-staging',
'abc-123',
'0xabc',
);
expect(order).toStrictEqual(mockOrder);
});
});
});
describe('getQuotes provider-scope widening (in-app)', () => {
const SCOPE_ASSET_ID = 'eip155:1/slip44:60';
const SCOPE_PAYMENT_METHOD = '/payments/debit-credit-card';
const SCOPE_WALLET = '0x1234567890abcdef1234567890abcdef12345678';
const NATIVE = '/providers/transak-native';
const MOONPAY = '/providers/moonpay';
const REVOLUT = '/providers/revolut';
const COINBASE = '/providers/coinbase';
const buildScopeProvider = (
id: string,
type: 'native' | 'aggregator',
limits?: Provider['limits'],
): Provider => ({
id,
name: id,
type,
environmentType: 'STAGING',
description: '',
hqAddress: '',
links: [],
logos: { light: '', dark: '', height: 24, width: 77 },
supportedCryptoCurrencies: { [SCOPE_ASSET_ID]: true },
...(limits ? { limits } : {}),
});
const fiatLimit = (
minAmount: number,
maxAmount: number,
): Provider['limits'] => ({
fiat: {
usd: {
[SCOPE_PAYMENT_METHOD]: {
minAmount,
maxAmount,
feeFixedRate: 0,
feeDynamicRate: 0,
},
},
},
});
const inAppScopeQuote = (provider: string, reliability: number): Quote => ({
provider,
quote: {
amountIn: 100,
amountOut: '0.05',
paymentMethod: SCOPE_PAYMENT_METHOD,
buyWidget: {
url: 'https://widget.example/checkout',
browser: 'APP_BROWSER',
},
},
metadata: { reliability },
});
const externalScopeQuote = (
provider: string,
reliability: number,
): Quote => ({
provider,
quote: {
amountIn: 100,
amountOut: '0.05',
paymentMethod: SCOPE_PAYMENT_METHOD,
buyWidget: {
url: 'https://widget.example/checkout',
browser: 'IN_APP_OS_BROWSER',
},
},
metadata: { reliability },
});
const scopeState = (
providers: Provider[],
): Partial<RampsControllerState> => ({
userRegion: createMockUserRegion('us-ca'),
providers: createResourceState(providers, null),
});
const callScopedGetQuotes = async (
messenger: RampsControllerMessenger,
overrides: Record<string, unknown> = {},
): Promise<QuotesResponse> =>
messenger.call('RampsController:getQuotes', {
action: 'buy',
amount: 100,
assetId: SCOPE_ASSET_ID,
fiat: 'USD',
paymentMethods: [SCOPE_PAYMENT_METHOD],
region: 'us-ca',
walletAddress: SCOPE_WALLET,
autoSelectProvider: true,
restrictToKnownOrNativeProviders: true,
...overrides,
});
it('widens to all supporting providers and returns the reliability winner at success[0], excluding external quotes', async () => {
const response: QuotesResponse = {
success: [
inAppScopeQuote(MOONPAY, 90),
inAppScopeQuote(REVOLUT, 80),
externalScopeQuote(COINBASE, 99),
inAppScopeQuote(NATIVE, 70),
],
// Coinbase is the most reliable but external, so it is skipped and the
// next in-app provider (MoonPay) wins.
sorted: [
{ sortBy: 'reliability', ids: [COINBASE, MOONPAY, REVOLUT, NATIVE] },
],
error: [],
customActions: [],
};
await withController(
{
options: {
getProviderScope: () => 'in-app',
state: scopeState([
buildScopeProvider(NATIVE, 'native'),
buildScopeProvider(MOONPAY, 'aggregator'),
buildScopeProvider(REVOLUT, 'aggregator'),
buildScopeProvider(COINBASE, 'aggregator'),
]),
},
},
async ({ messenger, rootMessenger }) => {
let quotedProviders: string[] | undefined;
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
async (params: { providers?: string[] }) => {
quotedProviders = params.providers;
return response;
},
);
const quotes = await callScopedGetQuotes(messenger);
// Widened beyond native-only: every supporting provider was quoted.
expect(quotedProviders).toStrictEqual([
NATIVE,
MOONPAY,
REVOLUT,
COINBASE,
]);
expect(quotes.success[0]?.provider).toBe(MOONPAY);
},
);
});
it('keeps the native provider as a valid in-app candidate and selects it when it ranks first', async () => {
const response: QuotesResponse = {
success: [inAppScopeQuote(NATIVE, 90), inAppScopeQuote(MOONPAY, 80)],
// Transak Native is the most reliable in-app quote, so it wins: the
// in-app scope must not exclude native providers.
sorted: [{ sortBy: 'reliability', ids: [NATIVE, MOONPAY] }],
error: [],
customActions: [],
};
await withController(
{
options: {
getProviderScope: () => 'in-app',
state: scopeState([
buildScopeProvider(NATIVE, 'native'),
buildScopeProvider(MOONPAY, 'aggregator'),
]),
},
},
async ({ messenger, rootMessenger }) => {
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
async () => response,
);
const quotes = await callScopedGetQuotes(messenger);
expect(quotes.success[0]?.provider).toBe(NATIVE);
},
);
});
it('falls back to the price order when there is no reliability order', async () => {
const response: QuotesResponse = {
success: [inAppScopeQuote(MOONPAY, 90), inAppScopeQuote(REVOLUT, 80)],
sorted: [{ sortBy: 'price', ids: [REVOLUT, MOONPAY] }],
error: [],
customActions: [],
};
await withController(
{
options: {
getProviderScope: () => 'in-app',
state: scopeState([
buildScopeProvider(MOONPAY, 'aggregator'),
buildScopeProvider(REVOLUT, 'aggregator'),
]),
},
},
async ({ messenger, rootMessenger }) => {
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
async () => response,
);
const quotes = await callScopedGetQuotes(messenger);
expect(quotes.success[0]?.provider).toBe(REVOLUT);
},
);
});
it('skips a provider whose fiat limits do not fit the amount and picks the next', async () => {
const response: QuotesResponse = {
success: [inAppScopeQuote(MOONPAY, 90), inAppScopeQuote(REVOLUT, 80)],
sorted: [{ sortBy: 'reliability', ids: [MOONPAY, REVOLUT] }],
error: [],
customActions: [],
};
await withController(
{
options: {
getProviderScope: () => 'in-app',
state: scopeState([
// MoonPay's minimum is above the $100 amount, so it is skipped.
buildScopeProvider(MOONPAY, 'aggregator', fiatLimit(200, 1000)),
// Revolut publishes no limits, so it stays eligible.
buildScopeProvider(REVOLUT, 'aggregator'),
]),
},
},
async ({ messenger, rootMessenger }) => {
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
async () => response,
);
const quotes = await callScopedGetQuotes(messenger);
expect(quotes.success[0]?.provider).toBe(REVOLUT);
},
);
});
it('returns an empty success list when no in-app quote is usable', async () => {
const response: QuotesResponse = {
success: [externalScopeQuote(COINBASE, 99)],
sorted: [{ sortBy: 'reliability', ids: [COINBASE] }],
error: [{ provider: MOONPAY, error: 'unavailable' }],
customActions: [],
};
await withController(
{
options: {
getProviderScope: () => 'in-app',
state: scopeState([buildScopeProvider(COINBASE, 'aggregator')]),
},
},
async ({ messenger, rootMessenger }) => {
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
async () => response,
);
const quotes = await callScopedGetQuotes(messenger);
expect(quotes.success).toStrictEqual([]);
expect(quotes.error).toStrictEqual(response.error);
},
);
});
it('returns an empty response on the widened path when no provider supports the asset, even without restrictToKnownOrNativeProviders', async () => {
// A provider is present (so `#getSupportingProvidersForRegion` reads state
// instead of hydrating), but it supports a different asset than
// `SCOPE_ASSET_ID`, leaving the supporting set empty.
const nonSupportingProvider: Provider = {
...buildScopeProvider(MOONPAY, 'aggregator'),
supportedCryptoCurrencies: { 'eip155:1/slip44:0': true },
};
await withController(
{
options: {
getProviderScope: () => 'in-app',
state: scopeState([nonSupportingProvider]),
},
},
async ({ messenger, rootMessenger }) => {
const getQuotesMock = jest.fn();
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
getQuotesMock,
);
// `autoSelectProvider` alone triggers widening; without
// `restrictToKnownOrNativeProviders` the empty guard is reached via the
// `|| widenToInAppProviders` branch.
const quotes = await callScopedGetQuotes(messenger, {
autoSelectProvider: true,
restrictToKnownOrNativeProviders: false,
});
expect(quotes).toStrictEqual({
success: [],
sorted: [],
error: [],
customActions: [],
});
expect(getQuotesMock).not.toHaveBeenCalled();
},
);
});
it('excludes custom-action providers from selection', async () => {
const response: QuotesResponse = {
success: [inAppScopeQuote(MOONPAY, 90), inAppScopeQuote(REVOLUT, 80)],
sorted: [{ sortBy: 'reliability', ids: [MOONPAY, REVOLUT] }],
error: [],
customActions: [
{
buy: { providerId: MOONPAY },
paymentMethodId: SCOPE_PAYMENT_METHOD,
supportedPaymentMethodIds: [SCOPE_PAYMENT_METHOD],
},
],
};
await withController(
{
options: {
getProviderScope: () => 'in-app',
state: scopeState([
buildScopeProvider(MOONPAY, 'aggregator'),
buildScopeProvider(REVOLUT, 'aggregator'),
]),
},
},
async ({ messenger, rootMessenger }) => {
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
async () => response,
);
const quotes = await callScopedGetQuotes(messenger);
// MoonPay is a custom action, so Revolut wins despite ranking higher.
expect(quotes.success[0]?.provider).toBe(REVOLUT);
},
);
});
it('does not widen and does not mutate providers.selected when the scope is off', async () => {
const response: QuotesResponse = {
success: [inAppScopeQuote(NATIVE, 70)],
sorted: [{ sortBy: 'reliability', ids: [NATIVE] }],
error: [],
customActions: [],
};
await withController(
{
options: {
getProviderScope: () => 'off',
state: scopeState([
buildScopeProvider(NATIVE, 'native'),
buildScopeProvider(MOONPAY, 'aggregator'),
]),
},
},
async ({ controller, messenger, rootMessenger }) => {
let quotedProviders: string[] | undefined;
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
async (params: { providers?: string[] }) => {
quotedProviders = params.providers;
return response;
},
);
const quotes = await callScopedGetQuotes(messenger);
// Native-only auto-selection is preserved: only the native provider
// is quoted and the response is returned untouched.
expect(quotedProviders).toStrictEqual([NATIVE]);
expect(quotes).toStrictEqual(response);
expect(controller.state.providers.selected).toBeNull();
},
);
});
it('does not widen when the caller passes an explicit providers list', async () => {
const response: QuotesResponse = {
success: [inAppScopeQuote(MOONPAY, 90)],
sorted: [{ sortBy: 'reliability', ids: [MOONPAY] }],
error: [],
customActions: [],
};
await withController(
{
options: {
getProviderScope: () => 'in-app',
state: scopeState([
buildScopeProvider(MOONPAY, 'aggregator'),
buildScopeProvider(REVOLUT, 'aggregator'),
]),
},
},
async ({ messenger, rootMessenger }) => {
let quotedProviders: string[] | undefined;
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
async (params: { providers?: string[] }) => {
quotedProviders = params.providers;
return response;
},
);
const quotes = await callScopedGetQuotes(messenger, {
providers: [MOONPAY],
});
expect(quotedProviders).toStrictEqual([MOONPAY]);
expect(quotes).toStrictEqual(response);
},
);
});
it('hydrates the provider catalog via getProviders when state is empty', async () => {
const response: QuotesResponse = {
success: [inAppScopeQuote(MOONPAY, 90)],
sorted: [{ sortBy: 'reliability', ids: [MOONPAY] }],
error: [],
customActions: [],
};
await withController(
{
options: {
getProviderScope: () => 'in-app',
state: { userRegion: createMockUserRegion('us-ca') },
},
},
async ({ messenger, rootMessenger }) => {
rootMessenger.registerActionHandler(
'RampsService:getProviders',
async () => ({
providers: [buildScopeProvider(MOONPAY, 'aggregator')],
}),
);
let quotedProviders: string[] | undefined;
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
async (params: { providers?: string[] }) => {
quotedProviders = params.providers;
return response;
},
);
const quotes = await callScopedGetQuotes(messenger);
expect(quotedProviders).toStrictEqual([MOONPAY]);
expect(quotes.success[0]?.provider).toBe(MOONPAY);
},
);
});
it('excludes a quote carrying an inline isCustomAction flag', async () => {
const inlineCustom = inAppScopeQuote(MOONPAY, 90);
(inlineCustom.quote as { isCustomAction?: boolean }).isCustomAction =
true;
const response: QuotesResponse = {
success: [inlineCustom, inAppScopeQuote(REVOLUT, 80)],
sorted: [{ sortBy: 'reliability', ids: [MOONPAY, REVOLUT] }],
error: [],
customActions: [],
};
await withController(
{
options: {
getProviderScope: () => 'in-app',
state: scopeState([
buildScopeProvider(MOONPAY, 'aggregator'),
buildScopeProvider(REVOLUT, 'aggregator'),
]),
},
},
async ({ messenger, rootMessenger }) => {
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
async () => response,
);
const quotes = await callScopedGetQuotes(messenger);
// The inline-flagged MoonPay quote is dropped, so Revolut wins.
expect(quotes.success[0]?.provider).toBe(REVOLUT);
},
);
});
it('falls through to the first candidate when the sort orders reference no surviving provider', async () => {
const response: QuotesResponse = {
success: [inAppScopeQuote(MOONPAY, 90)],
// Neither order lists MoonPay, so both walks fall through to
// the first surviving candidate.
sorted: [
{ sortBy: 'reliability', ids: [COINBASE] },
{ sortBy: 'price', ids: [REVOLUT] },
],
error: [],
customActions: [],
};
await withController(
{
options: {
getProviderScope: () => 'in-app',
state: scopeState([buildScopeProvider(MOONPAY, 'aggregator')]),
},
},
async ({ messenger, rootMessenger }) => {
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
async () => response,
);
const quotes = await callScopedGetQuotes(messenger);
expect(quotes.success[0]?.provider).toBe(MOONPAY);
},
);
});
it('with scope all, does not exclude external or custom-action quotes', async () => {
const response: QuotesResponse = {
success: [
externalScopeQuote(COINBASE, 99),
inAppScopeQuote(MOONPAY, 80),
],
sorted: [{ sortBy: 'reliability', ids: [COINBASE, MOONPAY] }],
error: [],
customActions: [
{
buy: { providerId: MOONPAY },
paymentMethodId: SCOPE_PAYMENT_METHOD,
supportedPaymentMethodIds: [SCOPE_PAYMENT_METHOD],
},
],
};
await withController(
{
options: {
getProviderScope: () => 'all',
state: scopeState([
buildScopeProvider(COINBASE, 'aggregator'),
buildScopeProvider(MOONPAY, 'aggregator'),
]),
},
},
async ({ messenger, rootMessenger }) => {
rootMessenger.registerActionHandler(
'RampsService:getQuotes',
async () => response,
);
const quotes = await callScopedGetQuotes(messenger);
// `all` keeps the external Coinbase quote (top reliability) eligible.
expect(quotes.success[0]?.provider).toBe(COINBASE);
},
);
});
it('widens on restrictToKnownOrNativeProviders alone and selects a provider whose limits fit', async () => {
const response: QuotesResponse = {
success: [inAppScopeQuote(MOONPAY, 90)],
sorted: [{ sortBy: 'reliability', ids: [MOONPAY] }],
error: [],
customActions: [],
};
await withController(
{
options: {
getProviderScope: () => 'in-app',