@pioneer-platform/pioneer-sdk 8.14.1 → 8.15.3

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.
package/dist/index.es.js CHANGED
@@ -15,6 +15,16 @@ var __toESM = (mod, isNodeMode, target) => {
15
15
  return to;
16
16
  };
17
17
  var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
18
+ var __export = (target, all) => {
19
+ for (var name in all)
20
+ __defProp(target, name, {
21
+ get: all[name],
22
+ enumerable: true,
23
+ configurable: true,
24
+ set: (newValue) => all[name] = () => newValue
25
+ });
26
+ };
27
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
18
28
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
19
29
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
20
30
  }) : x)(function(x) {
@@ -219,6 +229,545 @@ var require_split = __commonJS((exports, module) => {
219
229
  };
220
230
  });
221
231
 
232
+ // src/charts/utils.ts
233
+ import { assetData } from "@pioneer-platform/pioneer-discovery";
234
+ function hydrateAssetData(caip) {
235
+ return assetData[caip] || assetData[caip.toLowerCase()];
236
+ }
237
+ function checkDuplicateBalance(balances, caip, pubkey, validator) {
238
+ return balances.some((b2) => b2.caip === caip && b2.pubkey === pubkey && (!validator || b2.validator === validator));
239
+ }
240
+ function createBalanceIdentifier(caip, pubkey) {
241
+ return `${caip}:${pubkey}`;
242
+ }
243
+ var init_utils = () => {
244
+ };
245
+
246
+ // src/charts/custom-tokens.ts
247
+ async function fetchCustomTokens(params, balances) {
248
+ const { pioneer, pubkeys, blockchains, context } = params;
249
+ console.log(tag, "Fetching custom tokens...");
250
+ const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
251
+ const primaryAddress = evmPubkey?.address || evmPubkey?.master;
252
+ if (!primaryAddress) {
253
+ console.log(tag, "No EVM address found, skipping custom tokens");
254
+ return;
255
+ }
256
+ console.log(tag, "Using EVM address for custom tokens:", primaryAddress);
257
+ const supportedNetworks = blockchains.filter((net) => net.startsWith("eip155:"));
258
+ if (supportedNetworks.length === 0) {
259
+ console.log(tag, "No EVM networks for custom tokens");
260
+ return;
261
+ }
262
+ console.log(tag, `Checking custom tokens on ${supportedNetworks.length} networks`);
263
+ for (const networkId of supportedNetworks) {
264
+ try {
265
+ const response = await pioneer.GetCustomTokens({ networkId, userAddress: primaryAddress });
266
+ const customTokens = response?.data?.tokens || [];
267
+ console.log(tag, `Found ${customTokens.length} custom tokens on ${networkId}`);
268
+ for (const token of customTokens) {
269
+ const chartBalance = processCustomToken(token, primaryAddress, context, blockchains);
270
+ if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
271
+ balances.push(chartBalance);
272
+ console.log(tag, `Added custom token: ${chartBalance.symbol} = ${chartBalance.balance}`);
273
+ }
274
+ }
275
+ } catch (error) {
276
+ console.error(tag, `Error fetching custom tokens for ${networkId}:`, error.message);
277
+ }
278
+ }
279
+ console.log(tag, `Custom tokens complete. Total balances: ${balances.length}`);
280
+ }
281
+ function processCustomToken(token, primaryAddress, context, blockchains) {
282
+ if (!token.assetCaip || !token.networkId) {
283
+ return null;
284
+ }
285
+ let extractedNetworkId = token.networkId;
286
+ if (token.assetCaip.includes("/denom:")) {
287
+ const parts = token.assetCaip.split("/denom:");
288
+ if (parts.length > 0) {
289
+ extractedNetworkId = parts[0];
290
+ }
291
+ } else if (token.networkId && token.networkId.includes("/")) {
292
+ extractedNetworkId = token.networkId.split("/")[0];
293
+ }
294
+ const isEip155 = extractedNetworkId.startsWith("eip155:");
295
+ if (!isEip155 && !blockchains.includes(extractedNetworkId)) {
296
+ return null;
297
+ }
298
+ const tokenAssetInfo = hydrateAssetData(token.assetCaip);
299
+ const tokenPubkey = token.pubkey || primaryAddress;
300
+ const chartBalance = {
301
+ context,
302
+ chart: "pioneer",
303
+ contextType: context.split(":")[0],
304
+ name: tokenAssetInfo?.name || token.token?.name || "Unknown Custom Token",
305
+ caip: token.assetCaip,
306
+ icon: tokenAssetInfo?.icon || token.token?.icon || "",
307
+ pubkey: tokenPubkey,
308
+ ticker: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
309
+ ref: `${context}${token.assetCaip}`,
310
+ identifier: createBalanceIdentifier(token.assetCaip, tokenPubkey),
311
+ networkId: extractedNetworkId,
312
+ symbol: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
313
+ type: tokenAssetInfo?.type || "erc20",
314
+ token: true,
315
+ decimal: tokenAssetInfo?.decimal || token.token?.decimal,
316
+ balance: token.token?.balance?.toString() || "0",
317
+ priceUsd: token.token?.price || 0,
318
+ valueUsd: token.token?.balanceUSD || 0,
319
+ updated: new Date().getTime()
320
+ };
321
+ return chartBalance;
322
+ }
323
+ var tag = "| charts-custom-tokens |";
324
+ var init_custom_tokens = __esm(() => {
325
+ init_utils();
326
+ });
327
+
328
+ // src/charts/evm.ts
329
+ async function getEvmCharts(params) {
330
+ const { blockchains, pioneer, pubkeys, context } = params;
331
+ const balances = [];
332
+ const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
333
+ const primaryAddress = evmPubkey?.address || evmPubkey?.master;
334
+ console.log(tag2, "Total pubkeys available:", pubkeys.length);
335
+ console.log(tag2, "Blockchains to process:", blockchains);
336
+ const pubkeysForBatch = [];
337
+ for (const pubkey of pubkeys) {
338
+ const address = pubkey.address || pubkey.master || pubkey.pubkey;
339
+ if (!address)
340
+ continue;
341
+ const supportedNetworks = pubkey.networks || [];
342
+ for (const blockchain of blockchains) {
343
+ const supportsNetwork = supportedNetworks.some((net) => net === blockchain || net.endsWith(":*") && blockchain.startsWith(net.replace(":*", ":")));
344
+ if (supportsNetwork) {
345
+ let caip;
346
+ if (blockchain.startsWith("eip155:")) {
347
+ caip = `${blockchain}/slip44:60`;
348
+ } else {
349
+ caip = `${blockchain}/slip44:0`;
350
+ }
351
+ pubkeysForBatch.push({
352
+ pubkey: address,
353
+ caip
354
+ });
355
+ }
356
+ }
357
+ }
358
+ console.log(tag2, `Built ${pubkeysForBatch.length} pubkey-chain combinations for batch request`);
359
+ if (pubkeysForBatch.length === 0) {
360
+ console.log(tag2, "No pubkeys to query, skipping portfolio lookup");
361
+ return balances;
362
+ }
363
+ if (primaryAddress) {
364
+ await fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context);
365
+ }
366
+ await fetchCustomTokens({ blockchains, pioneer, pubkeys, context }, balances);
367
+ try {
368
+ console.log(tag2, `Calling GetPortfolio with ${pubkeysForBatch.length} pubkeys (batch + non-blocking)`);
369
+ let portfolio = await pioneer.GetPortfolio({
370
+ pubkeys: pubkeysForBatch
371
+ });
372
+ portfolio = portfolio.data?.data || portfolio.data;
373
+ if (!portfolio || !portfolio.balances) {
374
+ console.error(tag2, "No portfolio.balances found:", portfolio);
375
+ return balances;
376
+ }
377
+ console.log(tag2, `Portfolio returned ${portfolio.balances.length} balances`);
378
+ let processedCount = 0;
379
+ let skippedCount = 0;
380
+ for (const balance of portfolio.balances) {
381
+ const processedBalance = processPortfolioBalance(balance, primaryAddress, context, blockchains);
382
+ if (processedBalance) {
383
+ if (!checkDuplicateBalance(balances, processedBalance.caip, processedBalance.pubkey)) {
384
+ balances.push(processedBalance);
385
+ processedCount++;
386
+ }
387
+ } else {
388
+ skippedCount++;
389
+ }
390
+ }
391
+ console.log(tag2, `Processed ${processedCount} balances, skipped ${skippedCount}`);
392
+ if (portfolio.tokens && portfolio.tokens.length > 0) {
393
+ console.log(tag2, "Processing portfolio.tokens:", portfolio.tokens.length);
394
+ for (const token of portfolio.tokens) {
395
+ const processedToken = processPortfolioToken(token, primaryAddress, context, blockchains);
396
+ if (processedToken && !checkDuplicateBalance(balances, processedToken.caip, processedToken.pubkey)) {
397
+ balances.push(processedToken);
398
+ }
399
+ }
400
+ }
401
+ console.log(tag2, `Total balances (native + tokens): ${balances.length}`);
402
+ } catch (e) {
403
+ console.error(tag2, "Error fetching portfolio:", e);
404
+ }
405
+ return balances;
406
+ }
407
+ function processPortfolioBalance(balance, primaryAddress, context, blockchains) {
408
+ if (!balance.caip) {
409
+ console.error(tag2, "No caip found for:", balance);
410
+ return null;
411
+ }
412
+ const networkId = balance.caip.split("/")[0];
413
+ const isEip155 = networkId.startsWith("eip155:");
414
+ if (!isEip155 && !blockchains.includes(networkId)) {
415
+ return null;
416
+ }
417
+ const assetInfo = hydrateAssetData(balance.caip);
418
+ const balancePubkey = balance.pubkey || primaryAddress;
419
+ const balanceType = assetInfo?.type || balance.type || "native";
420
+ const isToken = balanceType !== "native" && balance.caip.includes("/erc20:");
421
+ let calculatedPrice = balance.priceUsd || balance.price || 0;
422
+ if ((!calculatedPrice || calculatedPrice === 0) && balance.valueUsd && balance.balance) {
423
+ const balanceNum = parseFloat(balance.balance.toString());
424
+ const valueNum = parseFloat(balance.valueUsd.toString());
425
+ if (balanceNum > 0 && valueNum > 0) {
426
+ calculatedPrice = valueNum / balanceNum;
427
+ console.log(tag2, `Calculated price from value/balance: ${calculatedPrice} for ${balance.caip}`);
428
+ }
429
+ }
430
+ const chartBalance = {
431
+ context,
432
+ chart: "pioneer",
433
+ contextType: "keepkey",
434
+ name: assetInfo?.name || balance.name || "Unknown",
435
+ caip: balance.caip,
436
+ icon: assetInfo?.icon || balance.icon || "",
437
+ pubkey: balancePubkey,
438
+ ticker: assetInfo?.symbol || balance.symbol || "UNK",
439
+ ref: `${context}${balance.caip}`,
440
+ identifier: createBalanceIdentifier(balance.caip, balancePubkey),
441
+ networkId,
442
+ chain: networkId,
443
+ symbol: assetInfo?.symbol || balance.symbol || "UNK",
444
+ type: balanceType,
445
+ token: isToken,
446
+ decimal: assetInfo?.decimal || balance.decimal,
447
+ balance: balance.balance.toString(),
448
+ price: calculatedPrice,
449
+ priceUsd: calculatedPrice,
450
+ valueUsd: balance.valueUsd.toString(),
451
+ updated: new Date().getTime()
452
+ };
453
+ if (balance.display) {
454
+ chartBalance.icon = ["multi", chartBalance.icon, balance.display.toString()].toString();
455
+ }
456
+ return chartBalance;
457
+ }
458
+ function processPortfolioToken(token, primaryAddress, context, blockchains) {
459
+ if (!token.assetCaip || !token.networkId) {
460
+ return null;
461
+ }
462
+ let extractedNetworkId = token.networkId;
463
+ if (token.assetCaip.includes("/denom:")) {
464
+ const parts = token.assetCaip.split("/denom:");
465
+ if (parts.length > 0) {
466
+ extractedNetworkId = parts[0];
467
+ }
468
+ } else if (token.networkId && token.networkId.includes("/")) {
469
+ extractedNetworkId = token.networkId.split("/")[0];
470
+ }
471
+ const isEip155 = extractedNetworkId.startsWith("eip155:");
472
+ if (!isEip155 && !blockchains.includes(extractedNetworkId)) {
473
+ return null;
474
+ }
475
+ const tokenAssetInfo = hydrateAssetData(token.assetCaip);
476
+ const tokenPubkey = token.pubkey || primaryAddress;
477
+ const chartBalance = {
478
+ context,
479
+ chart: "pioneer",
480
+ contextType: context.split(":")[0],
481
+ name: tokenAssetInfo?.name || token.token?.coingeckoId || token.token?.name || "Unknown",
482
+ caip: token.assetCaip,
483
+ icon: tokenAssetInfo?.icon || token.token?.icon || "",
484
+ pubkey: tokenPubkey,
485
+ ticker: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
486
+ ref: `${context}${token.assetCaip}`,
487
+ identifier: createBalanceIdentifier(token.assetCaip, tokenPubkey),
488
+ networkId: extractedNetworkId,
489
+ symbol: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
490
+ type: tokenAssetInfo?.type || "token",
491
+ token: true,
492
+ decimal: tokenAssetInfo?.decimal || token.token?.decimal,
493
+ balance: token.token?.balance?.toString() || "0",
494
+ priceUsd: token.token?.price || 0,
495
+ valueUsd: token.token?.balanceUSD || 0,
496
+ updated: new Date().getTime()
497
+ };
498
+ return chartBalance;
499
+ }
500
+ async function fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context) {
501
+ console.log(tag2, "Fetching stable coins for redundancy...");
502
+ try {
503
+ const fastFlag = typeof process !== "undefined" && process.env && process.env.PIONEER_FAST === "1";
504
+ const isTestContext = typeof context === "string" && /test|e2e/i.test(context);
505
+ if (fastFlag || isTestContext) {
506
+ console.log(tag2, "Fast mode detected (test/e2e). Skipping stable coin redundancy.");
507
+ return;
508
+ }
509
+ } catch (_2) {
510
+ }
511
+ const supportedNetworks = ["eip155:1", "eip155:137", "eip155:8453", "eip155:56"];
512
+ const networksToCheck = blockchains.filter((net) => supportedNetworks.includes(net));
513
+ if (networksToCheck.length === 0) {
514
+ console.log(tag2, "No supported networks for stable coins");
515
+ return;
516
+ }
517
+ console.log(tag2, `Checking stable coins on ${networksToCheck.length} networks`);
518
+ const withTimeout2 = (p, ms) => {
519
+ return new Promise((resolve, reject) => {
520
+ const t = setTimeout(() => reject(new Error(`timeout ${ms}ms`)), ms);
521
+ p.then((v2) => {
522
+ clearTimeout(t);
523
+ resolve(v2);
524
+ }).catch((e) => {
525
+ clearTimeout(t);
526
+ reject(e);
527
+ });
528
+ });
529
+ };
530
+ const results = await Promise.allSettled(networksToCheck.map(async (networkId) => {
531
+ try {
532
+ const response = await withTimeout2(pioneer.GetStableCoins({ networkId, address: primaryAddress }), 2000);
533
+ const stableCoins = response?.data?.tokens || [];
534
+ console.log(tag2, `Found ${stableCoins.length} stable coins on ${networkId}`);
535
+ for (const token of stableCoins) {
536
+ const chartBalance = processPortfolioToken(token, primaryAddress, context, blockchains);
537
+ if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
538
+ balances.push(chartBalance);
539
+ console.log(tag2, `Added stable coin: ${chartBalance.symbol} = ${chartBalance.balance}`);
540
+ }
541
+ }
542
+ } catch (error) {
543
+ console.error(tag2, `Error fetching stable coins for ${networkId}:`, error?.message || error);
544
+ }
545
+ }));
546
+ const failures = results.filter((r) => r.status === "rejected").length;
547
+ if (failures > 0)
548
+ console.log(tag2, `Stable coin fetch had ${failures} failures (non-blocking)`);
549
+ console.log(tag2, `Stable coin redundancy complete. Total balances: ${balances.length}`);
550
+ }
551
+ var tag2 = "| charts-evm |";
552
+ var init_evm = __esm(() => {
553
+ init_utils();
554
+ init_custom_tokens();
555
+ });
556
+
557
+ // src/charts/maya.ts
558
+ async function getMayaCharts(params, existingBalances) {
559
+ const { blockchains, pioneer, pubkeys, context } = params;
560
+ const balances = [];
561
+ try {
562
+ const mayaPubkey = pubkeys.find((p) => p.networks && Array.isArray(p.networks) && p.networks.includes("cosmos:mayachain-mainnet-v1"));
563
+ if (!mayaPubkey || !mayaPubkey.address) {
564
+ console.log(tag3, "No MAYA pubkey found, skipping MAYA token fetch");
565
+ return balances;
566
+ }
567
+ if (!blockchains.includes("cosmos:mayachain-mainnet-v1")) {
568
+ console.log(tag3, "MAYA network not in blockchains list, skipping MAYA token fetch");
569
+ return balances;
570
+ }
571
+ const hasMayaToken = existingBalances.some((b2) => b2.caip === "cosmos:mayachain-mainnet-v1/denom:maya");
572
+ if (hasMayaToken) {
573
+ console.log(tag3, "MAYA token already exists in balances, skipping");
574
+ return balances;
575
+ }
576
+ console.log(tag3, "MAYA token not found in portfolio, fetching separately...");
577
+ console.log(tag3, "MAYA pubkey address:", mayaPubkey.address);
578
+ const mayaBalanceResponse = await pioneer.GetPortfolioBalances({
579
+ pubkeys: [
580
+ {
581
+ caip: "cosmos:mayachain-mainnet-v1/denom:maya",
582
+ pubkey: mayaPubkey.address
583
+ }
584
+ ]
585
+ });
586
+ console.log(tag3, "MAYA balance response:", JSON.stringify(mayaBalanceResponse?.data, null, 2));
587
+ if (!mayaBalanceResponse?.data || mayaBalanceResponse.data.length === 0) {
588
+ console.log(tag3, "No MAYA token balance returned from GetPortfolioBalances API");
589
+ return balances;
590
+ }
591
+ console.log(tag3, "Found MAYA token balances:", mayaBalanceResponse.data.length);
592
+ for (const mayaBalance of mayaBalanceResponse.data) {
593
+ if (mayaBalance.caip !== "cosmos:mayachain-mainnet-v1/denom:maya") {
594
+ console.log(tag3, "Unexpected balance in MAYA response:", mayaBalance);
595
+ continue;
596
+ }
597
+ const mayaAssetInfo = hydrateAssetData(mayaBalance.caip);
598
+ const isToken = mayaBalance.caip.includes("/denom:") && !mayaBalance.caip.endsWith("/denom:cacao");
599
+ const mayaTokenBalance = {
600
+ context,
601
+ chart: "pioneer",
602
+ contextType: context.split(":")[0],
603
+ name: mayaAssetInfo?.name || "Maya Token",
604
+ caip: mayaBalance.caip,
605
+ icon: mayaAssetInfo?.icon || "https://pioneers.dev/coins/maya.png",
606
+ pubkey: mayaPubkey.address,
607
+ ticker: mayaAssetInfo?.symbol || "MAYA",
608
+ ref: `${context}${mayaBalance.caip}`,
609
+ identifier: createBalanceIdentifier(mayaBalance.caip, mayaPubkey.address),
610
+ networkId: "cosmos:mayachain-mainnet-v1",
611
+ symbol: mayaAssetInfo?.symbol || "MAYA",
612
+ type: mayaAssetInfo?.type || "token",
613
+ token: isToken,
614
+ decimal: mayaAssetInfo?.decimal,
615
+ balance: mayaBalance.balance?.toString() || "0",
616
+ priceUsd: parseFloat(mayaBalance.priceUsd) || 0,
617
+ valueUsd: parseFloat(mayaBalance.valueUsd) || 0,
618
+ updated: new Date().getTime()
619
+ };
620
+ console.log(tag3, "Adding MAYA token to balances:", mayaTokenBalance);
621
+ balances.push(mayaTokenBalance);
622
+ }
623
+ } catch (mayaError) {
624
+ console.error(tag3, "Error fetching MAYA token balance:", mayaError);
625
+ }
626
+ return balances;
627
+ }
628
+ var tag3 = "| charts-maya |";
629
+ var init_maya = __esm(() => {
630
+ init_utils();
631
+ });
632
+
633
+ // src/charts/cosmos-staking.ts
634
+ async function getCosmosStakingCharts(params) {
635
+ const { blockchains, pioneer, pubkeys, context } = params;
636
+ const balances = [];
637
+ try {
638
+ try {
639
+ const fastFlag = typeof process !== "undefined" && process.env && process.env.PIONEER_FAST === "1";
640
+ const isTestContext = typeof context === "string" && /test|e2e/i.test(context);
641
+ if (fastFlag || isTestContext) {
642
+ console.log(tag4, "Fast mode detected (test/e2e). Skipping cosmos staking fetch.");
643
+ return balances;
644
+ }
645
+ } catch (_2) {
646
+ }
647
+ console.log(tag4, "Adding Cosmos staking positions to charts...");
648
+ const cosmosPubkeys = pubkeys.filter((p) => p.networks && Array.isArray(p.networks) && p.networks.some((n) => n.includes("cosmos:cosmoshub") || n.includes("cosmos:osmosis")));
649
+ if (cosmosPubkeys.length === 0) {
650
+ console.log(tag4, "No cosmos pubkeys found for staking positions");
651
+ return balances;
652
+ }
653
+ console.log(tag4, "Found cosmos pubkeys for staking:", cosmosPubkeys.length);
654
+ await Promise.allSettled(cosmosPubkeys.map(async (cosmosPubkey) => {
655
+ if (!cosmosPubkey.address)
656
+ return;
657
+ const cosmosNetworks = cosmosPubkey.networks.filter((n) => n.includes("cosmos:cosmoshub") || n.includes("cosmos:osmosis"));
658
+ await Promise.allSettled(cosmosNetworks.filter((networkId) => blockchains.includes(networkId)).map(async (networkId) => {
659
+ await fetchStakingPositionsForNetwork(networkId, cosmosPubkey.address, context, pioneer, balances);
660
+ }));
661
+ }));
662
+ } catch (e) {
663
+ console.error(tag4, "Error adding cosmos staking positions:", e);
664
+ }
665
+ return balances;
666
+ }
667
+ async function fetchStakingPositionsForNetwork(networkId, address, context, pioneer, balances) {
668
+ try {
669
+ console.log(tag4, `Fetching staking positions for ${address} on ${networkId}...`);
670
+ let network;
671
+ if (networkId === "cosmos:cosmoshub-4") {
672
+ network = "cosmos";
673
+ } else if (networkId === "cosmos:osmosis-1") {
674
+ network = "osmosis";
675
+ } else {
676
+ console.error(tag4, `Unsupported networkId for staking: ${networkId}`);
677
+ return;
678
+ }
679
+ const stakingResponse = await pioneer.GetStakingPositions({
680
+ network,
681
+ address
682
+ });
683
+ if (!stakingResponse?.data || !Array.isArray(stakingResponse.data)) {
684
+ console.log(tag4, `No staking positions found for ${address} on ${networkId}`);
685
+ return;
686
+ }
687
+ console.log(tag4, `Found ${stakingResponse.data.length} staking positions for ${networkId}`);
688
+ for (const position of stakingResponse.data) {
689
+ const processedPosition = processStakingPosition(position, address, context, networkId);
690
+ if (processedPosition && !checkDuplicateBalance(balances, processedPosition.caip, processedPosition.pubkey, processedPosition.validator)) {
691
+ balances.push(processedPosition);
692
+ console.log(tag4, `Added ${position.type} position:`, {
693
+ balance: processedPosition.balance,
694
+ ticker: processedPosition.ticker,
695
+ valueUsd: processedPosition.valueUsd,
696
+ validator: processedPosition.validator
697
+ });
698
+ }
699
+ }
700
+ } catch (stakingError) {
701
+ console.error(tag4, `Error fetching staking positions for ${address} on ${networkId}:`, stakingError);
702
+ }
703
+ }
704
+ function processStakingPosition(position, address, context, networkId) {
705
+ if (!position.balance || position.balance <= 0 || !position.caip) {
706
+ return null;
707
+ }
708
+ const stakingAssetInfo = hydrateAssetData(position.caip);
709
+ const stakingBalance = {
710
+ context,
711
+ chart: "staking",
712
+ contextType: context.split(":")[0],
713
+ name: stakingAssetInfo?.name || position.name || `${position.type} Position`,
714
+ caip: position.caip,
715
+ icon: stakingAssetInfo?.icon || position.icon || "",
716
+ pubkey: address,
717
+ ticker: stakingAssetInfo?.symbol || position.ticker || position.symbol || "UNK",
718
+ ref: `${context}${position.caip}`,
719
+ identifier: createBalanceIdentifier(position.caip, address),
720
+ networkId,
721
+ symbol: stakingAssetInfo?.symbol || position.symbol || position.ticker || "UNK",
722
+ type: stakingAssetInfo?.type || position.type || "staking",
723
+ token: false,
724
+ decimal: stakingAssetInfo?.decimal,
725
+ balance: position.balance.toString(),
726
+ priceUsd: position.priceUsd || 0,
727
+ valueUsd: position.valueUsd || position.balance * (position.priceUsd || 0),
728
+ status: position.status || "active",
729
+ validator: position.validatorAddress || position.validator || "",
730
+ updated: new Date().getTime()
731
+ };
732
+ return stakingBalance;
733
+ }
734
+ var tag4 = "| charts-cosmos-staking |";
735
+ var init_cosmos_staking = __esm(() => {
736
+ init_utils();
737
+ });
738
+ // src/charts/index.ts
739
+ var exports_charts = {};
740
+ __export(exports_charts, {
741
+ getCharts: () => getCharts
742
+ });
743
+ var tag5 = "| getCharts |", getCharts = async (blockchains, pioneer, pubkeys, context) => {
744
+ try {
745
+ const balances = [];
746
+ console.log(tag5, "init");
747
+ const params = {
748
+ blockchains,
749
+ pioneer,
750
+ pubkeys,
751
+ context
752
+ };
753
+ const evmBalances = await getEvmCharts(params);
754
+ balances.push(...evmBalances);
755
+ const mayaBalances = await getMayaCharts(params, balances);
756
+ balances.push(...mayaBalances);
757
+ const stakingBalances = await getCosmosStakingCharts(params);
758
+ balances.push(...stakingBalances);
759
+ return balances;
760
+ } catch (error) {
761
+ console.error(tag5, "Error processing charts:", error);
762
+ throw error;
763
+ }
764
+ };
765
+ var init_charts = __esm(() => {
766
+ init_evm();
767
+ init_maya();
768
+ init_cosmos_staking();
769
+ });
770
+
222
771
  // src/index.ts
223
772
  import { KeepKeySdk } from "@keepkey/keepkey-sdk";
224
773
  import { caipToNetworkId as caipToNetworkId7, networkIdToCaip as networkIdToCaip2 } from "@pioneer-platform/pioneer-caip";
@@ -367,7 +916,7 @@ class Pioneer {
367
916
 
368
917
  // src/index.ts
369
918
  import { addressNListToBIP32 as addressNListToBIP322, getPaths } from "@pioneer-platform/pioneer-coins";
370
- import { assetData } from "@pioneer-platform/pioneer-discovery";
919
+ import { assetData as assetData2 } from "@pioneer-platform/pioneer-discovery";
371
920
  import { Events } from "@pioneer-platform/pioneer-events";
372
921
 
373
922
  // node:events
@@ -1617,9 +2166,16 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
1617
2166
  accountInfo = accountInfo.data;
1618
2167
  const sequence = accountInfo.Sequence.toString();
1619
2168
  const ledgerIndexCurrent = parseInt(accountInfo.ledger_index_current);
1620
- let desttag = memo;
1621
- if (!desttag || /^\s*$/.test(desttag) || isNaN(desttag)) {
1622
- desttag = "0";
2169
+ let desttag = undefined;
2170
+ if (memo && memo.trim() !== "") {
2171
+ if (!/^\d+$/.test(memo.trim())) {
2172
+ throw new Error(`XRP destination tag must be numeric. Got: "${memo}"`);
2173
+ }
2174
+ const tagNum = parseInt(memo.trim(), 10);
2175
+ if (isNaN(tagNum) || tagNum < 0 || tagNum > 4294967295) {
2176
+ throw new Error(`XRP destination tag must be 0-4294967295. Got: ${memo}`);
2177
+ }
2178
+ desttag = tagNum.toString();
1623
2179
  }
1624
2180
  if (isMax) {
1625
2181
  amount = Number(accountInfo.Balance) - 1e6 - 1;
@@ -1628,6 +2184,22 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
1628
2184
  amount = amount * 1e6;
1629
2185
  amount = amount.toString();
1630
2186
  }
2187
+ const msg = {
2188
+ type: "ripple-sdk/MsgSend",
2189
+ value: {
2190
+ amount: [
2191
+ {
2192
+ amount,
2193
+ denom: "drop"
2194
+ }
2195
+ ],
2196
+ from_address: fromAddress,
2197
+ to_address: to
2198
+ }
2199
+ };
2200
+ if (desttag !== undefined) {
2201
+ msg.DestinationTag = desttag;
2202
+ }
1631
2203
  let tx = {
1632
2204
  type: "auth/StdTx",
1633
2205
  value: {
@@ -1641,36 +2213,24 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
1641
2213
  gas: "28000"
1642
2214
  },
1643
2215
  memo: memo || "",
1644
- msg: [
1645
- {
1646
- type: "ripple-sdk/MsgSend",
1647
- DestinationTag: desttag,
1648
- value: {
1649
- amount: [
1650
- {
1651
- amount,
1652
- denom: "drop"
1653
- }
1654
- ],
1655
- from_address: fromAddress,
1656
- to_address: to
1657
- }
1658
- }
1659
- ],
2216
+ msg: [msg],
1660
2217
  signatures: null
1661
2218
  }
1662
2219
  };
2220
+ const payment = {
2221
+ amount,
2222
+ destination: to
2223
+ };
2224
+ if (desttag !== undefined) {
2225
+ payment.destinationTag = desttag;
2226
+ }
1663
2227
  let unsignedTx = {
1664
2228
  addressNList: [2147483692, 2147483792, 2147483648, 0, 0],
1665
2229
  tx,
1666
2230
  flags: undefined,
1667
2231
  lastLedgerSequence: (ledgerIndexCurrent + 1000).toString(),
1668
2232
  sequence: sequence || "0",
1669
- payment: {
1670
- amount,
1671
- destination: to,
1672
- destinationTag: desttag
1673
- }
2233
+ payment
1674
2234
  };
1675
2235
  return unsignedTx;
1676
2236
  } catch (error) {
@@ -2945,6 +3505,10 @@ async function getFees(pioneer, networkId) {
2945
3505
  console.log(tag, "Using hardcoded fees for Cosmos network:", networkId);
2946
3506
  return getCosmosFees(networkId);
2947
3507
  }
3508
+ if (networkId === "ripple:4109c6f2045fc7eff4cde8f9905d19c2") {
3509
+ console.log(tag, "Using hardcoded fees for Ripple: 0.00001 XRP");
3510
+ return getRippleFees(networkId);
3511
+ }
2948
3512
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
2949
3513
  console.log(tag, "Using hardcoded fees for Dogecoin: 10 sat/byte");
2950
3514
  return {
@@ -3271,6 +3835,39 @@ function getCosmosFees(networkId) {
3271
3835
  raw: { hardcoded: true, base: feeConfig.base, unit: feeConfig.unit, denom: feeConfig.denom }
3272
3836
  };
3273
3837
  }
3838
+ function getRippleFees(networkId) {
3839
+ const networkName = getNetworkName(networkId);
3840
+ const standardFee = "0.00001";
3841
+ return {
3842
+ slow: {
3843
+ label: "Standard",
3844
+ value: standardFee,
3845
+ unit: "XRP",
3846
+ description: `Fixed fee for ${networkName}. XRP uses a deterministic fee model.`,
3847
+ estimatedTime: "~4 seconds",
3848
+ priority: "low"
3849
+ },
3850
+ average: {
3851
+ label: "Standard",
3852
+ value: standardFee,
3853
+ unit: "XRP",
3854
+ description: `Fixed fee for ${networkName}. XRP uses a deterministic fee model.`,
3855
+ estimatedTime: "~4 seconds",
3856
+ priority: "medium"
3857
+ },
3858
+ fastest: {
3859
+ label: "Standard",
3860
+ value: standardFee,
3861
+ unit: "XRP",
3862
+ description: `Fixed fee for ${networkName}. XRP uses a deterministic fee model.`,
3863
+ estimatedTime: "~4 seconds",
3864
+ priority: "high"
3865
+ },
3866
+ networkId,
3867
+ networkType: "RIPPLE",
3868
+ raw: { hardcoded: true, fee: standardFee, unit: "XRP" }
3869
+ };
3870
+ }
3274
3871
  function getFallbackFees(networkId) {
3275
3872
  const networkType = getNetworkType(networkId);
3276
3873
  const networkName = getNetworkName(networkId);
@@ -3669,7 +4266,7 @@ class SDK {
3669
4266
  this.appIcon = config.appIcon || "https://pioneers.dev/coins/keepkey.png";
3670
4267
  this.spec = spec || config.spec || "https://api.keepkey.info/spec/swagger";
3671
4268
  this.wss = config.wss || "wss://api.keepkey.info";
3672
- this.assets = assetData;
4269
+ this.assets = assetData2;
3673
4270
  this.assetsMap = new Map;
3674
4271
  this.username = config.username;
3675
4272
  this.queryKey = config.queryKey;
@@ -3720,9 +4317,9 @@ class SDK {
3720
4317
  fallbackToRemote: true
3721
4318
  }) : null;
3722
4319
  this.pairWallet = async (options) => {
3723
- const tag = TAG9 + " | pairWallet | ";
4320
+ const tag6 = TAG9 + " | pairWallet | ";
3724
4321
  if (this.viewOnlyMode || this.skipDevicePairing) {
3725
- console.log(tag, "\uD83D\uDC41️ [VIEW-ONLY] Skipping device pairing");
4322
+ console.log(tag6, "\uD83D\uDC41️ [VIEW-ONLY] Skipping device pairing");
3726
4323
  return {
3727
4324
  success: false,
3728
4325
  reason: "view-only-mode",
@@ -3763,7 +4360,7 @@ class SDK {
3763
4360
  return true;
3764
4361
  };
3765
4362
  this.setPubkeys = (newPubkeys) => {
3766
- const tag = `${TAG9} | setPubkeys | `;
4363
+ const tag6 = `${TAG9} | setPubkeys | `;
3767
4364
  this.pubkeys = [];
3768
4365
  this.pubkeySet.clear();
3769
4366
  let added = 0;
@@ -3789,7 +4386,7 @@ class SDK {
3789
4386
  return !!this.keepkeyEndpoint && this.keepkeyEndpoint.isAvailable;
3790
4387
  };
3791
4388
  this.getUnifiedPortfolio = async function() {
3792
- const tag = `${TAG9} | getUnifiedPortfolio | `;
4389
+ const tag6 = `${TAG9} | getUnifiedPortfolio | `;
3793
4390
  try {
3794
4391
  const startTime = performance.now();
3795
4392
  try {
@@ -3800,17 +4397,17 @@ class SDK {
3800
4397
  signal: AbortSignal.timeout(2000)
3801
4398
  });
3802
4399
  if (!portfolioResponse.ok) {
3803
- console.warn(tag, "Portfolio endpoint returned", portfolioResponse.status);
4400
+ console.warn(tag6, "Portfolio endpoint returned", portfolioResponse.status);
3804
4401
  return null;
3805
4402
  }
3806
4403
  const portfolioData = await portfolioResponse.json();
3807
4404
  const loadTime = performance.now() - startTime;
3808
4405
  if (!portfolioData.success) {
3809
- console.warn(tag, "Portfolio API returned success=false");
4406
+ console.warn(tag6, "Portfolio API returned success=false");
3810
4407
  return null;
3811
4408
  }
3812
4409
  if (portfolioData.totalValueUsd === 0 || !portfolioData.totalValueUsd) {
3813
- console.warn(tag, "Portfolio value is $0.00 - may need device connection or sync");
4410
+ console.warn(tag6, "Portfolio value is $0.00 - may need device connection or sync");
3814
4411
  return null;
3815
4412
  }
3816
4413
  let allBalances = [];
@@ -3897,14 +4494,14 @@ class SDK {
3897
4494
  };
3898
4495
  } catch (fetchError) {
3899
4496
  if (fetchError.name === "AbortError") {
3900
- console.log(tag, "Unified portfolio request timed out (this is normal if vault not running)");
4497
+ console.log(tag6, "Unified portfolio request timed out (this is normal if vault not running)");
3901
4498
  } else {
3902
- console.log(tag, "Failed to fetch unified portfolio:", fetchError.message);
4499
+ console.log(tag6, "Failed to fetch unified portfolio:", fetchError.message);
3903
4500
  }
3904
4501
  return null;
3905
4502
  }
3906
4503
  } catch (e) {
3907
- console.error(tag, "Error:", e);
4504
+ console.error(tag6, "Error:", e);
3908
4505
  return null;
3909
4506
  }
3910
4507
  };
@@ -3915,7 +4512,7 @@ class SDK {
3915
4512
  return this.syncState.isSynced;
3916
4513
  };
3917
4514
  this.init = async function(walletsVerbose, setup) {
3918
- const tag = `${TAG9} | init | `;
4515
+ const tag6 = `${TAG9} | init | `;
3919
4516
  try {
3920
4517
  if (!this.username)
3921
4518
  throw Error("username required!");
@@ -3980,11 +4577,11 @@ class SDK {
3980
4577
  this.events.emit("message", request);
3981
4578
  });
3982
4579
  clientEvents.events.on("balance:update", (data) => {
3983
- const tag2 = TAG9 + " | balance:update | ";
4580
+ const tag7 = TAG9 + " | balance:update | ";
3984
4581
  try {
3985
4582
  const payload = typeof data === "string" ? JSON.parse(data) : data;
3986
4583
  const balance = payload.balance;
3987
- console.log(tag2, "Received balance update:", balance.caip);
4584
+ console.log(tag7, "Received balance update:", balance.caip);
3988
4585
  const exists = this.balances.find((b2) => b2.caip === balance.caip && b2.pubkey === balance.pubkey);
3989
4586
  if (!exists) {
3990
4587
  this.balances.push(balance);
@@ -3994,27 +4591,27 @@ class SDK {
3994
4591
  }
3995
4592
  this.events.emit("BALANCE_UPDATE", balance);
3996
4593
  } catch (e) {
3997
- console.error(tag2, "Error processing balance update:", e);
4594
+ console.error(tag7, "Error processing balance update:", e);
3998
4595
  }
3999
4596
  });
4000
4597
  clientEvents.events.on("sync:progress", (data) => {
4001
- const tag2 = TAG9 + " | sync:progress | ";
4598
+ const tag7 = TAG9 + " | sync:progress | ";
4002
4599
  try {
4003
4600
  const payload = typeof data === "string" ? JSON.parse(data) : data;
4004
- console.log(tag2, `Sync progress: ${payload.percentage}%`);
4601
+ console.log(tag7, `Sync progress: ${payload.percentage}%`);
4005
4602
  this.syncState.syncProgress = payload.percentage;
4006
4603
  this.syncState.syncedChains = payload.completed;
4007
4604
  this.syncState.totalChains = payload.total;
4008
4605
  this.events.emit("SYNC_PROGRESS", this.syncState);
4009
4606
  } catch (e) {
4010
- console.error(tag2, "Error processing sync progress:", e);
4607
+ console.error(tag7, "Error processing sync progress:", e);
4011
4608
  }
4012
4609
  });
4013
4610
  clientEvents.events.on("sync:complete", (data) => {
4014
- const tag2 = TAG9 + " | sync:complete | ";
4611
+ const tag7 = TAG9 + " | sync:complete | ";
4015
4612
  try {
4016
4613
  const payload = typeof data === "string" ? JSON.parse(data) : data;
4017
- console.log(tag2, `Sync complete: ${payload.balances} balances in ${payload.duration}ms`);
4614
+ console.log(tag7, `Sync complete: ${payload.balances} balances in ${payload.duration}ms`);
4018
4615
  this.syncState.isSynced = true;
4019
4616
  this.syncState.isInitialSync = false;
4020
4617
  this.syncState.syncProgress = 100;
@@ -4023,7 +4620,7 @@ class SDK {
4023
4620
  this.events.emit("SYNC_COMPLETE", this.syncState);
4024
4621
  this.events.emit("SYNC_STATE_CHANGED", this.syncState);
4025
4622
  } catch (e) {
4026
- console.error(tag2, "Error processing sync complete:", e);
4623
+ console.error(tag7, "Error processing sync complete:", e);
4027
4624
  }
4028
4625
  });
4029
4626
  this.events.emit("SET_STATUS", "init");
@@ -4055,18 +4652,27 @@ class SDK {
4055
4652
  }
4056
4653
  return this.pioneer;
4057
4654
  } catch (e) {
4058
- console.error(tag, "e: ", e);
4655
+ console.error(tag6, "e: ", e);
4059
4656
  throw e;
4060
4657
  }
4061
4658
  };
4062
4659
  this.buildDashboardFromBalances = function() {
4063
4660
  return buildDashboardFromBalances(this.balances, this.blockchains, this.assetsMap);
4064
4661
  };
4662
+ this.inferTypeFromCaip = function(caip) {
4663
+ if (caip.includes("/slip44:"))
4664
+ return "native";
4665
+ if (caip.includes("/erc20:") || caip.includes("/bep20:") || caip.includes("/spl:"))
4666
+ return "token";
4667
+ if (caip.includes("/denom:"))
4668
+ return "native";
4669
+ return "unknown";
4670
+ };
4065
4671
  this.syncMarket = async function() {
4066
4672
  return syncMarket(this.balances, this.pioneer);
4067
4673
  };
4068
4674
  this.sync = async function() {
4069
- const tag = `${TAG9} | sync | `;
4675
+ const tag6 = `${TAG9} | sync | `;
4070
4676
  try {
4071
4677
  const matchesNetwork = (item, networkId) => {
4072
4678
  if (!item.networks || !Array.isArray(item.networks))
@@ -4110,9 +4716,9 @@ class SDK {
4110
4716
  }
4111
4717
  }
4112
4718
  await this.getBalances();
4113
- console.log(tag, "Loading charts (tokens + portfolio)...");
4719
+ console.log(tag6, "Loading charts (tokens + portfolio)...");
4114
4720
  await this.getCharts();
4115
- console.log(tag, `Charts loaded. Total balances: ${this.balances.length}`);
4721
+ console.log(tag6, `Charts loaded. Total balances: ${this.balances.length}`);
4116
4722
  await this.syncMarket();
4117
4723
  const dashboardData = {
4118
4724
  networks: [],
@@ -4201,7 +4807,7 @@ class SDK {
4201
4807
  this.events.emit("SYNC_COMPLETE", this.syncState);
4202
4808
  return true;
4203
4809
  } catch (e) {
4204
- console.error(tag, "Error in sync:", e);
4810
+ console.error(tag6, "Error in sync:", e);
4205
4811
  throw e;
4206
4812
  }
4207
4813
  };
@@ -4215,7 +4821,7 @@ class SDK {
4215
4821
  }
4216
4822
  };
4217
4823
  this.buildTx = async function(sendPayload) {
4218
- let tag = TAG9 + " | buildTx | ";
4824
+ let tag6 = TAG9 + " | buildTx | ";
4219
4825
  try {
4220
4826
  const transactionDependencies = {
4221
4827
  context: this.context,
@@ -4229,7 +4835,7 @@ class SDK {
4229
4835
  };
4230
4836
  let txManager = new TransactionManager(transactionDependencies, this.events);
4231
4837
  let unsignedTx = await txManager.transfer(sendPayload);
4232
- console.log(tag, "unsignedTx: ", unsignedTx);
4838
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4233
4839
  return unsignedTx;
4234
4840
  } catch (e) {
4235
4841
  console.error(e);
@@ -4237,14 +4843,14 @@ class SDK {
4237
4843
  }
4238
4844
  };
4239
4845
  this.buildDelegateTx = async function(caip, params) {
4240
- let tag = TAG9 + " | buildDelegateTx | ";
4846
+ let tag6 = TAG9 + " | buildDelegateTx | ";
4241
4847
  try {
4242
4848
  const delegateParams = {
4243
4849
  ...params,
4244
4850
  type: "delegate"
4245
4851
  };
4246
4852
  let unsignedTx = await createUnsignedStakingTx(caip, delegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4247
- console.log(tag, "unsignedTx: ", unsignedTx);
4853
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4248
4854
  return unsignedTx;
4249
4855
  } catch (e) {
4250
4856
  console.error(e);
@@ -4252,14 +4858,14 @@ class SDK {
4252
4858
  }
4253
4859
  };
4254
4860
  this.buildUndelegateTx = async function(caip, params) {
4255
- let tag = TAG9 + " | buildUndelegateTx | ";
4861
+ let tag6 = TAG9 + " | buildUndelegateTx | ";
4256
4862
  try {
4257
4863
  const undelegateParams = {
4258
4864
  ...params,
4259
4865
  type: "undelegate"
4260
4866
  };
4261
4867
  let unsignedTx = await createUnsignedStakingTx(caip, undelegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4262
- console.log(tag, "unsignedTx: ", unsignedTx);
4868
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4263
4869
  return unsignedTx;
4264
4870
  } catch (e) {
4265
4871
  console.error(e);
@@ -4267,14 +4873,14 @@ class SDK {
4267
4873
  }
4268
4874
  };
4269
4875
  this.buildClaimRewardsTx = async function(caip, params) {
4270
- let tag = TAG9 + " | buildClaimRewardsTx | ";
4876
+ let tag6 = TAG9 + " | buildClaimRewardsTx | ";
4271
4877
  try {
4272
4878
  const claimParams = {
4273
4879
  ...params,
4274
4880
  type: "claim_rewards"
4275
4881
  };
4276
4882
  let unsignedTx = await createUnsignedStakingTx(caip, claimParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4277
- console.log(tag, "unsignedTx: ", unsignedTx);
4883
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4278
4884
  return unsignedTx;
4279
4885
  } catch (e) {
4280
4886
  console.error(e);
@@ -4282,7 +4888,7 @@ class SDK {
4282
4888
  }
4283
4889
  };
4284
4890
  this.buildClaimAllRewardsTx = async function(caip, params) {
4285
- let tag = TAG9 + " | buildClaimAllRewardsTx | ";
4891
+ let tag6 = TAG9 + " | buildClaimAllRewardsTx | ";
4286
4892
  try {
4287
4893
  const claimAllParams = {
4288
4894
  ...params,
@@ -4296,7 +4902,7 @@ class SDK {
4296
4902
  }
4297
4903
  };
4298
4904
  this.signTx = async function(caip, unsignedTx) {
4299
- let tag = TAG9 + " | signTx | ";
4905
+ let tag6 = TAG9 + " | signTx | ";
4300
4906
  try {
4301
4907
  const transactionDependencies = {
4302
4908
  context: this.context,
@@ -4317,7 +4923,7 @@ class SDK {
4317
4923
  }
4318
4924
  };
4319
4925
  this.broadcastTx = async function(caip, signedTx) {
4320
- let tag = TAG9 + " | broadcastTx | ";
4926
+ let tag6 = TAG9 + " | broadcastTx | ";
4321
4927
  try {
4322
4928
  const transactionDependencies = {
4323
4929
  context: this.context,
@@ -4341,7 +4947,7 @@ class SDK {
4341
4947
  }
4342
4948
  };
4343
4949
  this.swap = async function(swapPayload) {
4344
- let tag = `${TAG9} | swap | `;
4950
+ let tag6 = `${TAG9} | swap | `;
4345
4951
  try {
4346
4952
  if (!swapPayload)
4347
4953
  throw Error("swapPayload required!");
@@ -4390,15 +4996,15 @@ class SDK {
4390
4996
  throw new Error(`Cannot use max amount: no balance found for ${swapPayload.caipIn}`);
4391
4997
  }
4392
4998
  let totalBalance = 0;
4393
- console.log(tag, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4999
+ console.log(tag6, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4394
5000
  for (const balanceEntry of inputBalances) {
4395
5001
  const balance = parseFloat(balanceEntry.balance) || 0;
4396
5002
  totalBalance += balance;
4397
- console.log(tag, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
5003
+ console.log(tag6, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4398
5004
  }
4399
5005
  this.assetContext.balance = totalBalance.toString();
4400
5006
  this.assetContext.valueUsd = (totalBalance * parseFloat(this.assetContext.priceUsd || "0")).toFixed(2);
4401
- console.log(tag, `Updated assetContext balance to aggregated total: ${totalBalance}`);
5007
+ console.log(tag6, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4402
5008
  const feeReserves = {
4403
5009
  "bip122:000000000019d6689c085ae165831e93/slip44:0": 0.00005,
4404
5010
  "eip155:1/slip44:60": 0.001,
@@ -4409,7 +5015,7 @@ class SDK {
4409
5015
  };
4410
5016
  const reserve = feeReserves[swapPayload.caipIn] || 0.0001;
4411
5017
  inputAmount = Math.max(0, totalBalance - reserve);
4412
- console.log(tag, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
5018
+ console.log(tag6, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4413
5019
  } else {
4414
5020
  inputAmount = typeof swapPayload.amount === "string" ? parseFloat(swapPayload.amount) : swapPayload.amount;
4415
5021
  if (isNaN(inputAmount) || inputAmount <= 0) {
@@ -4429,7 +5035,7 @@ class SDK {
4429
5035
  result = await this.pioneer.Quote(quote);
4430
5036
  result = result.data;
4431
5037
  } catch (e) {
4432
- console.error(tag, "Failed to get quote: ", e);
5038
+ console.error(tag6, "Failed to get quote: ", e);
4433
5039
  throw Error("Quote API failed for path: " + quote.sellAsset + " -> " + quote.buyAsset + ". Error: " + e);
4434
5040
  }
4435
5041
  if (!result || result.length === 0)
@@ -4456,16 +5062,16 @@ class SDK {
4456
5062
  if (tx.type === "deposit") {
4457
5063
  unsignedTx = await createUnsignedTendermintTx(caip, tx.type, tx.txParams.amount, tx.txParams.memo, this.pubkeys, this.pioneer, this.pubkeyContext, false, undefined);
4458
5064
  } else if (tx.type === "EVM" || tx.type === "evm") {
4459
- console.log(tag, "Building EVM swap transaction with createUnsignedEvmTx");
5065
+ console.log(tag6, "Building EVM swap transaction with createUnsignedEvmTx");
4460
5066
  unsignedTx = await createUnsignedEvmTx(caip, tx.txParams.recipientAddress, parseFloat(tx.txParams.amount), tx.txParams.memo, this.pubkeys, this.pioneer, this.pubkeyContext, false);
4461
- console.log(tag, "✅ Built complete EVM transaction:", {
5067
+ console.log(tag6, "✅ Built complete EVM transaction:", {
4462
5068
  to: unsignedTx.to,
4463
5069
  from: this.pubkeyContext?.address,
4464
5070
  value: unsignedTx.value,
4465
5071
  chainId: unsignedTx.chainId,
4466
5072
  hasData: !!unsignedTx.data
4467
5073
  });
4468
- console.log(tag, "\uD83D\uDEE1️ Running Tenderly simulation for EVM swap...");
5074
+ console.log(tag6, "\uD83D\uDEE1️ Running Tenderly simulation for EVM swap...");
4469
5075
  try {
4470
5076
  const insightResult = await this.pioneer.Insight({
4471
5077
  tx: unsignedTx,
@@ -4473,15 +5079,15 @@ class SDK {
4473
5079
  isThorchainSwap: tx.txParams.isThorchainSwap || false
4474
5080
  });
4475
5081
  const insight = insightResult.body;
4476
- console.log(tag, "Simulation result:", insight?.simulation);
5082
+ console.log(tag6, "Simulation result:", insight?.simulation);
4477
5083
  if (!insight || !insight.simulation) {
4478
- console.warn(tag, "⚠️ WARNING: Tenderly simulation unavailable - proceeding without validation");
5084
+ console.warn(tag6, "⚠️ WARNING: Tenderly simulation unavailable - proceeding without validation");
4479
5085
  } else if (!insight.simulation.success) {
4480
- console.warn(tag, `⚠️ WARNING: Swap simulation FAILED - ${insight.simulation.error || "Transaction may revert"}`);
4481
- console.warn(tag, "⚠️ Proceeding anyway - USE CAUTION");
5086
+ console.warn(tag6, `⚠️ WARNING: Swap simulation FAILED - ${insight.simulation.error || "Transaction may revert"}`);
5087
+ console.warn(tag6, "⚠️ Proceeding anyway - USE CAUTION");
4482
5088
  } else {
4483
5089
  if (tx.txParams.isThorchainSwap) {
4484
- console.log(tag, "\uD83D\uDD0D Verifying THORChain swap parameters...");
5090
+ console.log(tag6, "\uD83D\uDD0D Verifying THORChain swap parameters...");
4485
5091
  const method = insight.simulation.method;
4486
5092
  if (!method || !method.toLowerCase().includes("deposit")) {
4487
5093
  throw new Error(`❌ CRITICAL: Invalid THORChain swap method: ${method} - expected depositWithExpiry`);
@@ -4492,20 +5098,20 @@ class SDK {
4492
5098
  if (routerAddress.toLowerCase() === vaultAddress.toLowerCase()) {
4493
5099
  throw new Error(`❌ CRITICAL: Sending directly to vault ${vaultAddress} instead of router!`);
4494
5100
  }
4495
- console.log(tag, `✅ Router: ${routerAddress}`);
4496
- console.log(tag, `✅ Vault: ${vaultAddress}`);
5101
+ console.log(tag6, `✅ Router: ${routerAddress}`);
5102
+ console.log(tag6, `✅ Vault: ${vaultAddress}`);
4497
5103
  }
4498
5104
  if (insight.simulation.addresses && insight.simulation.addresses.length > 0) {
4499
- console.log(tag, `✅ Addresses involved: ${insight.simulation.addresses.length}`);
5105
+ console.log(tag6, `✅ Addresses involved: ${insight.simulation.addresses.length}`);
4500
5106
  } else {
4501
- console.log(tag, "⚠️ WARNING: No addresses detected in simulation");
5107
+ console.log(tag6, "⚠️ WARNING: No addresses detected in simulation");
4502
5108
  }
4503
5109
  }
4504
- console.log(tag, `✅ Simulation PASSED - Gas used: ${insight.simulation.gasUsed}`);
4505
- console.log(tag, `✅ Method: ${insight.simulation.method}`);
5110
+ console.log(tag6, `✅ Simulation PASSED - Gas used: ${insight.simulation.gasUsed}`);
5111
+ console.log(tag6, `✅ Method: ${insight.simulation.method}`);
4506
5112
  }
4507
5113
  } catch (e) {
4508
- console.error(tag, "❌ Simulation validation failed:", e.message);
5114
+ console.error(tag6, "❌ Simulation validation failed:", e.message);
4509
5115
  throw new Error(`Swap blocked by simulation failure: ${e.message}`);
4510
5116
  }
4511
5117
  } else {
@@ -4525,12 +5131,12 @@ class SDK {
4525
5131
  return unsignedTx;
4526
5132
  }
4527
5133
  } catch (e) {
4528
- console.error(tag, "Error: ", e);
5134
+ console.error(tag6, "Error: ", e);
4529
5135
  throw e;
4530
5136
  }
4531
5137
  };
4532
5138
  this.transfer = async function(sendPayload) {
4533
- let tag = `${TAG9} | transfer | `;
5139
+ let tag6 = `${TAG9} | transfer | `;
4534
5140
  try {
4535
5141
  if (!sendPayload)
4536
5142
  throw Error("sendPayload required!");
@@ -4564,15 +5170,15 @@ class SDK {
4564
5170
  return { txid, events: this.events };
4565
5171
  } catch (error) {
4566
5172
  if (error instanceof Error) {
4567
- console.error(tag, "An error occurred during the transfer process:", error.message);
5173
+ console.error(tag6, "An error occurred during the transfer process:", error.message);
4568
5174
  } else {
4569
- console.error(tag, "An unknown error occurred during the transfer process");
5175
+ console.error(tag6, "An unknown error occurred during the transfer process");
4570
5176
  }
4571
5177
  throw error;
4572
5178
  }
4573
5179
  };
4574
5180
  this.followTransaction = async function(caip, txid) {
4575
- let tag = " | followTransaction | ";
5181
+ let tag6 = " | followTransaction | ";
4576
5182
  try {
4577
5183
  const finalConfirmationBlocksByCaip = {
4578
5184
  dogecoin: 3,
@@ -4602,7 +5208,7 @@ class SDK {
4602
5208
  }
4603
5209
  }
4604
5210
  } catch (error) {
4605
- console.error(tag, "Error:", error);
5211
+ console.error(tag6, "Error:", error);
4606
5212
  }
4607
5213
  if (!isConfirmed) {
4608
5214
  await new Promise((resolve) => setTimeout(resolve, 8000));
@@ -4620,18 +5226,18 @@ class SDK {
4620
5226
  requiredConfirmations
4621
5227
  };
4622
5228
  } catch (error) {
4623
- console.error(tag, "Error:", error);
5229
+ console.error(tag6, "Error:", error);
4624
5230
  throw new Error("Failed to follow transaction");
4625
5231
  }
4626
5232
  };
4627
5233
  this.setBlockchains = async function(blockchains) {
4628
- const tag = `${TAG9} | setBlockchains | `;
5234
+ const tag6 = `${TAG9} | setBlockchains | `;
4629
5235
  try {
4630
5236
  if (!blockchains)
4631
5237
  throw Error("blockchains required!");
4632
5238
  const uniqueBlockchains = [...new Set(blockchains)];
4633
5239
  if (blockchains.length !== uniqueBlockchains.length) {
4634
- console.warn(tag, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
5240
+ console.warn(tag6, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
4635
5241
  }
4636
5242
  this.blockchains = uniqueBlockchains;
4637
5243
  this.events.emit("SET_BLOCKCHAINS", this.blockchains);
@@ -4641,12 +5247,12 @@ class SDK {
4641
5247
  }
4642
5248
  };
4643
5249
  this.addAsset = async function(caip, data) {
4644
- let tag = TAG9 + " | addAsset | ";
5250
+ let tag6 = TAG9 + " | addAsset | ";
4645
5251
  try {
4646
5252
  let success = false;
4647
5253
  if (!caip)
4648
5254
  throw new Error("caip required!");
4649
- let dataLocal = assetData[caip];
5255
+ let dataLocal = assetData2[caip];
4650
5256
  if (!dataLocal) {
4651
5257
  if (!data.networkId)
4652
5258
  throw new Error("networkId required! can not build asset");
@@ -4679,22 +5285,22 @@ class SDK {
4679
5285
  }
4680
5286
  };
4681
5287
  this.clearWalletState = async function() {
4682
- const tag = `${TAG9} | clearWalletState | `;
5288
+ const tag6 = `${TAG9} | clearWalletState | `;
4683
5289
  try {
4684
5290
  this.context = null;
4685
5291
  this.paths = [];
4686
5292
  this.blockchains = [];
4687
5293
  this.pubkeys = [];
4688
5294
  this.pubkeySet.clear();
4689
- console.log(tag, "Cleared wallet state including pubkeys and tracking set");
5295
+ console.log(tag6, "Cleared wallet state including pubkeys and tracking set");
4690
5296
  return true;
4691
5297
  } catch (e) {
4692
- console.error(tag, "e: ", e);
5298
+ console.error(tag6, "e: ", e);
4693
5299
  throw e;
4694
5300
  }
4695
5301
  };
4696
5302
  this.addPath = async function(path) {
4697
- const tag = `${TAG9} | addPath | `;
5303
+ const tag6 = `${TAG9} | addPath | `;
4698
5304
  try {
4699
5305
  this.paths.push(path);
4700
5306
  const pubkey = await getPubkey(path.networks[0], path, this.keepKeySdk, this.context);
@@ -4703,14 +5309,14 @@ class SDK {
4703
5309
  this.buildDashboardFromBalances();
4704
5310
  return { success: true, pubkey };
4705
5311
  } catch (e) {
4706
- console.error(tag, "Failed:", e);
5312
+ console.error(tag6, "Failed:", e);
4707
5313
  throw e;
4708
5314
  }
4709
5315
  };
4710
5316
  this.addPaths = async function(paths) {
4711
- const tag = `${TAG9} | addPaths | `;
5317
+ const tag6 = `${TAG9} | addPaths | `;
4712
5318
  try {
4713
- console.log(tag, `Adding ${paths.length} paths in batch mode...`);
5319
+ console.log(tag6, `Adding ${paths.length} paths in batch mode...`);
4714
5320
  this.paths.push(...paths);
4715
5321
  const newPubkeys = [];
4716
5322
  for (const path of paths) {
@@ -4719,10 +5325,10 @@ class SDK {
4719
5325
  this.addPubkey(pubkey);
4720
5326
  newPubkeys.push(pubkey);
4721
5327
  } catch (error) {
4722
- console.warn(tag, `Failed to get pubkey for path ${path.note}:`, error.message);
5328
+ console.warn(tag6, `Failed to get pubkey for path ${path.note}:`, error.message);
4723
5329
  }
4724
5330
  }
4725
- console.log(tag, `Successfully added ${newPubkeys.length} pubkeys`);
5331
+ console.log(tag6, `Successfully added ${newPubkeys.length} pubkeys`);
4726
5332
  const networkSet = new Set;
4727
5333
  for (const path of paths) {
4728
5334
  if (path.networks && Array.isArray(path.networks)) {
@@ -4730,13 +5336,13 @@ class SDK {
4730
5336
  }
4731
5337
  }
4732
5338
  const uniqueNetworks = [...networkSet];
4733
- console.log(tag, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
5339
+ console.log(tag6, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
4734
5340
  await this.getBalancesForNetworks(uniqueNetworks);
4735
5341
  this.buildDashboardFromBalances();
4736
- console.log(tag, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
5342
+ console.log(tag6, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
4737
5343
  return { success: true, pubkeys: newPubkeys };
4738
5344
  } catch (e) {
4739
- console.error(tag, "Failed:", e);
5345
+ console.error(tag6, "Failed:", e);
4740
5346
  throw e;
4741
5347
  }
4742
5348
  };
@@ -4744,12 +5350,12 @@ class SDK {
4744
5350
  return this.getGasAssets();
4745
5351
  };
4746
5352
  this.getGasAssets = async function() {
4747
- const tag = `${TAG9} | getGasAssets | `;
5353
+ const tag6 = `${TAG9} | getGasAssets | `;
4748
5354
  try {
4749
5355
  for (let i = 0;i < this.blockchains.length; i++) {
4750
5356
  let networkId = this.blockchains[i];
4751
5357
  let caip = networkIdToCaip2(networkId);
4752
- let asset = await assetData[caip.toLowerCase()];
5358
+ let asset = await assetData2[caip.toLowerCase()];
4753
5359
  if (asset) {
4754
5360
  asset.caip = caip.toLowerCase();
4755
5361
  asset.networkId = networkId;
@@ -4778,7 +5384,7 @@ class SDK {
4778
5384
  denom: "maya"
4779
5385
  };
4780
5386
  this.assetsMap.set(mayaTokenCaip, mayaToken);
4781
- console.log(tag, "Added MAYA token to assetsMap");
5387
+ console.log(tag6, "Added MAYA token to assetsMap");
4782
5388
  }
4783
5389
  return this.assetsMap;
4784
5390
  } catch (e) {
@@ -4787,7 +5393,7 @@ class SDK {
4787
5393
  }
4788
5394
  };
4789
5395
  this.getPubkeys = async function() {
4790
- const tag = `${TAG9} | getPubkeys | `;
5396
+ const tag6 = `${TAG9} | getPubkeys | `;
4791
5397
  try {
4792
5398
  if (this.paths.length === 0)
4793
5399
  throw new Error("No paths found!");
@@ -4801,43 +5407,46 @@ class SDK {
4801
5407
  }
4802
5408
  const pubkeysWithoutNetworks = this.pubkeys.filter((pk) => !pk.networks || !Array.isArray(pk.networks) || pk.networks.length === 0);
4803
5409
  if (pubkeysWithoutNetworks.length > 0) {
4804
- console.error(tag, "ERROR: Some pubkeys missing networks field!");
4805
- console.error(tag, "Affected pubkeys:", pubkeysWithoutNetworks.length);
5410
+ console.error(tag6, "ERROR: Some pubkeys missing networks field!");
5411
+ console.error(tag6, "Affected pubkeys:", pubkeysWithoutNetworks.length);
4806
5412
  pubkeysWithoutNetworks.forEach((pk) => {
4807
- console.error(tag, ` - ${pk.note || pk.pubkey}: networks=${pk.networks}`);
5413
+ console.error(tag6, ` - ${pk.note || pk.pubkey}: networks=${pk.networks}`);
4808
5414
  });
4809
5415
  for (const pubkey of pubkeysWithoutNetworks) {
4810
5416
  const matchingPath = this.paths.find((p) => JSON.stringify(p.addressNList) === JSON.stringify(pubkey.addressNList));
4811
5417
  if (matchingPath && matchingPath.networks) {
4812
- console.warn(tag, ` ⚠️ Auto-fixing: Adding networks from path ${matchingPath.note}`);
5418
+ console.warn(tag6, ` ⚠️ Auto-fixing: Adding networks from path ${matchingPath.note}`);
4813
5419
  pubkey.networks = matchingPath.networks;
4814
5420
  }
4815
5421
  }
4816
5422
  const stillMissing = this.pubkeys.filter((pk) => !pk.networks || !Array.isArray(pk.networks) || pk.networks.length === 0);
4817
5423
  if (stillMissing.length > 0) {
4818
- console.error(tag, `❌ CRITICAL: ${stillMissing.length} pubkeys still missing networks after auto-fix!`);
5424
+ console.error(tag6, `❌ CRITICAL: ${stillMissing.length} pubkeys still missing networks after auto-fix!`);
4819
5425
  stillMissing.forEach((pk) => {
4820
- console.error(tag, ` - ${pk.note || pk.pubkey}`);
5426
+ console.error(tag6, ` - ${pk.note || pk.pubkey}`);
4821
5427
  });
4822
5428
  } else {
4823
- console.log(tag, `✅ Auto-fix successful: All pubkeys now have networks field`);
5429
+ console.log(tag6, `✅ Auto-fix successful: All pubkeys now have networks field`);
4824
5430
  }
4825
5431
  }
4826
5432
  this.events.emit("SET_PUBKEYS", this.pubkeys);
4827
5433
  return pubkeys;
4828
5434
  } catch (error) {
4829
5435
  console.error("Error in getPubkeys:", error);
4830
- console.error(tag, "Error in getPubkeys:", error);
5436
+ console.error(tag6, "Error in getPubkeys:", error);
4831
5437
  throw error;
4832
5438
  }
4833
5439
  };
4834
- this.getBalancesForNetworks = async function(networkIds) {
4835
- const tag = `${TAG9} | getBalancesForNetworks | `;
5440
+ this.getBalancesForNetworks = async function(networkIds, forceRefresh) {
5441
+ const tag6 = `${TAG9} | getBalancesForNetworks | `;
4836
5442
  try {
4837
5443
  if (!this.pioneer) {
4838
- console.error(tag, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
5444
+ console.error(tag6, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
4839
5445
  throw new Error("Pioneer client not initialized. Call init() first.");
4840
5446
  }
5447
+ if (forceRefresh) {
5448
+ console.log(tag6, "\uD83D\uDD04 Force refresh requested - bypassing balance cache");
5449
+ }
4841
5450
  console.log("\uD83D\uDD0D [DIAGNOSTIC] Input networks:", networkIds);
4842
5451
  console.log("\uD83D\uDD0D [DIAGNOSTIC] Total pubkeys:", this.pubkeys.length);
4843
5452
  const pubkeysWithNetworks = this.pubkeys.filter((p) => p.networks && Array.isArray(p.networks));
@@ -4863,20 +5472,20 @@ class SDK {
4863
5472
  return network === adjustedNetworkId;
4864
5473
  }));
4865
5474
  if (pubkeys.length === 0) {
4866
- console.warn(tag, `⚠️ No pubkeys found for ${networkId} with networks field`);
4867
- console.warn(tag, "Attempting fallback: finding pubkeys by path matching");
5475
+ console.warn(tag6, `⚠️ No pubkeys found for ${networkId} with networks field`);
5476
+ console.warn(tag6, "Attempting fallback: finding pubkeys by path matching");
4868
5477
  const pathsForNetwork = this.paths.filter((p) => p.networks?.includes(networkId) || networkId.startsWith("eip155:") && p.networks?.includes("eip155:*"));
4869
5478
  for (const path of pathsForNetwork) {
4870
5479
  const matchingPubkey = this.pubkeys.find((pk) => JSON.stringify(pk.addressNList) === JSON.stringify(path.addressNList));
4871
5480
  if (matchingPubkey) {
4872
- console.warn(tag, ` ✓ Found pubkey via path matching: ${matchingPubkey.note || matchingPubkey.pubkey.slice(0, 10)}`);
5481
+ console.warn(tag6, ` ✓ Found pubkey via path matching: ${matchingPubkey.note || matchingPubkey.pubkey.slice(0, 10)}`);
4873
5482
  pubkeys.push(matchingPubkey);
4874
5483
  }
4875
5484
  }
4876
5485
  if (pubkeys.length > 0) {
4877
- console.warn(tag, ` ✅ Fallback successful: Found ${pubkeys.length} pubkeys for ${networkId}`);
5486
+ console.warn(tag6, ` ✅ Fallback successful: Found ${pubkeys.length} pubkeys for ${networkId}`);
4878
5487
  } else {
4879
- console.error(tag, ` ❌ Fallback failed: No pubkeys found for ${networkId}`);
5488
+ console.error(tag6, ` ❌ Fallback failed: No pubkeys found for ${networkId}`);
4880
5489
  }
4881
5490
  }
4882
5491
  const caipNative = await networkIdToCaip2(networkId);
@@ -4898,7 +5507,7 @@ class SDK {
4898
5507
  const apiCallStart = performance.now();
4899
5508
  console.time("GetPortfolioBalances Response Time");
4900
5509
  try {
4901
- let marketInfo = await this.pioneer.GetPortfolioBalances({ pubkeys: assetQuery });
5510
+ let marketInfo = await this.pioneer.GetPortfolioBalances({ pubkeys: assetQuery }, forceRefresh ? { forceRefresh: true } : undefined);
4902
5511
  const apiCallTime = performance.now() - apiCallStart;
4903
5512
  console.timeEnd("GetPortfolioBalances Response Time");
4904
5513
  console.log(`⏱️ [PERF] API call completed in ${apiCallTime.toFixed(0)}ms`);
@@ -4908,10 +5517,23 @@ class SDK {
4908
5517
  console.log(`⏱️ [PERF] Starting balance enrichment...`);
4909
5518
  for (let balance of balances) {
4910
5519
  const assetInfo = this.assetsMap.get(balance.caip.toLowerCase()) || this.assetsMap.get(balance.caip);
4911
- if (!assetInfo)
5520
+ if (!assetInfo) {
5521
+ console.warn(`⚠️ [ENRICHMENT] Asset metadata missing for ${balance.caip}, using fallback enrichment`);
5522
+ const inferredType = this.inferTypeFromCaip(balance.caip);
5523
+ Object.assign(balance, {
5524
+ type: balance.type || inferredType,
5525
+ isNative: balance.isNative ?? inferredType === "native",
5526
+ networkId: caipToNetworkId7(balance.caip),
5527
+ icon: "https://pioneers.dev/coins/unknown.png",
5528
+ identifier: `${balance.caip}:${balance.pubkey}`,
5529
+ updated: Date.now()
5530
+ });
4912
5531
  continue;
5532
+ }
4913
5533
  const color = ASSET_COLORS[balance.caip] || assetInfo.color;
4914
5534
  Object.assign(balance, assetInfo, {
5535
+ type: balance.type || assetInfo.type,
5536
+ isNative: balance.isNative ?? assetInfo.isNative,
4915
5537
  networkId: caipToNetworkId7(balance.caip),
4916
5538
  icon: assetInfo.icon || "https://pioneers.dev/coins/etherum.png",
4917
5539
  identifier: `${balance.caip}:${balance.pubkey}`,
@@ -4933,43 +5555,43 @@ class SDK {
4933
5555
  console.log(`⏱️ [PERF] Total getBalancesForNetworks: ${(performance.now() - apiCallStart).toFixed(0)}ms`);
4934
5556
  return this.balances;
4935
5557
  } catch (apiError) {
4936
- console.error(tag, "GetPortfolioBalances API call failed:", apiError);
5558
+ console.error(tag6, "GetPortfolioBalances API call failed:", apiError);
4937
5559
  throw new Error(`GetPortfolioBalances API call failed: ${apiError?.message || "Unknown error"}`);
4938
5560
  }
4939
5561
  } catch (e) {
4940
- console.error(tag, "Error: ", e);
5562
+ console.error(tag6, "Error: ", e);
4941
5563
  throw e;
4942
5564
  }
4943
5565
  };
4944
- this.getBalances = async function() {
4945
- const tag = `${TAG9} | getBalances | `;
5566
+ this.getBalances = async function(forceRefresh) {
5567
+ const tag6 = `${TAG9} | getBalances | `;
4946
5568
  try {
4947
- return await this.getBalancesForNetworks(this.blockchains);
5569
+ return await this.getBalancesForNetworks(this.blockchains, forceRefresh);
4948
5570
  } catch (e) {
4949
- console.error(tag, "Error in getBalances: ", e);
5571
+ console.error(tag6, "Error in getBalances: ", e);
4950
5572
  throw e;
4951
5573
  }
4952
5574
  };
4953
5575
  this.getBalance = async function(networkId) {
4954
- const tag = `${TAG9} | getBalance | `;
5576
+ const tag6 = `${TAG9} | getBalance | `;
4955
5577
  try {
4956
5578
  const results = await this.getBalancesForNetworks([networkId]);
4957
5579
  const filtered = results.filter(async (b2) => b2.networkId === await networkIdToCaip2(networkId));
4958
5580
  return filtered;
4959
5581
  } catch (e) {
4960
- console.error(tag, "Error: ", e);
5582
+ console.error(tag6, "Error: ", e);
4961
5583
  throw e;
4962
5584
  }
4963
5585
  };
4964
5586
  this.getFees = async function(networkId) {
4965
- const tag = `${TAG9} | getFees | `;
5587
+ const tag6 = `${TAG9} | getFees | `;
4966
5588
  try {
4967
5589
  if (!this.pioneer) {
4968
5590
  throw new Error("Pioneer client not initialized. Call init() first.");
4969
5591
  }
4970
5592
  return await getFees(this.pioneer, networkId);
4971
5593
  } catch (e) {
4972
- console.error(tag, "Error getting fees: ", e);
5594
+ console.error(tag6, "Error getting fees: ", e);
4973
5595
  throw e;
4974
5596
  }
4975
5597
  };
@@ -4977,42 +5599,12 @@ class SDK {
4977
5599
  return estimateTransactionFee(feeRate, unit, networkType, txSize);
4978
5600
  };
4979
5601
  this.getCharts = async function() {
4980
- const tag = `${TAG9} | getCharts | `;
5602
+ const tag6 = `${TAG9} | getCharts | `;
4981
5603
  try {
4982
- console.log(tag, "Fetching charts from batch endpoint");
4983
- const pubkeysForBatch = [];
4984
- for (const pubkey of this.pubkeys) {
4985
- const address = pubkey.address || pubkey.master || pubkey.pubkey;
4986
- if (!address)
4987
- continue;
4988
- const supportedNetworks = pubkey.networks || [];
4989
- for (const blockchain of this.blockchains) {
4990
- const supportsNetwork = supportedNetworks.some((net) => net === blockchain || net.endsWith(":*") && blockchain.startsWith(net.replace(":*", ":")));
4991
- if (supportsNetwork) {
4992
- let caip;
4993
- if (blockchain.startsWith("eip155:")) {
4994
- caip = `${blockchain}/slip44:60`;
4995
- } else {
4996
- caip = `${blockchain}/slip44:0`;
4997
- }
4998
- pubkeysForBatch.push({
4999
- pubkey: address,
5000
- caip
5001
- });
5002
- }
5003
- }
5004
- }
5005
- console.log(tag, `Calling batch GetCharts with ${pubkeysForBatch.length} pubkeys`);
5006
- let newBalances = [];
5007
- try {
5008
- const chartsResponse = await this.pioneer.GetCharts({
5009
- pubkeys: pubkeysForBatch
5010
- });
5011
- newBalances = chartsResponse?.data?.balances || [];
5012
- console.log(tag, `Received ${newBalances.length} balances from batch endpoint`);
5013
- } catch (chartsError) {
5014
- console.warn(tag, `GetCharts API not available (${chartsError.message}), continuing without charts data`);
5015
- }
5604
+ console.log(tag6, "Fetching charts (portfolio + tokens + staking)...");
5605
+ const { getCharts: getChartsModular } = await Promise.resolve().then(() => (init_charts(), exports_charts));
5606
+ const newBalances = await getChartsModular(this.blockchains, this.pioneer, this.pubkeys, this.context);
5607
+ console.log(tag6, `Modular charts returned ${newBalances.length} balances (native + tokens + staking)`);
5016
5608
  const uniqueBalances = new Map([...this.balances, ...newBalances].map((balance) => [
5017
5609
  balance.identifier || `${balance.caip}:${balance.pubkey}`,
5018
5610
  {
@@ -5020,17 +5612,19 @@ class SDK {
5020
5612
  type: balance.type || "balance"
5021
5613
  }
5022
5614
  ]));
5023
- console.log(tag, "uniqueBalances: ", uniqueBalances.size);
5615
+ console.log(tag6, "Deduplicated to:", uniqueBalances.size, "unique balances");
5024
5616
  this.balances = Array.from(uniqueBalances.values());
5025
- console.log(tag, "Updated this.balances: ", this.balances.length);
5617
+ const tokens = this.balances.filter((b2) => b2.token === true);
5618
+ const native = this.balances.filter((b2) => b2.token !== true);
5619
+ console.log(tag6, `Balance breakdown: ${native.length} native + ${tokens.length} tokens = ${this.balances.length} total`);
5026
5620
  return this.balances;
5027
5621
  } catch (e) {
5028
- console.error(tag, "Error in getCharts:", e);
5622
+ console.error(tag6, "Error in getCharts:", e);
5029
5623
  throw e;
5030
5624
  }
5031
5625
  };
5032
5626
  this.setContext = async (context) => {
5033
- const tag = `${TAG9} | setContext | `;
5627
+ const tag6 = `${TAG9} | setContext | `;
5034
5628
  try {
5035
5629
  if (!context)
5036
5630
  throw Error("context required!");
@@ -5038,12 +5632,12 @@ class SDK {
5038
5632
  this.events.emit("SET_CONTEXT", context);
5039
5633
  return { success: true };
5040
5634
  } catch (e) {
5041
- console.error(tag, "e: ", e);
5635
+ console.error(tag6, "e: ", e);
5042
5636
  return { success: false };
5043
5637
  }
5044
5638
  };
5045
5639
  this.setContextType = async (contextType) => {
5046
- const tag = `${TAG9} | setContextType | `;
5640
+ const tag6 = `${TAG9} | setContextType | `;
5047
5641
  try {
5048
5642
  if (!contextType)
5049
5643
  throw Error("contextType required!");
@@ -5051,22 +5645,27 @@ class SDK {
5051
5645
  this.events.emit("SET_CONTEXT_TYPE", contextType);
5052
5646
  return { success: true };
5053
5647
  } catch (e) {
5054
- console.error(tag, "e: ", e);
5648
+ console.error(tag6, "e: ", e);
5055
5649
  return { success: false };
5056
5650
  }
5057
5651
  };
5058
- this.refresh = async () => {
5059
- const tag = `${TAG9} | refresh | `;
5652
+ this.refresh = async (forceRefresh) => {
5653
+ const tag6 = `${TAG9} | refresh | `;
5060
5654
  try {
5061
- await this.sync();
5655
+ if (forceRefresh) {
5656
+ console.log(tag6, "\uD83D\uDD04 Force refresh - fetching fresh balances from blockchain");
5657
+ await this.getBalances(true);
5658
+ } else {
5659
+ await this.sync();
5660
+ }
5062
5661
  return this.balances;
5063
5662
  } catch (e) {
5064
- console.error(tag, "e: ", e);
5663
+ console.error(tag6, "e: ", e);
5065
5664
  throw e;
5066
5665
  }
5067
5666
  };
5068
5667
  this.setAssetContext = async function(asset) {
5069
- const tag = `${TAG9} | setAssetContext | `;
5668
+ const tag6 = `${TAG9} | setAssetContext | `;
5070
5669
  try {
5071
5670
  if (!asset) {
5072
5671
  this.assetContext = null;
@@ -5078,7 +5677,7 @@ class SDK {
5078
5677
  asset.networkId = caipToNetworkId7(asset.caip);
5079
5678
  if (!this.pubkeys || this.pubkeys.length === 0) {
5080
5679
  const errorMsg = `Cannot set asset context for ${asset.caip} - no pubkeys loaded. Please initialize wallet first.`;
5081
- console.error(tag, errorMsg);
5680
+ console.error(tag6, errorMsg);
5082
5681
  throw new Error(errorMsg);
5083
5682
  }
5084
5683
  const pubkeysForNetwork = this.pubkeys.filter((e) => {
@@ -5093,8 +5692,8 @@ class SDK {
5093
5692
  });
5094
5693
  if (pubkeysForNetwork.length === 0) {
5095
5694
  const errorMsg = `Cannot set asset context for ${asset.caip} - no address/xpub found for network ${asset.networkId}`;
5096
- console.error(tag, errorMsg);
5097
- console.error(tag, "Available networks in pubkeys:", [
5695
+ console.error(tag6, errorMsg);
5696
+ console.error(tag6, "Available networks in pubkeys:", [
5098
5697
  ...new Set(this.pubkeys.flatMap((p) => p.networks || []))
5099
5698
  ]);
5100
5699
  throw new Error(errorMsg);
@@ -5104,43 +5703,43 @@ class SDK {
5104
5703
  const xpubFound = pubkeysForNetwork.some((p) => p.type === "xpub" && p.pubkey);
5105
5704
  if (!xpubFound) {
5106
5705
  const errorMsg = `Cannot set asset context for UTXO chain ${asset.caip} - xpub required but not found`;
5107
- console.error(tag, errorMsg);
5706
+ console.error(tag6, errorMsg);
5108
5707
  throw new Error(errorMsg);
5109
5708
  }
5110
5709
  }
5111
5710
  const hasValidAddress = pubkeysForNetwork.some((p) => p.address || p.master || p.pubkey);
5112
5711
  if (!hasValidAddress) {
5113
5712
  const errorMsg = `Cannot set asset context for ${asset.caip} - no valid address found in pubkeys`;
5114
- console.error(tag, errorMsg);
5713
+ console.error(tag6, errorMsg);
5115
5714
  throw new Error(errorMsg);
5116
5715
  }
5117
- console.log(tag, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5716
+ console.log(tag6, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5118
5717
  let freshPriceUsd = 0;
5119
5718
  try {
5120
5719
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5121
- console.warn(tag, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5720
+ console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5122
5721
  } else {
5123
- console.log(tag, "Fetching fresh market price for:", asset.caip);
5722
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
5124
5723
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5125
- console.log(tag, "Market data response:", marketData);
5724
+ console.log(tag6, "Market data response:", marketData);
5126
5725
  if (marketData && marketData.data && marketData.data.length > 0) {
5127
5726
  freshPriceUsd = marketData.data[0];
5128
- console.log(tag, "✅ Fresh market price:", freshPriceUsd);
5727
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5129
5728
  } else {
5130
- console.warn(tag, "No market data returned for:", asset.caip);
5729
+ console.warn(tag6, "No market data returned for:", asset.caip);
5131
5730
  }
5132
5731
  }
5133
5732
  } catch (marketError) {
5134
- console.error(tag, "Error fetching market price:", marketError);
5733
+ console.error(tag6, "Error fetching market price:", marketError);
5135
5734
  }
5136
5735
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5137
- console.log(tag, "assetInfo: ", assetInfo);
5138
- let assetInfoDiscovery = assetData[asset.caip];
5139
- console.log(tag, "assetInfoDiscovery: ", assetInfoDiscovery);
5736
+ console.log(tag6, "assetInfo: ", assetInfo);
5737
+ let assetInfoDiscovery = assetData2[asset.caip];
5738
+ console.log(tag6, "assetInfoDiscovery: ", assetInfoDiscovery);
5140
5739
  if (assetInfoDiscovery)
5141
5740
  assetInfo = assetInfoDiscovery;
5142
5741
  if (!assetInfo) {
5143
- console.log(tag, "Building placeholder asset!");
5742
+ console.log(tag6, "Building placeholder asset!");
5144
5743
  assetInfo = {
5145
5744
  caip: asset.caip.toLowerCase(),
5146
5745
  networkId: asset.networkId,
@@ -5157,30 +5756,30 @@ class SDK {
5157
5756
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5158
5757
  if (balance > 0 && valueUsd > 0) {
5159
5758
  priceValue = valueUsd / balance;
5160
- console.log(tag, "calculated priceUsd from valueUsd/balance:", priceValue);
5759
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5161
5760
  }
5162
5761
  }
5163
5762
  if (priceValue && priceValue > 0) {
5164
- console.log(tag, "detected priceUsd from balance:", priceValue);
5763
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
5165
5764
  assetInfo.priceUsd = priceValue;
5166
5765
  }
5167
5766
  }
5168
5767
  if (freshPriceUsd && freshPriceUsd > 0) {
5169
5768
  assetInfo.priceUsd = freshPriceUsd;
5170
- console.log(tag, "✅ Using fresh market price:", freshPriceUsd);
5769
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5171
5770
  let totalBalance = 0;
5172
5771
  let totalValueUsd = 0;
5173
- console.log(tag, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5772
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5174
5773
  for (const balanceEntry of matchingBalances) {
5175
5774
  const balance = parseFloat(balanceEntry.balance) || 0;
5176
5775
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5177
5776
  totalBalance += balance;
5178
5777
  totalValueUsd += valueUsd;
5179
- console.log(tag, ` Balance entry: ${balance} (${valueUsd} USD)`);
5778
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5180
5779
  }
5181
5780
  assetInfo.balance = totalBalance.toString();
5182
5781
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5183
- console.log(tag, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5782
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5184
5783
  }
5185
5784
  const assetBalances = this.balances.filter((b2) => b2.caip === asset.caip);
5186
5785
  const assetPubkeys = this.pubkeys.filter((p) => p.networks && Array.isArray(p.networks) && p.networks.includes(caipToNetworkId7(asset.caip)) || caipToNetworkId7(asset.caip).includes("eip155") && p.networks && Array.isArray(p.networks) && p.networks.some((n) => n.startsWith("eip155")));
@@ -5200,7 +5799,7 @@ class SDK {
5200
5799
  const balanceAmount = parseFloat(balance.balance || 0);
5201
5800
  balance.valueUsd = (balanceAmount * freshPriceUsd).toString();
5202
5801
  }
5203
- console.log(tag, "Updated all balances with fresh price data");
5802
+ console.log(tag6, "Updated all balances with fresh price data");
5204
5803
  }
5205
5804
  this.assetContext = finalAssetContext;
5206
5805
  if (asset.isToken || asset.type === "token" || assetInfo.isToken || assetInfo.type === "token") {
@@ -5252,20 +5851,20 @@ class SDK {
5252
5851
  const currentContextValid = this.pubkeyContext?.networks?.includes(networkId);
5253
5852
  if (!this.pubkeyContext || !currentContextValid) {
5254
5853
  this.pubkeyContext = assetPubkeys[0];
5255
- console.log(tag, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5854
+ console.log(tag6, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5256
5855
  } else {
5257
- console.log(tag, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5856
+ console.log(tag6, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5258
5857
  }
5259
5858
  }
5260
5859
  this.events.emit("SET_ASSET_CONTEXT", this.assetContext);
5261
5860
  return this.assetContext;
5262
5861
  } catch (e) {
5263
- console.error(tag, "e: ", e);
5862
+ console.error(tag6, "e: ", e);
5264
5863
  throw e;
5265
5864
  }
5266
5865
  };
5267
5866
  this.setPubkeyContext = async function(pubkey) {
5268
- let tag = `${TAG9} | setPubkeyContext | `;
5867
+ let tag6 = `${TAG9} | setPubkeyContext | `;
5269
5868
  try {
5270
5869
  if (!pubkey)
5271
5870
  throw Error("pubkey is required");
@@ -5273,31 +5872,31 @@ class SDK {
5273
5872
  throw Error("invalid pubkey: missing pubkey or address");
5274
5873
  const exists = this.pubkeys.some((pk) => pk.pubkey === pubkey.pubkey || pk.address === pubkey.address || pk.pubkey === pubkey.address);
5275
5874
  if (!exists) {
5276
- console.warn(tag, "Pubkey not found in current pubkeys array");
5875
+ console.warn(tag6, "Pubkey not found in current pubkeys array");
5277
5876
  }
5278
5877
  this.pubkeyContext = pubkey;
5279
- console.log(tag, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5878
+ console.log(tag6, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5280
5879
  return true;
5281
5880
  } catch (e) {
5282
- console.error(tag, "e: ", e);
5881
+ console.error(tag6, "e: ", e);
5283
5882
  throw e;
5284
5883
  }
5285
5884
  };
5286
5885
  this.setOutboundAssetContext = async function(asset) {
5287
- const tag = `${TAG9} | setOutputAssetContext | `;
5886
+ const tag6 = `${TAG9} | setOutputAssetContext | `;
5288
5887
  try {
5289
- console.log(tag, "0. asset: ", asset);
5888
+ console.log(tag6, "0. asset: ", asset);
5290
5889
  if (!asset) {
5291
5890
  this.outboundAssetContext = null;
5292
5891
  return;
5293
5892
  }
5294
- console.log(tag, "1 asset: ", asset);
5893
+ console.log(tag6, "1 asset: ", asset);
5295
5894
  if (!asset.caip)
5296
5895
  throw Error("Invalid Asset! missing caip!");
5297
5896
  if (!asset.networkId)
5298
5897
  asset.networkId = caipToNetworkId7(asset.caip);
5299
- console.log(tag, "networkId: ", asset.networkId);
5300
- console.log(tag, "this.pubkeys: ", this.pubkeys);
5898
+ console.log(tag6, "networkId: ", asset.networkId);
5899
+ console.log(tag6, "this.pubkeys: ", this.pubkeys);
5301
5900
  const pubkey = this.pubkeys.find((p) => {
5302
5901
  if (!p.networks || !Array.isArray(p.networks))
5303
5902
  return false;
@@ -5312,23 +5911,23 @@ class SDK {
5312
5911
  let freshPriceUsd = 0;
5313
5912
  try {
5314
5913
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5315
- console.warn(tag, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5914
+ console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5316
5915
  } else {
5317
- console.log(tag, "Fetching fresh market price for:", asset.caip);
5916
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
5318
5917
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5319
- console.log(tag, "Market data response:", marketData);
5918
+ console.log(tag6, "Market data response:", marketData);
5320
5919
  if (marketData && marketData.data && marketData.data.length > 0) {
5321
5920
  freshPriceUsd = marketData.data[0];
5322
- console.log(tag, "✅ Fresh market price:", freshPriceUsd);
5921
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5323
5922
  } else {
5324
- console.warn(tag, "No market data returned for:", asset.caip);
5923
+ console.warn(tag6, "No market data returned for:", asset.caip);
5325
5924
  }
5326
5925
  }
5327
5926
  } catch (marketError) {
5328
- console.error(tag, "Error fetching market price:", marketError);
5927
+ console.error(tag6, "Error fetching market price:", marketError);
5329
5928
  }
5330
5929
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5331
- console.log(tag, "assetInfo: ", assetInfo);
5930
+ console.log(tag6, "assetInfo: ", assetInfo);
5332
5931
  if (!assetInfo) {
5333
5932
  assetInfo = {
5334
5933
  caip: asset.caip.toLowerCase(),
@@ -5346,70 +5945,70 @@ class SDK {
5346
5945
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5347
5946
  if (balance > 0 && valueUsd > 0) {
5348
5947
  priceValue = valueUsd / balance;
5349
- console.log(tag, "calculated priceUsd from valueUsd/balance:", priceValue);
5948
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5350
5949
  }
5351
5950
  }
5352
5951
  if (priceValue && priceValue > 0) {
5353
- console.log(tag, "detected priceUsd from balance:", priceValue);
5952
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
5354
5953
  assetInfo.priceUsd = priceValue;
5355
5954
  }
5356
5955
  }
5357
5956
  if (freshPriceUsd && freshPriceUsd > 0) {
5358
5957
  assetInfo.priceUsd = freshPriceUsd;
5359
- console.log(tag, "✅ Using fresh market price:", freshPriceUsd);
5958
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5360
5959
  let totalBalance = 0;
5361
5960
  let totalValueUsd = 0;
5362
- console.log(tag, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5961
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5363
5962
  for (const balanceEntry of matchingBalances) {
5364
5963
  const balance = parseFloat(balanceEntry.balance) || 0;
5365
5964
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5366
5965
  totalBalance += balance;
5367
5966
  totalValueUsd += valueUsd;
5368
- console.log(tag, ` Balance entry: ${balance} (${valueUsd} USD)`);
5967
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5369
5968
  }
5370
5969
  assetInfo.balance = totalBalance.toString();
5371
5970
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5372
- console.log(tag, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5971
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5373
5972
  }
5374
- console.log(tag, "CHECKPOINT 1");
5973
+ console.log(tag6, "CHECKPOINT 1");
5375
5974
  this.outboundAssetContext = { ...assetInfo, ...asset, ...pubkey };
5376
- console.log(tag, "CHECKPOINT 3");
5377
- console.log(tag, "outboundAssetContext: assetInfo: ", assetInfo);
5975
+ console.log(tag6, "CHECKPOINT 3");
5976
+ console.log(tag6, "outboundAssetContext: assetInfo: ", assetInfo);
5378
5977
  if (asset.caip) {
5379
5978
  this.outboundBlockchainContext = caipToNetworkId7(asset.caip);
5380
5979
  } else if (asset.networkId) {
5381
5980
  this.outboundBlockchainContext = asset.networkId;
5382
5981
  }
5383
- console.log(tag, "CHECKPOINT 4");
5982
+ console.log(tag6, "CHECKPOINT 4");
5384
5983
  this.events.emit("SET_OUTBOUND_ASSET_CONTEXT", this.outboundAssetContext);
5385
5984
  return this.outboundAssetContext;
5386
5985
  } catch (e) {
5387
- console.error(tag, "e: ", e);
5986
+ console.error(tag6, "e: ", e);
5388
5987
  throw e;
5389
5988
  }
5390
5989
  };
5391
5990
  }
5392
5991
  CheckERC20Allowance = async (params) => {
5393
- const tag = TAG9 + " | CheckERC20Allowance | ";
5992
+ const tag6 = TAG9 + " | CheckERC20Allowance | ";
5394
5993
  try {
5395
- console.log(tag, "Checking ERC20 allowance:", params);
5994
+ console.log(tag6, "Checking ERC20 allowance:", params);
5396
5995
  const result = await this.pioneer.GetTokenAllowance(params);
5397
- console.log(tag, "Allowance result:", result);
5996
+ console.log(tag6, "Allowance result:", result);
5398
5997
  return result.data;
5399
5998
  } catch (e) {
5400
- console.error(tag, "Error checking ERC20 allowance:", e);
5999
+ console.error(tag6, "Error checking ERC20 allowance:", e);
5401
6000
  throw e;
5402
6001
  }
5403
6002
  };
5404
6003
  BuildERC20ApprovalTx = async (params) => {
5405
- const tag = TAG9 + " | BuildERC20ApprovalTx | ";
6004
+ const tag6 = TAG9 + " | BuildERC20ApprovalTx | ";
5406
6005
  try {
5407
- console.log(tag, "Building ERC20 approval transaction:", params);
6006
+ console.log(tag6, "Building ERC20 approval transaction:", params);
5408
6007
  const result = await this.pioneer.BuildApprovalTransaction(params);
5409
- console.log(tag, "Approval tx built:", result);
6008
+ console.log(tag6, "Approval tx built:", result);
5410
6009
  return result.data;
5411
6010
  } catch (e) {
5412
- console.error(tag, "Error building approval transaction:", e);
6011
+ console.error(tag6, "Error building approval transaction:", e);
5413
6012
  throw e;
5414
6013
  }
5415
6014
  };