-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathinternal.ts
More file actions
2777 lines (2507 loc) · 67.5 KB
/
Copy pathinternal.ts
File metadata and controls
2777 lines (2507 loc) · 67.5 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 { captureException } from "@sentry/browser";
import {
Address,
rpc as SorobanRpc,
Networks,
Horizon,
FeeBumpTransaction,
StrKey,
Transaction,
TransactionBuilder,
xdr,
XdrLargeInt,
} from "stellar-sdk";
import BigNumber from "bignumber.js";
import { INDEXER_URL } from "@shared/constants/mercury";
import {
AutoLockTimeoutMinutes,
DEFAULT_AUTO_LOCK_TIMEOUT_MINUTES,
} from "@shared/constants/autoLock";
import {
AssetListResponse,
AssetsListItem,
AssetsLists,
} from "@shared/constants/soroban/asset-list";
import {
getBalance,
getDecimals,
getName,
getSymbol,
transfer,
} from "@shared/helpers/soroban/token";
import {
getAssetFromCanonical,
getCanonicalFromAsset,
getSdk,
isCustomNetwork,
makeDisplayableBalances,
xlmToStroop,
} from "@shared/helpers/stellar";
import {
buildSorobanServer,
getNewTxBuilder,
} from "@shared/helpers/soroban/server";
import {
getContractSpec as getContractSpecHelper,
getIsTokenSpec as getIsTokenSpecHelper,
isContractId,
} from "./helpers/soroban";
import {
Account,
AllowList,
BalanceToMigrate,
MigratableAccount,
MigratedAccount,
Settings,
IndexerSettings,
SettingsState,
ExperimentalFeatures,
IssuerKey,
AssetVisibility,
ApiTokenPrices,
HorizonOperation,
UserNotification,
CollectibleContract,
DiscoverData,
RecentProtocolEntry,
SaveSettingsResponse,
TrendingAsset,
} from "./types";
import {
AccountBalancesInterface,
BalanceMap,
Balances,
V2AccountBalances,
} from "./types/backend-api";
import {
MAINNET_NETWORK_DETAILS,
DEFAULT_NETWORKS,
NetworkDetails,
NETWORKS,
PASSPHRASE_TO_PRICE_NETWORK,
} from "../constants/stellar";
import { SERVICE_TYPES } from "../constants/services";
import { isDev } from "../helpers/dev";
import { SorobanRpcNotSupportedError } from "../constants/errors";
import { APPLICATION_STATE } from "../constants/applicationState";
import { WalletType } from "../constants/hardwareWallet";
import { sendMessageToBackground } from "./helpers/extensionMessaging";
import { fetchBackendV2 } from "./helpers/fetchBackendV2";
import { getIconUrlFromIssuer } from "./helpers/getIconUrlFromIssuer";
import { getLedgerKeyAccounts } from "./helpers/getLedgerKeyAccounts";
import { redactErrorBody } from "./helpers/redactErrorBody";
import { stellarSdkServer, submitTx } from "./helpers/stellarSdkServer";
import { getIconFromTokenLists } from "./helpers/getIconFromTokenList";
import { mapAccountBalancesV2 } from "./helpers/mapAccountBalancesV2";
import { addBlockaidScanResults } from "./helpers/addBlockaidScanResults";
import { injectLocalTokenBalances } from "./helpers/injectLocalTokenBalances";
const TRANSACTIONS_LIMIT = 100;
export const SendTxStatus: {
[index: string]: SorobanRpc.Api.SendTransactionStatus;
} = {
Pending: "PENDING",
Duplicate: "DUPLICATE",
Retry: "TRY_AGAIN_LATER",
Error: "ERROR",
};
export const GetTxStatus: {
[index: string]: SorobanRpc.Api.GetTransactionStatus;
} = {
Success: SorobanRpc.Api.GetTransactionStatus.SUCCESS,
NotFound: SorobanRpc.Api.GetTransactionStatus.NOT_FOUND,
Failed: SorobanRpc.Api.GetTransactionStatus.FAILED,
};
export const DEFAULT_ALLOW_LIST: AllowList = {
[NETWORKS.PUBLIC]: {},
[NETWORKS.TESTNET]: {},
[NETWORKS.FUTURENET]: {},
};
export const createAccount = async ({
password,
isOverwritingAccount = false,
}: {
password: string;
isOverwritingAccount: boolean;
}): Promise<{
publicKey: string;
allAccounts: Array<Account>;
hasPrivateKey: boolean;
}> => {
let publicKey = "";
let allAccounts = [] as Array<Account>;
let hasPrivateKey = false;
let error = "";
try {
({ allAccounts, publicKey, hasPrivateKey, error } =
await sendMessageToBackground({
activePublicKey: null,
password,
isOverwritingAccount,
type: SERVICE_TYPES.CREATE_ACCOUNT,
}));
} catch (e) {
console.error(e);
}
if (error) {
throw new Error(error);
}
return { allAccounts, publicKey, hasPrivateKey };
};
export const fundAccount = async ({
activePublicKey,
publicKey,
}: {
activePublicKey: string;
publicKey: string;
}): Promise<void> => {
try {
await sendMessageToBackground({
activePublicKey,
publicKey,
type: SERVICE_TYPES.FUND_ACCOUNT,
});
} catch (e) {
console.error(e);
}
};
export const addAccount = async ({
activePublicKey,
password,
}: {
activePublicKey: string;
password: string;
}): Promise<{
publicKey: string;
allAccounts: Array<Account>;
hasPrivateKey: boolean;
}> => {
let error = "";
let publicKey = "";
let allAccounts = [] as Array<Account>;
let hasPrivateKey = false;
try {
({ allAccounts, error, publicKey, hasPrivateKey } =
await sendMessageToBackground({
activePublicKey,
password,
type: SERVICE_TYPES.ADD_ACCOUNT,
}));
} catch (e) {
console.error(e);
}
if (error) {
throw new Error(error);
}
return { allAccounts, publicKey, hasPrivateKey };
};
export const importAccount = async ({
password,
privateKey,
activePublicKey,
}: {
password: string;
privateKey: string;
activePublicKey: string;
}): Promise<{
publicKey: string;
allAccounts: Array<Account>;
hasPrivateKey: boolean;
}> => {
let error = "";
let publicKey = "";
let allAccounts = [] as Array<Account>;
let hasPrivateKey = false;
try {
({ allAccounts, publicKey, error, hasPrivateKey } =
await sendMessageToBackground({
activePublicKey,
password,
privateKey,
type: SERVICE_TYPES.IMPORT_ACCOUNT,
}));
} catch (e) {
console.error(e);
}
// @TODO: should this be universal? See asana ticket.
if (error) {
throw new Error(error);
}
return { allAccounts, publicKey, hasPrivateKey };
};
export const importHardwareWallet = async ({
activePublicKey,
publicKey,
hardwareWalletType,
bipPath,
}: {
activePublicKey: string;
publicKey: string;
hardwareWalletType: WalletType;
bipPath: string;
}) => {
let _publicKey = "";
let allAccounts = [] as Array<Account>;
let hasPrivateKey = false;
let _bipPath = "";
try {
({
publicKey: _publicKey,
allAccounts,
hasPrivateKey,
bipPath: _bipPath,
} = await sendMessageToBackground({
activePublicKey,
publicKey,
hardwareWalletType,
bipPath,
type: SERVICE_TYPES.IMPORT_HARDWARE_WALLET,
}));
} catch (e) {
console.log({ e });
}
return {
allAccounts,
publicKey: _publicKey,
hasPrivateKey,
bipPath: _bipPath,
};
};
export const makeAccountActive = ({
activePublicKey,
publicKey,
}: {
activePublicKey: string;
publicKey: string;
}): Promise<{ publicKey: string; hasPrivateKey: boolean; bipPath: string }> =>
sendMessageToBackground({
activePublicKey,
publicKey,
type: SERVICE_TYPES.MAKE_ACCOUNT_ACTIVE,
});
export const updateAccountName = ({
activePublicKey,
accountName,
publicKey,
}: {
activePublicKey: string;
accountName: string;
publicKey: string;
}): Promise<{ allAccounts: Array<Account> }> =>
sendMessageToBackground({
activePublicKey,
accountName,
publicKey,
type: SERVICE_TYPES.UPDATE_ACCOUNT_NAME,
});
export const loadAccount = (): Promise<{
hasPrivateKey: boolean;
publicKey: string;
applicationState: APPLICATION_STATE;
allAccounts: Array<Account>;
bipPath: string;
tokenIdList: string[];
}> =>
sendMessageToBackground({
activePublicKey: null,
type: SERVICE_TYPES.LOAD_ACCOUNT,
});
export const getMnemonicPhrase = async (): Promise<{
mnemonicPhrase: string;
}> => {
let response = { mnemonicPhrase: "" };
try {
response = await sendMessageToBackground({
activePublicKey: null,
type: SERVICE_TYPES.GET_MNEMONIC_PHRASE,
});
} catch (e) {
console.error(e);
}
return response;
};
export const getMigratedMnemonicPhrase = async (): Promise<{
mnemonicPhrase: string;
}> => {
let response = { mnemonicPhrase: "" };
try {
response = await sendMessageToBackground({
activePublicKey: null,
type: SERVICE_TYPES.GET_MIGRATED_MNEMONIC_PHRASE,
});
} catch (e) {
console.error(e);
}
return response;
};
export const confirmMnemonicPhrase = async (
mnemonicPhraseToConfirm: string,
): Promise<{
isCorrectPhrase: boolean;
applicationState: APPLICATION_STATE;
}> => {
let response = {
isCorrectPhrase: false,
applicationState: APPLICATION_STATE.PASSWORD_CREATED,
};
try {
response = await sendMessageToBackground({
activePublicKey: null,
mnemonicPhraseToConfirm,
type: SERVICE_TYPES.CONFIRM_MNEMONIC_PHRASE,
});
} catch (e) {
console.error(e);
}
return response;
};
export const confirmMigratedMnemonicPhrase = async (
mnemonicPhraseToConfirm: string,
): Promise<{
isCorrectPhrase: boolean;
}> => {
let response = {
isCorrectPhrase: false,
};
try {
response = await sendMessageToBackground({
activePublicKey: null,
mnemonicPhraseToConfirm,
type: SERVICE_TYPES.CONFIRM_MIGRATED_MNEMONIC_PHRASE,
});
} catch (e) {
console.error(e);
}
return response;
};
export const recoverAccount = async ({
password,
recoverMnemonic,
isOverwritingAccount = false,
}: {
password: string;
recoverMnemonic: string;
isOverwritingAccount: boolean;
}): Promise<{
publicKey: string;
allAccounts: Array<Account>;
hasPrivateKey: boolean;
error: string;
}> => {
let publicKey = "";
let allAccounts = [] as Array<Account>;
let hasPrivateKey = false;
let error = "";
try {
({ allAccounts, publicKey, hasPrivateKey, error } =
await sendMessageToBackground({
activePublicKey: null,
password,
recoverMnemonic,
isOverwritingAccount,
type: SERVICE_TYPES.RECOVER_ACCOUNT,
}));
} catch (e) {
console.error(e);
}
return { allAccounts, publicKey, hasPrivateKey, error };
};
export const confirmPassword = async (
password: string,
): Promise<{
publicKey: string;
hasPrivateKey: boolean;
applicationState: APPLICATION_STATE;
allAccounts: Array<Account>;
bipPath: string;
}> => {
let response = {
publicKey: "",
hasPrivateKey: false,
applicationState: APPLICATION_STATE.MNEMONIC_PHRASE_CONFIRMED,
allAccounts: [] as Array<Account>,
bipPath: "",
};
try {
response = await sendMessageToBackground({
activePublicKey: null,
password,
type: SERVICE_TYPES.CONFIRM_PASSWORD,
});
} catch (e) {
console.error(e);
}
return response;
};
export const getAccountInfo = async ({
publicKey,
networkDetails,
}: {
publicKey: string;
networkDetails: NetworkDetails;
}) => {
const { networkUrl } = networkDetails;
const server = new Horizon.Server(networkUrl);
let account;
let signerArr = { records: [] as Horizon.ServerApi.AccountRecord[] };
try {
account = await server.loadAccount(publicKey);
signerArr = await server.accounts().forSigner(publicKey).call();
} catch (e) {
console.error(e);
}
return {
account,
isSigner: signerArr.records.length > 1,
};
};
export const getMigratableAccounts = async () => {
let migratableAccounts: MigratableAccount[] = [];
try {
({ migratableAccounts } = await sendMessageToBackground({
activePublicKey: null,
type: SERVICE_TYPES.GET_MIGRATABLE_ACCOUNTS,
}));
} catch (e) {
console.error(e);
}
return { migratableAccounts };
};
/**
* Fetches the seed-derived analytics user id from the background. Returns
* `null` when locked (no active session) or if the message fails.
*/
export const getAnalyticsUserId = async (): Promise<{
analyticsUserId: string | null;
}> => {
let analyticsUserId: string | null = null;
try {
({ analyticsUserId } = await sendMessageToBackground({
activePublicKey: null,
type: SERVICE_TYPES.GET_ANALYTICS_USER_ID,
}));
} catch (e) {
console.error(e);
}
return { analyticsUserId };
};
export const migrateAccounts = async ({
balancesToMigrate,
isMergeSelected,
recommendedFee,
}: {
balancesToMigrate: BalanceToMigrate[];
isMergeSelected: boolean;
recommendedFee: string;
}): Promise<{
publicKey: string;
migratedAccounts: Array<MigratedAccount>;
allAccounts: Array<Account>;
hasPrivateKey: boolean;
error: string;
}> => {
let publicKey = "";
let migratedAccounts = [] as Array<MigratedAccount>;
let allAccounts = [] as Array<Account>;
let hasPrivateKey = false;
let error = "";
try {
({ migratedAccounts, allAccounts, publicKey, hasPrivateKey, error } =
await sendMessageToBackground({
activePublicKey: null,
balancesToMigrate,
isMergeSelected,
recommendedFee,
type: SERVICE_TYPES.MIGRATE_ACCOUNTS,
}));
} catch (e) {
console.error(e);
}
return { migratedAccounts, allAccounts, publicKey, hasPrivateKey, error };
};
export const getAccountIndexerBalances = async ({
publicKey,
networkDetails,
shouldSkipScan,
}: {
publicKey: string;
networkDetails: NetworkDetails;
shouldSkipScan?: boolean;
}): Promise<AccountBalancesInterface> => {
const contractIds = await getTokenIds({
activePublicKey: publicKey,
network: networkDetails.network as NETWORKS,
});
const url = new URL(`${INDEXER_URL}/account-balances/${publicKey}`);
url.searchParams.append("network", networkDetails.network);
if (shouldSkipScan) {
url.searchParams.append("should_skip_scan", "true");
}
for (const id of contractIds) {
url.searchParams.append("contract_ids", id);
}
const response = await fetch(url.href);
const data = (await response.json()) as AccountBalancesInterface;
if (!response.ok) {
const _err = JSON.stringify(data);
captureException(
`Failed to fetch account balances - ${response.status}: ${response.statusText}`,
);
throw new Error(_err);
}
if ("error" in data && (data?.error?.horizon || data?.error?.soroban)) {
captureException(
`Failed to fetch account balances - ${response.status}: ${response.statusText}`,
);
}
const formattedBalances = {} as NonNullable<
AccountBalancesInterface["balances"]
>;
for (const balanceKey of Object.keys(data.balances || {})) {
const balance = data.balances![balanceKey];
formattedBalances[balanceKey] = {
...balance,
available: new BigNumber(balance.available),
total: new BigNumber(balance.total),
};
}
return {
...data,
balances: formattedBalances,
// v1 returns a contract-token balance only for an ID it was handed, so
// every locally saved contract is removable from the balances view.
localOnlyTokenIds: contractIds,
};
};
export const getAccountBalancesV2 = async ({
publicKey,
networkDetails,
shouldSkipScan,
}: {
publicKey: string;
networkDetails: NetworkDetails;
shouldSkipScan?: boolean;
}): Promise<AccountBalancesInterface> => {
// Multi-address fan-out endpoint; the extension fetches one account at a
// time. Addresses travel in the POST body, so the URL carries no G-address
// (unlike the v1 GET path, which needs the beforeSend URL scrubber). The
// *response* does key its results by address, so bodies reported to Sentry
// below go through redactErrorBody — beforeSend only rewrites request URLs,
// never message strings.
//
// This is a freighter-backend-v2 call, so it goes through the background
// chokepoint (callBackendV2), which attaches the per-request JWT (#2879).
// Balances are only fetched from an unlocked wallet, so the request always
// carries the JWT. The query lives in the path so callBackendV2 signs the
// JWT's methodAndPath over the server's full request-target (path + query).
const { status, body } = await fetchBackendV2({
method: "POST",
path: `/accounts/balances?network=${networkDetails.network}`,
body: JSON.stringify({ addresses: [publicKey] }),
});
// Mirror getTokenPrices: a 200 without a `data` payload is still a failure —
// callers' try/catch only handles throws, not bad returns.
const parsedResponse = body as { data?: V2AccountBalances[] };
if (status !== 200 || !parsedResponse?.data) {
const _err = JSON.stringify(body);
captureException(
`Failed to fetch account balances v2 - ${status}: ${redactErrorBody(
body,
)}`,
);
throw new Error(_err);
}
const account = parsedResponse.data.find(
(accountBalances) => accountBalances.address === publicKey,
);
// The backend includes every requested address in the fan-out result, with
// is_funded=false for unfunded accounts. A missing entry is a malformed
// response — treating it as "unfunded" would render (and cache) a funded
// wallet as empty.
if (!account) {
captureException(
`v2 balances response is missing the requested account - ${status}: ${redactErrorBody(
body,
)}`,
);
throw new Error(
`v2 balances response is missing the requested account ${publicKey}`,
);
}
// v2 takes account addresses only, so the locally saved custom-token
// contract IDs the v1 path sent as `contract_ids` hints are merged in here
// instead. Skipped for an unfunded account: the not-funded UI renders in
// place of balances, so resolving tokens would only burn requests.
const mappedBalances = mapAccountBalancesV2(account);
const mergedBalances = account.is_funded
? await injectLocalTokenBalances({
accountBalances: mappedBalances,
backendTokenIds: new Set(
(account.balances || []).map((balance) => balance.token_id),
),
localTokenIds: await getTokenIds({
activePublicKey: publicKey,
network: networkDetails.network as NETWORKS,
}),
networkPassphrase: networkDetails.networkPassphrase,
fetchTokenDetails: (contractId) =>
getTokenDetails({
contractId,
publicKey,
networkDetails,
shouldFetchBalance: true,
}),
})
: mappedBalances;
// The v2 response has no Blockaid data yet — replicate the v1 backend's
// scan-and-merge client-side so both paths return the same payload. Runs
// after the merge so locally added tokens are scanned too, as they were on
// v1.
return await addBlockaidScanResults(
mergedBalances,
networkDetails,
shouldSkipScan,
);
};
export const getTokenPrices = async (
tokens: string[],
networkDetails: NetworkDetails,
// Required, not defaulted: callers must thread the `use_token_prices_v2`
// feature flag so Amplitude can roll back to the v1 endpoint without a
// release. A default silently opts new callers into v2 and defeats the
// kill switch.
useV2: boolean,
// Cancels the request when the caller no longer needs the answer (e.g. the
// confirmation price snapshot's terminal-status deadline). A true network
// abort on the v1 path; the v2 request runs in the background service
// worker across a message boundary the signal cannot cross, so there it
// only skips a not-yet-sent request and rejects a no-longer-wanted result.
signal?: AbortSignal,
): Promise<ApiTokenPrices> => {
// NOTE: API does not accept LP IDs or custom tokens
const filteredTokens = tokens.filter((tokenId) => {
const asset = getAssetFromCanonical(tokenId);
return !tokenId.includes(":lp") && !isContractId(asset.issuer);
});
const requestBody = JSON.stringify({ tokens: filteredTokens });
// The v2 token-prices endpoint is a freighter-backend-v2 call, so it goes
// through the background chokepoint (callBackendV2), which attaches the
// per-request JWT (#2879). token-prices is only ever fetched from an unlocked
// wallet (a locked wallet shows the login screen), so this request always
// carries the JWT. The v1 path below is the legacy indexer, a direct fetch.
if (useV2) {
// The v2 token-prices endpoint only supports pubnet and testnet. Derive the
// price network from the passphrase rather than networkDetails.network so
// that custom networks sharing the pubnet/testnet passphrase (stored as
// STANDALONE) still resolve to the correct supported network. Anything else
// (Futurenet, custom passphrases) is skipped to avoid a guaranteed error and
// Sentry noise.
const priceNetwork =
PASSPHRASE_TO_PRICE_NETWORK[networkDetails.networkPassphrase];
if (!priceNetwork) {
return {};
}
// Nothing priceable left after filtering, so skip the request rather than
// POST an empty tokens array and risk a 4xx that surfaces as an error.
if (!filteredTokens.length) {
return {};
}
if (signal?.aborted) {
throw new DOMException("token-prices request aborted", "AbortError");
}
// Query lives in the path so callBackendV2 signs the JWT's methodAndPath
// over the server's full request-target (path + query) — see #2879.
const { status, body } = await fetchBackendV2({
method: "POST",
path: `/token-prices?network=${priceNetwork}`,
body: requestBody,
});
// The background request cannot be cancelled mid-flight (see `signal`
// param doc); reject a result nobody wants instead of returning it.
if (signal?.aborted) {
throw new DOMException("token-prices request aborted", "AbortError");
}
// Mirror getDiscoverData: a 200 without a `data` payload is still a
// failure — returning undefined would violate the Promise<ApiTokenPrices>
// contract (the caller's try/catch only handles throws, not bad returns).
const parsed = body as { data?: ApiTokenPrices };
if (status !== 200 || !parsed?.data) {
const _err = JSON.stringify(body);
captureException(
`Failed to fetch token prices - ${status}: ${redactErrorBody(body)}`,
);
throw new Error(_err);
}
return parsed.data;
}
// v1 (legacy) path — direct fetch to the v1 indexer, not a backend-v2 call.
const url = new URL(`${INDEXER_URL}/token-prices`);
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: requestBody,
signal,
};
const response = await fetch(url.href, options);
const parsedResponse = (await response.json()) as { data: ApiTokenPrices };
if (!response.ok) {
const _err = JSON.stringify(parsedResponse);
captureException(
`Failed to fetch token prices - ${response.status}: ${response.statusText}`,
);
throw new Error(_err);
}
return parsedResponse.data;
};
export const getDiscoverData = async (): Promise<DiscoverData> => {
const { status, body } = await fetchBackendV2({
method: "GET",
path: "/protocols",
});
const parsed = body as {
data?: {
protocols: {
description: string;
icon_url: string;
name: string;
website_url: string;
tags: string[];
is_blacklisted: boolean;
background_url?: string;
is_trending: boolean;
}[];
};
};
if (status !== 200 || !parsed?.data) {
const _err = JSON.stringify(parsed);
captureException(`Failed to fetch discover entries - ${status}`);
throw new Error(_err);
}
return parsed.data.protocols.map((entry) => ({
description: entry.description,
iconUrl: entry.icon_url,
name: entry.name,
websiteUrl: entry.website_url,
tags: entry.tags,
isBlacklisted: entry.is_blacklisted,
backgroundUrl: entry.background_url,
isTrending: entry.is_trending,
}));
};
export const getSorobanTokenBalance = async (
server: SorobanRpc.Server,
contractId: string,
txBuilders: {
// need a builder per operation, Soroban currently has single op transactions
balance: TransactionBuilder;
name: TransactionBuilder;
decimals: TransactionBuilder;
symbol: TransactionBuilder;
},
balanceParams: xdr.ScVal[],
) => {
// Right now we can only have 1 operation per TX in Soroban
// for now we need to do 4 tx simulations to show 1 user balance. :(
// TODO: figure out how to fetch ledger keys to do this more efficiently
const decimals = await getDecimals(contractId, server, txBuilders.decimals);
const name = await getName(contractId, server, txBuilders.name);
const symbol = await getSymbol(contractId, server, txBuilders.symbol);
const balance = await getBalance(
contractId,
balanceParams,
server,
txBuilders.balance,
);
return {
balance,
decimals,
name,
symbol,
};
};
export const getAccountBalancesStandalone = async ({
publicKey,
networkDetails,
isMainnet,
}: {
publicKey: string;
networkDetails: NetworkDetails;
isMainnet: boolean;
}) => {
const { network, networkUrl, networkPassphrase } = networkDetails;
let balances = {} as BalanceMap;
let isFunded = null;
let subentryCount = 0;
try {
const server = stellarSdkServer(networkUrl, networkPassphrase);
const accountSummary = await server.accounts().accountId(publicKey).call();
const displayableBalances = await makeDisplayableBalances(
accountSummary,
isMainnet,
);
const sponsor = accountSummary.sponsor
? { sponsor: accountSummary.sponsor }
: {};
const resp = {
...sponsor,
id: accountSummary.id,
subentryCount: accountSummary.subentry_count,
sponsoredCount: accountSummary.num_sponsored,
sponsoringCount: accountSummary.num_sponsoring,
inflationDestination: accountSummary.inflation_destination,
thresholds: accountSummary.thresholds,
signers: accountSummary.signers,
flags: accountSummary.flags,
sequenceNumber: accountSummary.sequence,
balances: displayableBalances,
};
balances = resp.balances;
subentryCount = resp.subentryCount;
for (let i = 0; i < Object.keys(resp.balances).length; i++) {
const k = Object.keys(resp.balances)[i];
const v = resp.balances[k];
if (v.liquidityPoolId) {
const server = stellarSdkServer(networkUrl, networkPassphrase);
const lp = await server
.liquidityPools()
.liquidityPoolId(v.liquidityPoolId)
.call();
balances[k] = {
...balances[k],
liquidityPoolId: v.liquidityPoolId,
reserves: lp.reserves,
};
}
}
isFunded = true;
} catch (e) {
console.error(e);
return {
balances,
isFunded: false,
subentryCount,
} as AccountBalancesInterface;
}
// Get token balances to combine with classic balances
const tokenIdList = await getTokenIds({
activePublicKey: publicKey,
network: network as NETWORKS,
});
const tokenBalances = {} as any;
if (tokenIdList.length) {
if (!networkDetails.sorobanRpcUrl) {
throw new SorobanRpcNotSupportedError();
}
const server = buildSorobanServer(
networkDetails.sorobanRpcUrl,
networkDetails.networkPassphrase,
);
const params = [new Address(publicKey).toScVal()];
for (let i = 0; i < tokenIdList.length; i += 1) {
const tokenId = tokenIdList[i];
/*
Right now, Soroban transactions only support 1 operation per tx
so we need a builder per value from the contract,
once/if multi-op transactions are supported this can send
1 tx with an operation for each value.
*/
try {
const { balance, symbol, ...rest } = await getSorobanTokenBalance(
server,
tokenId,
{
balance: await getNewTxBuilder(publicKey, networkDetails, server),
name: await getNewTxBuilder(publicKey, networkDetails, server),