-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathinternal.test.ts
More file actions
624 lines (541 loc) · 19.1 KB
/
Copy pathinternal.test.ts
File metadata and controls
624 lines (541 loc) · 19.1 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
import { Networks } from "stellar-sdk";
import {
FUTURENET_NETWORK_DETAILS,
MAINNET_NETWORK_DETAILS,
TESTNET_NETWORK_DETAILS,
} from "@shared/constants/stellar";
import * as GetLedgerKeyAccounts from "../helpers/getLedgerKeyAccounts";
import * as GetIconUrlFromIssuer from "../helpers/getIconUrlFromIssuer";
import * as IconProbe from "../helpers/iconProbe";
import * as internalApi from "../internal";
import { sendMessageToBackground } from "@shared/api/helpers/extensionMessaging";
import { SERVICE_TYPES } from "@shared/constants/services";
jest.mock("@shared/api/helpers/extensionMessaging");
const mockedSend = sendMessageToBackground as jest.Mock;
describe("internalApi", () => {
afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});
describe("getAssetDomains", () => {
it("should return a list of domains from a list of issuers", async () => {
jest
.spyOn(GetLedgerKeyAccounts, "getLedgerKeyAccounts")
.mockResolvedValue({
G1: {
account_id:
"GDF32CQINROD3E2LMCGZUDVMWTXCJFR5SBYVRJ7WAAIAS3P7DCVWZEFY",
home_domain: "stellar1.org",
balance: "1000000000000000000",
seq_num: 1,
num_sub_entries: 1,
inflation_dest: "G1",
flags: 1,
thresholds: "1000000000000000000",
signers: [
{
key: "GDF32CQINROD3E2LMCGZUDVMWTXCJFR5SBYVRJ7WAAIAS3P7DCVWZEFY",
weight: 1,
},
],
sequence_number: 1,
},
G2: {
account_id:
"GBKWMR7TJ7BBICOOXRY2SWXKCWPTOHZPI6MP4LNNE5A73VP3WADGG3CH",
home_domain: "stellar2.org",
balance: "1000000000000000000",
seq_num: 1,
num_sub_entries: 1,
inflation_dest:
"GBKWMR7TJ7BBICOOXRY2SWXKCWPTOHZPI6MP4LNNE5A73VP3WADGG3CH",
flags: 1,
thresholds: "1000000000000000000",
signers: [
{
key: "GBKWMR7TJ7BBICOOXRY2SWXKCWPTOHZPI6MP4LNNE5A73VP3WADGG3CH",
weight: 1,
},
],
sequence_number: 1,
},
});
const assetDomains = await internalApi.getAssetDomains({
assetIssuerDomainsToFetch: [
"GDF32CQINROD3E2LMCGZUDVMWTXCJFR5SBYVRJ7WAAIAS3P7DCVWZEFY",
"GBKWMR7TJ7BBICOOXRY2SWXKCWPTOHZPI6MP4LNNE5A73VP3WADGG3CH",
],
networkDetails: TESTNET_NETWORK_DETAILS,
});
expect(assetDomains).toEqual({
G1: "stellar1.org",
G2: "stellar2.org",
});
});
it("should return an empty object if the fetch fails", async () => {
jest
.spyOn(GetLedgerKeyAccounts, "getLedgerKeyAccounts")
.mockRejectedValue(new Error("Fetch failed"));
const assetDomains = await internalApi.getAssetDomains({
assetIssuerDomainsToFetch: ["G1", "G2"],
networkDetails: TESTNET_NETWORK_DETAILS,
});
expect(assetDomains).toEqual({});
});
it("should return an empty object if not valid public keys are provided", async () => {
const getLedgerKeyAccountsSpy = jest.spyOn(
GetLedgerKeyAccounts,
"getLedgerKeyAccounts",
);
const assetDomains = await internalApi.getAssetDomains({
assetIssuerDomainsToFetch: [
"CAZXRTOKNUQ2JQQF3NCRU7GYMDJNZ2NMQN6IGN4FCT5DWPODMPVEXSND",
],
networkDetails: TESTNET_NETWORK_DETAILS,
});
expect(getLedgerKeyAccountsSpy).not.toHaveBeenCalled();
expect(assetDomains).toEqual({});
});
});
describe("simulateTokenTransfer", () => {
it("includes the fee in stroops in the indexer request body", async () => {
const fetchSpy = jest.spyOn(global, "fetch").mockResolvedValue({
ok: true,
json: jest.fn().mockResolvedValue({
preparedTransaction: "prepared-xdr",
simulationResponse: { minResourceFee: "100" },
}),
} as unknown as Response);
await internalApi.simulateTokenTransfer({
address: "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM",
publicKey: "GBRPYHIL2C2FCU5RNBJQ3WXZH4E2LQ7H5GIPQKNORRACV4W6F6C4P4W5",
memo: "memo",
params: {
publicKey: "GBRPYHIL2C2FCU5RNBJQ3WXZH4E2LQ7H5GIPQKNORRACV4W6F6C4P4W5",
destination:
"GDQP2KPQGKIHYJGXNUIYOMHARUARCA6JYB6CYH6ZJQ4Q25PDBLQZKK7L",
amount: 1,
},
networkDetails: TESTNET_NETWORK_DETAILS,
transactionFee: "0.00001",
});
expect(fetchSpy).toHaveBeenCalledWith(
expect.stringContaining("/simulate-token-transfer"),
expect.objectContaining({
method: "POST",
body: JSON.stringify({
address: "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM",
pub_key: "GBRPYHIL2C2FCU5RNBJQ3WXZH4E2LQ7H5GIPQKNORRACV4W6F6C4P4W5",
memo: "memo",
fee: "100",
params: {
publicKey:
"GBRPYHIL2C2FCU5RNBJQ3WXZH4E2LQ7H5GIPQKNORRACV4W6F6C4P4W5",
destination:
"GDQP2KPQGKIHYJGXNUIYOMHARUARCA6JYB6CYH6ZJQ4Q25PDBLQZKK7L",
amount: 1,
},
network_passphrase: TESTNET_NETWORK_DETAILS.networkPassphrase,
}),
}),
);
});
});
describe("getTokenPrices request payload filtering", () => {
// The v2 path routes through the FETCH_BACKEND_V2 background chokepoint
// (#2879), so it goes through sendMessageToBackground, not a direct fetch.
const mockSendOk = () =>
mockedSend.mockResolvedValue({ status: 200, body: { data: {} } });
const sentMessage = () => mockedSend.mock.calls[0][0];
it("excludes contract-ID issuers from the indexer request", async () => {
mockSendOk();
await internalApi.getTokenPrices(
[
"native",
"USDC:GCK3D3V2XNLLKRFGFFFDEJXA4O2J4X36HET2FE446AV3M4U7DPHO3PEM",
"DT:CCXVDIGMR6WTXZQX2OEVD6YM6AYCYPXPQ7YYH6OZMRS7U6VD3AVHNGBJ",
],
MAINNET_NETWORK_DETAILS,
true,
);
const body = JSON.parse(sentMessage().body as string);
expect(body.tokens).toEqual([
"native",
"USDC:GCK3D3V2XNLLKRFGFFFDEJXA4O2J4X36HET2FE446AV3M4U7DPHO3PEM",
]);
});
it("excludes liquidity-pool IDs from the indexer request", async () => {
mockSendOk();
await internalApi.getTokenPrices(
["native", "abc123:lp"],
MAINNET_NETWORK_DETAILS,
true,
);
const body = JSON.parse(sentMessage().body as string);
expect(body.tokens).toEqual(["native"]);
});
it("targets the v2 chokepoint with the network query param", async () => {
mockSendOk();
await internalApi.getTokenPrices(
["native"],
TESTNET_NETWORK_DETAILS,
true,
);
const message = sentMessage();
expect(message.type).toBe(SERVICE_TYPES.FETCH_BACKEND_V2);
expect(message.method).toBe("POST");
expect(message.path).toContain("/token-prices");
expect(message.path).toContain("network=TESTNET");
});
it("derives the price network from the passphrase for custom networks", async () => {
mockSendOk();
// Custom network stored as STANDALONE but sharing the pubnet passphrase
// must still resolve to PUBLIC and hit the endpoint.
await internalApi.getTokenPrices(
["native"],
{
...MAINNET_NETWORK_DETAILS,
network: "STANDALONE",
networkName: "Custom Pubnet",
networkPassphrase: Networks.PUBLIC,
},
true,
);
expect(mockedSend).toHaveBeenCalled();
expect(sentMessage().path).toContain("network=PUBLIC");
});
it("skips the request on unsupported networks", async () => {
mockSendOk();
const prices = await internalApi.getTokenPrices(
["native"],
FUTURENET_NETWORK_DETAILS,
true,
);
expect(mockedSend).not.toHaveBeenCalled();
expect(prices).toEqual({});
});
it("skips the request when every token is filtered out", async () => {
mockSendOk();
const prices = await internalApi.getTokenPrices(
[
"abc123:lp",
"DT:CCXVDIGMR6WTXZQX2OEVD6YM6AYCYPXPQ7YYH6OZMRS7U6VD3AVHNGBJ",
],
MAINNET_NETWORK_DETAILS,
true,
);
expect(mockedSend).not.toHaveBeenCalled();
expect(prices).toEqual({});
});
});
describe("getTokenPrices v2 response handling", () => {
it("returns the price data from a 200 response", async () => {
const prices = { native: { usd: "1", usdDelta24hPct: "0" } };
mockedSend.mockResolvedValue({ status: 200, body: { data: prices } });
const result = await internalApi.getTokenPrices(
["native"],
TESTNET_NETWORK_DETAILS,
true,
);
expect(result).toEqual(prices);
});
it("throws on a non-200 response", async () => {
mockedSend.mockResolvedValue({ status: 500, body: null });
await expect(
internalApi.getTokenPrices(["native"], TESTNET_NETWORK_DETAILS, true),
).rejects.toThrow();
});
it("throws when a 200 response is missing its data payload", async () => {
// A 200 without `data` must throw, not resolve to undefined — otherwise
// undefined flows into the price cache/UI.
mockedSend.mockResolvedValue({ status: 200, body: {} });
await expect(
internalApi.getTokenPrices(["native"], TESTNET_NETWORK_DETAILS, true),
).rejects.toThrow();
});
});
describe("getTokenPrices v1 endpoint (useV2 = false)", () => {
const mockFetchOk = () =>
jest.spyOn(global, "fetch").mockResolvedValue({
ok: true,
json: jest.fn().mockResolvedValue({ data: {} }),
} as unknown as Response);
it("targets the v1 endpoint without a network query param", async () => {
const fetchSpy = mockFetchOk();
await internalApi.getTokenPrices(
["native"],
TESTNET_NETWORK_DETAILS,
false,
);
const requestUrl = fetchSpy.mock.calls[0][0] as string;
expect(requestUrl).toContain("/token-prices");
expect(requestUrl).not.toContain("network=");
});
it("still filters LP IDs and contract-ID issuers from the request", async () => {
const fetchSpy = mockFetchOk();
await internalApi.getTokenPrices(
[
"native",
"abc123:lp",
"DT:CCXVDIGMR6WTXZQX2OEVD6YM6AYCYPXPQ7YYH6OZMRS7U6VD3AVHNGBJ",
],
MAINNET_NETWORK_DETAILS,
false,
);
const requestInit = fetchSpy.mock.calls[0][1] as RequestInit;
const body = JSON.parse(requestInit.body as string);
expect(body.tokens).toEqual(["native"]);
});
it("does NOT skip unsupported networks (unlike v2)", async () => {
const fetchSpy = mockFetchOk();
await internalApi.getTokenPrices(
["native"],
FUTURENET_NETWORK_DETAILS,
false,
);
expect(fetchSpy).toHaveBeenCalled();
});
it("does NOT skip when every token is filtered out (unlike v2)", async () => {
const fetchSpy = mockFetchOk();
await internalApi.getTokenPrices(
[
"abc123:lp",
"DT:CCXVDIGMR6WTXZQX2OEVD6YM6AYCYPXPQ7YYH6OZMRS7U6VD3AVHNGBJ",
],
MAINNET_NETWORK_DETAILS,
false,
);
expect(fetchSpy).toHaveBeenCalled();
const requestInit = fetchSpy.mock.calls[0][1] as RequestInit;
const body = JSON.parse(requestInit.body as string);
expect(body.tokens).toEqual([]);
});
});
describe("getDiscoverData", () => {
it("fetches /protocols via the FETCH_BACKEND_V2 message", async () => {
mockedSend.mockResolvedValue({
status: 200,
body: {
data: {
protocols: [
{
description: "d",
icon_url: "i",
name: "n",
website_url: "w",
tags: ["t"],
is_blacklisted: false,
is_trending: true,
},
],
},
},
});
const result = await internalApi.getDiscoverData();
expect(mockedSend).toHaveBeenCalledWith({
type: SERVICE_TYPES.FETCH_BACKEND_V2,
activePublicKey: null,
method: "GET",
path: "/protocols",
});
expect(result[0]).toMatchObject({
name: "n",
iconUrl: "i",
isTrending: true,
});
});
});
describe("retryAssetIcon", () => {
const KEY = "GATISXX6BZ6NC7IKQBY37CJD4SOZL3CYZJWXEDG6JVIY4WBS6KXJHN6Q";
const CODE = "USDT0";
const CANONICAL = `${CODE}:${KEY}`;
const FAILED_ICON = "https://ipfs.io/ipfs/bafkreidead";
const OTHER_DEAD_ICON = "https://also-dead.example/icon.png";
const LIVE_ICON = "https://docs.usdt0.to/downloads/usdt0/icon.png";
const TOML_ICON = "https://usdt0.to/icon.png";
const listWith = (icon: string, provider: string) =>
({
name: "Test list",
description: "",
network: "public",
version: "1.0",
provider,
assets: [
{
code: CODE,
issuer: KEY,
name: CODE,
org: CODE,
domain: "usdt0.to",
icon,
decimals: 7,
},
],
}) as any;
/** Stands in for the browser: only the named urls render. */
const onlyLoads = (...loadable: string[]) =>
jest
.spyOn(IconProbe, "firstLoadableIconUrl")
.mockImplementation(async (urls: string[]) =>
urls.find((url) => loadable.includes(url)),
);
const retry = (
assetsListsData: unknown[],
failedIcon: string = FAILED_ICON,
) =>
internalApi.retryAssetIcon({
activePublicKey: null,
key: KEY,
code: CODE,
assetIcons: { [CANONICAL]: failedIcon },
networkDetails: MAINNET_NETWORK_DETAILS,
assetsListsData: assetsListsData as any,
});
it("settles on a candidate that loads", async () => {
onlyLoads(LIVE_ICON);
const result = await retry([
listWith(OTHER_DEAD_ICON, "A"),
listWith(LIVE_ICON, "B"),
]);
expect(result[CANONICAL]).toEqual(LIVE_ICON);
});
it("never re-offers the url that just failed, even if it would load", async () => {
// The url rendered once and is cached; it is failing now. Handing it
// back would just re-render the same broken image.
onlyLoads(FAILED_ICON, LIVE_ICON);
const result = await retry([
listWith(FAILED_ICON, "A"),
listWith(LIVE_ICON, "B"),
]);
expect(result[CANONICAL]).toEqual(LIVE_ICON);
});
it("falls back to the issuer TOML when the lists offer nothing else", async () => {
onlyLoads(TOML_ICON);
jest
.spyOn(GetIconUrlFromIssuer, "getIconUrlFromIssuer")
.mockResolvedValue(TOML_ICON);
const result = await retry([listWith(FAILED_ICON, "A")]);
expect(result[CANONICAL]).toEqual(TOML_ICON);
});
it("clears the icon when no source offers anything that loads", async () => {
onlyLoads();
jest
.spyOn(GetIconUrlFromIssuer, "getIconUrlFromIssuer")
.mockResolvedValue(TOML_ICON);
const result = await retry([listWith(FAILED_ICON, "A")]);
expect(result[CANONICAL]).toEqual("");
});
});
describe("getAssetIcons", () => {
const KEY = "GATISXX6BZ6NC7IKQBY37CJD4SOZL3CYZJWXEDG6JVIY4WBS6KXJHN6Q";
const CODE = "USDT0";
const CANONICAL = `${CODE}:${KEY}`;
const DEAD_ICON = "https://ipfs.io/ipfs/bafkreidead";
const LIVE_ICON = "https://docs.usdt0.to/downloads/usdt0/icon.png";
const TOML_ICON = "https://usdt0.to/icon.png";
const balances = {
[CANONICAL]: {
token: { code: CODE, issuer: { key: KEY } },
},
} as any;
const listWith = (icon: string, provider: string) =>
({
name: "Test list",
description: "",
network: "public",
version: "1.0",
provider,
assets: [
{
code: CODE,
issuer: KEY,
name: CODE,
org: CODE,
domain: "usdt0.to",
icon,
decimals: 7,
},
],
}) as any;
/** Stands in for the browser: only `loadable` renders. */
const onlyLoads = (loadable: string) =>
jest
.spyOn(IconProbe, "firstLoadableIconUrl")
.mockImplementation(async (urls: string[]) =>
urls.find((url) => url === loadable),
);
it("uses the candidate that loads rather than the one listed first", async () => {
onlyLoads(LIVE_ICON);
const icons = await internalApi.getAssetIcons({
balances,
networkDetails: MAINNET_NETWORK_DETAILS,
assetsListsData: [listWith(DEAD_ICON, "A"), listWith(LIVE_ICON, "B")],
cachedIcons: {},
});
expect(icons[CANONICAL]).toEqual(LIVE_ICON);
});
it("caches the icon it settled on, not the one it rejected", async () => {
onlyLoads(LIVE_ICON);
await internalApi.getAssetIcons({
balances,
networkDetails: MAINNET_NETWORK_DETAILS,
assetsListsData: [listWith(DEAD_ICON, "A"), listWith(LIVE_ICON, "B")],
cachedIcons: {},
});
expect(mockedSend).toHaveBeenCalledWith({
activePublicKey: null,
assetCanonical: CANONICAL,
iconUrl: LIVE_ICON,
type: SERVICE_TYPES.CACHE_ASSET_ICON,
});
});
it("falls back to the issuer TOML when no list candidate loads", async () => {
onlyLoads(TOML_ICON);
jest
.spyOn(GetLedgerKeyAccounts, "getLedgerKeyAccounts")
.mockResolvedValue({
[KEY]: { home_domain: "usdt0.to" },
} as any);
jest
.spyOn(GetIconUrlFromIssuer, "getIconUrlFromIssuer")
.mockResolvedValue(TOML_ICON);
const icons = await internalApi.getAssetIcons({
balances,
networkDetails: MAINNET_NETWORK_DETAILS,
assetsListsData: [listWith(DEAD_ICON, "A")],
cachedIcons: {},
});
expect(icons[CANONICAL]).toEqual(TOML_ICON);
});
it("discards an issuer TOML icon that does not load", async () => {
// Nothing renders, including the toml's own url.
onlyLoads("https://nothing-loads.example/icon.png");
jest
.spyOn(GetLedgerKeyAccounts, "getLedgerKeyAccounts")
.mockResolvedValue({
[KEY]: { home_domain: "usdt0.to" },
} as any);
jest
.spyOn(GetIconUrlFromIssuer, "getIconUrlFromIssuer")
.mockResolvedValue(TOML_ICON);
const icons = await internalApi.getAssetIcons({
balances,
networkDetails: MAINNET_NETWORK_DETAILS,
assetsListsData: [listWith(DEAD_ICON, "A")],
cachedIcons: {},
});
expect(icons[CANONICAL]).toBeNull();
});
it("trusts an already-cached icon without re-probing it", async () => {
const probe = jest.spyOn(IconProbe, "firstLoadableIconUrl");
const icons = await internalApi.getAssetIcons({
balances,
networkDetails: MAINNET_NETWORK_DETAILS,
assetsListsData: [listWith(LIVE_ICON, "A")],
cachedIcons: { [CANONICAL]: LIVE_ICON },
});
expect(icons[CANONICAL]).toEqual(LIVE_ICON);
expect(probe).not.toHaveBeenCalled();
});
});
});