@pioneer-platform/pioneer-sdk 8.11.12 → 8.11.14

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.cjs CHANGED
@@ -390,471 +390,10 @@ class Pioneer {
390
390
 
391
391
  // src/index.ts
392
392
  var import_pioneer_coins4 = require("@pioneer-platform/pioneer-coins");
393
- var import_pioneer_discovery2 = require("@pioneer-platform/pioneer-discovery");
393
+ var import_pioneer_discovery = require("@pioneer-platform/pioneer-discovery");
394
394
  var import_pioneer_events = require("@pioneer-platform/pioneer-events");
395
395
  var import_events = __toESM(require("events"));
396
396
 
397
- // src/charts/utils.ts
398
- var import_pioneer_discovery = require("@pioneer-platform/pioneer-discovery");
399
- function hydrateAssetData(caip) {
400
- return import_pioneer_discovery.assetData[caip] || import_pioneer_discovery.assetData[caip.toLowerCase()];
401
- }
402
- function checkDuplicateBalance(balances, caip, pubkey, validator) {
403
- return balances.some((b) => b.caip === caip && b.pubkey === pubkey && (!validator || b.validator === validator));
404
- }
405
- function createBalanceIdentifier(caip, pubkey) {
406
- return `${caip}:${pubkey}`;
407
- }
408
-
409
- // src/charts/custom-tokens.ts
410
- var tag = "| charts-custom-tokens |";
411
- async function fetchCustomTokens(params, balances) {
412
- const { pioneer, pubkeys, blockchains, context } = params;
413
- console.log(tag, "Fetching custom tokens...");
414
- const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
415
- const primaryAddress = evmPubkey?.address || evmPubkey?.master;
416
- if (!primaryAddress) {
417
- console.log(tag, "No EVM address found, skipping custom tokens");
418
- return;
419
- }
420
- console.log(tag, "Using EVM address for custom tokens:", primaryAddress);
421
- const supportedNetworks = blockchains.filter((net) => net.startsWith("eip155:"));
422
- if (supportedNetworks.length === 0) {
423
- console.log(tag, "No EVM networks for custom tokens");
424
- return;
425
- }
426
- console.log(tag, `Checking custom tokens on ${supportedNetworks.length} networks`);
427
- for (const networkId of supportedNetworks) {
428
- try {
429
- const response = await pioneer.GetCustomTokens({ networkId, userAddress: primaryAddress });
430
- const customTokens = response?.data?.tokens || [];
431
- console.log(tag, `Found ${customTokens.length} custom tokens on ${networkId}`);
432
- for (const token of customTokens) {
433
- const chartBalance = processCustomToken(token, primaryAddress, context, blockchains);
434
- if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
435
- balances.push(chartBalance);
436
- console.log(tag, `Added custom token: ${chartBalance.symbol} = ${chartBalance.balance}`);
437
- }
438
- }
439
- } catch (error) {
440
- console.error(tag, `Error fetching custom tokens for ${networkId}:`, error.message);
441
- }
442
- }
443
- console.log(tag, `Custom tokens complete. Total balances: ${balances.length}`);
444
- }
445
- function processCustomToken(token, primaryAddress, context, blockchains) {
446
- if (!token.assetCaip || !token.networkId) {
447
- return null;
448
- }
449
- let extractedNetworkId = token.networkId;
450
- if (token.assetCaip.includes("/denom:")) {
451
- const parts = token.assetCaip.split("/denom:");
452
- if (parts.length > 0) {
453
- extractedNetworkId = parts[0];
454
- }
455
- } else if (token.networkId && token.networkId.includes("/")) {
456
- extractedNetworkId = token.networkId.split("/")[0];
457
- }
458
- const isEip155 = extractedNetworkId.startsWith("eip155:");
459
- if (!isEip155 && !blockchains.includes(extractedNetworkId)) {
460
- return null;
461
- }
462
- const tokenAssetInfo = hydrateAssetData(token.assetCaip);
463
- const tokenPubkey = token.pubkey || primaryAddress;
464
- const chartBalance = {
465
- context,
466
- chart: "pioneer",
467
- contextType: context.split(":")[0],
468
- name: tokenAssetInfo?.name || token.token?.name || "Unknown Custom Token",
469
- caip: token.assetCaip,
470
- icon: tokenAssetInfo?.icon || token.token?.icon || "",
471
- pubkey: tokenPubkey,
472
- ticker: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
473
- ref: `${context}${token.assetCaip}`,
474
- identifier: createBalanceIdentifier(token.assetCaip, tokenPubkey),
475
- networkId: extractedNetworkId,
476
- symbol: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
477
- type: tokenAssetInfo?.type || "erc20",
478
- token: true,
479
- decimal: tokenAssetInfo?.decimal || token.token?.decimal,
480
- balance: token.token?.balance?.toString() || "0",
481
- priceUsd: token.token?.price || 0,
482
- valueUsd: token.token?.balanceUSD || 0,
483
- updated: new Date().getTime()
484
- };
485
- return chartBalance;
486
- }
487
-
488
- // src/charts/evm.ts
489
- var tag2 = "| charts-evm |";
490
- async function getEvmCharts(params) {
491
- const { blockchains, pioneer, pubkeys, context } = params;
492
- const balances = [];
493
- const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
494
- const primaryAddress = evmPubkey?.address || evmPubkey?.master;
495
- console.log(tag2, "Total pubkeys available:", pubkeys.length);
496
- console.log(tag2, "Blockchains to process:", blockchains);
497
- if (!primaryAddress) {
498
- console.log(tag2, "No EVM address found, skipping portfolio lookup (Zapper only supports Ethereum)");
499
- return balances;
500
- }
501
- console.log(tag2, "Using EVM address for portfolio:", primaryAddress);
502
- await fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context);
503
- await fetchCustomTokens({ blockchains, pioneer, pubkeys, context }, balances);
504
- try {
505
- let portfolio = await pioneer.GetPortfolio({
506
- networkId: "eip155:1",
507
- address: primaryAddress
508
- });
509
- portfolio = portfolio.data?.data || portfolio.data;
510
- if (!portfolio || !portfolio.balances) {
511
- console.error(tag2, "No portfolio.balances found:", portfolio);
512
- return balances;
513
- }
514
- console.log(tag2, `Portfolio returned ${portfolio.balances.length} balances`);
515
- let processedCount = 0;
516
- let skippedCount = 0;
517
- for (const balance of portfolio.balances) {
518
- const processedBalance = processPortfolioBalance(balance, primaryAddress, context, blockchains);
519
- if (processedBalance) {
520
- if (!checkDuplicateBalance(balances, processedBalance.caip, processedBalance.pubkey)) {
521
- balances.push(processedBalance);
522
- processedCount++;
523
- }
524
- } else {
525
- skippedCount++;
526
- }
527
- }
528
- console.log(tag2, `Processed ${processedCount} balances, skipped ${skippedCount}`);
529
- if (portfolio.tokens && portfolio.tokens.length > 0) {
530
- console.log(tag2, "Processing portfolio.tokens:", portfolio.tokens.length);
531
- for (const token of portfolio.tokens) {
532
- const processedToken = processPortfolioToken(token, primaryAddress, context, blockchains);
533
- if (processedToken && !checkDuplicateBalance(balances, processedToken.caip, processedToken.pubkey)) {
534
- balances.push(processedToken);
535
- }
536
- }
537
- }
538
- } catch (e) {
539
- console.error(tag2, "Error fetching portfolio:", e);
540
- }
541
- return balances;
542
- }
543
- function processPortfolioBalance(balance, primaryAddress, context, blockchains) {
544
- if (!balance.caip) {
545
- console.error(tag2, "No caip found for:", balance);
546
- return null;
547
- }
548
- const networkId = balance.caip.split("/")[0];
549
- const isEip155 = networkId.startsWith("eip155:");
550
- if (!isEip155 && !blockchains.includes(networkId)) {
551
- return null;
552
- }
553
- const assetInfo = hydrateAssetData(balance.caip);
554
- const balancePubkey = balance.pubkey || primaryAddress;
555
- const balanceType = assetInfo?.type || balance.type || "native";
556
- const isToken = balanceType !== "native" && balance.caip.includes("/erc20:");
557
- let calculatedPrice = balance.priceUsd || balance.price || 0;
558
- if ((!calculatedPrice || calculatedPrice === 0) && balance.valueUsd && balance.balance) {
559
- const balanceNum = parseFloat(balance.balance.toString());
560
- const valueNum = parseFloat(balance.valueUsd.toString());
561
- if (balanceNum > 0 && valueNum > 0) {
562
- calculatedPrice = valueNum / balanceNum;
563
- console.log(tag2, `Calculated price from value/balance: ${calculatedPrice} for ${balance.caip}`);
564
- }
565
- }
566
- const chartBalance = {
567
- context,
568
- chart: "pioneer",
569
- contextType: "keepkey",
570
- name: assetInfo?.name || balance.name || "Unknown",
571
- caip: balance.caip,
572
- icon: assetInfo?.icon || balance.icon || "",
573
- pubkey: balancePubkey,
574
- ticker: assetInfo?.symbol || balance.symbol || "UNK",
575
- ref: `${context}${balance.caip}`,
576
- identifier: createBalanceIdentifier(balance.caip, balancePubkey),
577
- networkId,
578
- chain: networkId,
579
- symbol: assetInfo?.symbol || balance.symbol || "UNK",
580
- type: balanceType,
581
- token: isToken,
582
- decimal: assetInfo?.decimal || balance.decimal,
583
- balance: balance.balance.toString(),
584
- price: calculatedPrice,
585
- priceUsd: calculatedPrice,
586
- valueUsd: balance.valueUsd.toString(),
587
- updated: new Date().getTime()
588
- };
589
- if (balance.display) {
590
- chartBalance.icon = ["multi", chartBalance.icon, balance.display.toString()].toString();
591
- }
592
- return chartBalance;
593
- }
594
- function processPortfolioToken(token, primaryAddress, context, blockchains) {
595
- if (!token.assetCaip || !token.networkId) {
596
- return null;
597
- }
598
- let extractedNetworkId = token.networkId;
599
- if (token.assetCaip.includes("/denom:")) {
600
- const parts = token.assetCaip.split("/denom:");
601
- if (parts.length > 0) {
602
- extractedNetworkId = parts[0];
603
- }
604
- } else if (token.networkId && token.networkId.includes("/")) {
605
- extractedNetworkId = token.networkId.split("/")[0];
606
- }
607
- const isEip155 = extractedNetworkId.startsWith("eip155:");
608
- if (!isEip155 && !blockchains.includes(extractedNetworkId)) {
609
- return null;
610
- }
611
- const tokenAssetInfo = hydrateAssetData(token.assetCaip);
612
- const tokenPubkey = token.pubkey || primaryAddress;
613
- const chartBalance = {
614
- context,
615
- chart: "pioneer",
616
- contextType: context.split(":")[0],
617
- name: tokenAssetInfo?.name || token.token?.coingeckoId || token.token?.name || "Unknown",
618
- caip: token.assetCaip,
619
- icon: tokenAssetInfo?.icon || token.token?.icon || "",
620
- pubkey: tokenPubkey,
621
- ticker: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
622
- ref: `${context}${token.assetCaip}`,
623
- identifier: createBalanceIdentifier(token.assetCaip, tokenPubkey),
624
- networkId: extractedNetworkId,
625
- symbol: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
626
- type: tokenAssetInfo?.type || "token",
627
- token: true,
628
- decimal: tokenAssetInfo?.decimal || token.token?.decimal,
629
- balance: token.token?.balance?.toString() || "0",
630
- priceUsd: token.token?.price || 0,
631
- valueUsd: token.token?.balanceUSD || 0,
632
- updated: new Date().getTime()
633
- };
634
- return chartBalance;
635
- }
636
- async function fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context) {
637
- console.log(tag2, "Fetching stable coins for redundancy...");
638
- const supportedNetworks = ["eip155:1", "eip155:137", "eip155:8453", "eip155:56"];
639
- const networksToCheck = blockchains.filter((net) => supportedNetworks.includes(net));
640
- if (networksToCheck.length === 0) {
641
- console.log(tag2, "No supported networks for stable coins");
642
- return;
643
- }
644
- console.log(tag2, `Checking stable coins on ${networksToCheck.length} networks`);
645
- for (const networkId of networksToCheck) {
646
- try {
647
- const response = await pioneer.GetStableCoins({ networkId, address: primaryAddress });
648
- const stableCoins = response?.data?.tokens || [];
649
- console.log(tag2, `Found ${stableCoins.length} stable coins on ${networkId}`);
650
- for (const token of stableCoins) {
651
- const chartBalance = processPortfolioToken(token, primaryAddress, context, blockchains);
652
- if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
653
- balances.push(chartBalance);
654
- console.log(tag2, `Added stable coin: ${chartBalance.symbol} = ${chartBalance.balance}`);
655
- }
656
- }
657
- } catch (error) {
658
- console.error(tag2, `Error fetching stable coins for ${networkId}:`, error.message);
659
- }
660
- }
661
- console.log(tag2, `Stable coin redundancy complete. Total balances: ${balances.length}`);
662
- }
663
-
664
- // src/charts/maya.ts
665
- var tag3 = "| charts-maya |";
666
- async function getMayaCharts(params, existingBalances) {
667
- const { blockchains, pioneer, pubkeys, context } = params;
668
- const balances = [];
669
- try {
670
- const mayaPubkey = pubkeys.find((p) => p.networks && Array.isArray(p.networks) && p.networks.includes("cosmos:mayachain-mainnet-v1"));
671
- if (!mayaPubkey || !mayaPubkey.address) {
672
- console.log(tag3, "No MAYA pubkey found, skipping MAYA token fetch");
673
- return balances;
674
- }
675
- if (!blockchains.includes("cosmos:mayachain-mainnet-v1")) {
676
- console.log(tag3, "MAYA network not in blockchains list, skipping MAYA token fetch");
677
- return balances;
678
- }
679
- const hasMayaToken = existingBalances.some((b) => b.caip === "cosmos:mayachain-mainnet-v1/denom:maya");
680
- if (hasMayaToken) {
681
- console.log(tag3, "MAYA token already exists in balances, skipping");
682
- return balances;
683
- }
684
- console.log(tag3, "MAYA token not found in portfolio, fetching separately...");
685
- console.log(tag3, "MAYA pubkey address:", mayaPubkey.address);
686
- const mayaBalanceResponse = await pioneer.GetPortfolioBalances([
687
- {
688
- caip: "cosmos:mayachain-mainnet-v1/denom:maya",
689
- pubkey: mayaPubkey.address
690
- }
691
- ]);
692
- console.log(tag3, "MAYA balance response:", JSON.stringify(mayaBalanceResponse?.data, null, 2));
693
- if (!mayaBalanceResponse?.data || mayaBalanceResponse.data.length === 0) {
694
- console.log(tag3, "No MAYA token balance returned from GetPortfolioBalances API");
695
- return balances;
696
- }
697
- console.log(tag3, "Found MAYA token balances:", mayaBalanceResponse.data.length);
698
- for (const mayaBalance of mayaBalanceResponse.data) {
699
- if (mayaBalance.caip !== "cosmos:mayachain-mainnet-v1/denom:maya") {
700
- console.log(tag3, "Unexpected balance in MAYA response:", mayaBalance);
701
- continue;
702
- }
703
- const mayaAssetInfo = hydrateAssetData(mayaBalance.caip);
704
- const isToken = mayaBalance.caip.includes("/denom:") && !mayaBalance.caip.endsWith("/denom:cacao");
705
- const mayaTokenBalance = {
706
- context,
707
- chart: "pioneer",
708
- contextType: context.split(":")[0],
709
- name: mayaAssetInfo?.name || "Maya Token",
710
- caip: mayaBalance.caip,
711
- icon: mayaAssetInfo?.icon || "https://pioneers.dev/coins/maya.png",
712
- pubkey: mayaPubkey.address,
713
- ticker: mayaAssetInfo?.symbol || "MAYA",
714
- ref: `${context}${mayaBalance.caip}`,
715
- identifier: createBalanceIdentifier(mayaBalance.caip, mayaPubkey.address),
716
- networkId: "cosmos:mayachain-mainnet-v1",
717
- symbol: mayaAssetInfo?.symbol || "MAYA",
718
- type: mayaAssetInfo?.type || "token",
719
- token: isToken,
720
- decimal: mayaAssetInfo?.decimal,
721
- balance: mayaBalance.balance?.toString() || "0",
722
- priceUsd: parseFloat(mayaBalance.priceUsd) || 0,
723
- valueUsd: parseFloat(mayaBalance.valueUsd) || 0,
724
- updated: new Date().getTime()
725
- };
726
- console.log(tag3, "Adding MAYA token to balances:", mayaTokenBalance);
727
- balances.push(mayaTokenBalance);
728
- }
729
- } catch (mayaError) {
730
- console.error(tag3, "Error fetching MAYA token balance:", mayaError);
731
- }
732
- return balances;
733
- }
734
-
735
- // src/charts/cosmos-staking.ts
736
- var tag4 = "| charts-cosmos-staking |";
737
- async function getCosmosStakingCharts(params) {
738
- const { blockchains, pioneer, pubkeys, context } = params;
739
- const balances = [];
740
- try {
741
- console.log(tag4, "Adding Cosmos staking positions to charts...");
742
- const cosmosPubkeys = pubkeys.filter((p) => p.networks && Array.isArray(p.networks) && p.networks.some((n) => n.includes("cosmos:cosmoshub") || n.includes("cosmos:osmosis")));
743
- if (cosmosPubkeys.length === 0) {
744
- console.log(tag4, "No cosmos pubkeys found for staking positions");
745
- return balances;
746
- }
747
- console.log(tag4, "Found cosmos pubkeys for staking:", cosmosPubkeys.length);
748
- for (const cosmosPubkey of cosmosPubkeys) {
749
- if (!cosmosPubkey.address) {
750
- continue;
751
- }
752
- const cosmosNetworks = cosmosPubkey.networks.filter((n) => n.includes("cosmos:cosmoshub") || n.includes("cosmos:osmosis"));
753
- for (const networkId of cosmosNetworks) {
754
- if (!blockchains.includes(networkId)) {
755
- continue;
756
- }
757
- await fetchStakingPositionsForNetwork(networkId, cosmosPubkey.address, context, pioneer, balances);
758
- }
759
- }
760
- } catch (e) {
761
- console.error(tag4, "Error adding cosmos staking positions:", e);
762
- }
763
- return balances;
764
- }
765
- async function fetchStakingPositionsForNetwork(networkId, address, context, pioneer, balances) {
766
- try {
767
- console.log(tag4, `Fetching staking positions for ${address} on ${networkId}...`);
768
- let network;
769
- if (networkId === "cosmos:cosmoshub-4") {
770
- network = "cosmos";
771
- } else if (networkId === "cosmos:osmosis-1") {
772
- network = "osmosis";
773
- } else {
774
- console.error(tag4, `Unsupported networkId for staking: ${networkId}`);
775
- return;
776
- }
777
- const stakingResponse = await pioneer.GetStakingPositions({
778
- network,
779
- address
780
- });
781
- if (!stakingResponse?.data || !Array.isArray(stakingResponse.data)) {
782
- console.log(tag4, `No staking positions found for ${address} on ${networkId}`);
783
- return;
784
- }
785
- console.log(tag4, `Found ${stakingResponse.data.length} staking positions for ${networkId}`);
786
- for (const position of stakingResponse.data) {
787
- const processedPosition = processStakingPosition(position, address, context, networkId);
788
- if (processedPosition && !checkDuplicateBalance(balances, processedPosition.caip, processedPosition.pubkey, processedPosition.validator)) {
789
- balances.push(processedPosition);
790
- console.log(tag4, `Added ${position.type} position:`, {
791
- balance: processedPosition.balance,
792
- ticker: processedPosition.ticker,
793
- valueUsd: processedPosition.valueUsd,
794
- validator: processedPosition.validator
795
- });
796
- }
797
- }
798
- } catch (stakingError) {
799
- console.error(tag4, `Error fetching staking positions for ${address} on ${networkId}:`, stakingError);
800
- }
801
- }
802
- function processStakingPosition(position, address, context, networkId) {
803
- if (!position.balance || position.balance <= 0 || !position.caip) {
804
- return null;
805
- }
806
- const stakingAssetInfo = hydrateAssetData(position.caip);
807
- const stakingBalance = {
808
- context,
809
- chart: "staking",
810
- contextType: context.split(":")[0],
811
- name: stakingAssetInfo?.name || position.name || `${position.type} Position`,
812
- caip: position.caip,
813
- icon: stakingAssetInfo?.icon || position.icon || "",
814
- pubkey: address,
815
- ticker: stakingAssetInfo?.symbol || position.ticker || position.symbol || "UNK",
816
- ref: `${context}${position.caip}`,
817
- identifier: createBalanceIdentifier(position.caip, address),
818
- networkId,
819
- symbol: stakingAssetInfo?.symbol || position.symbol || position.ticker || "UNK",
820
- type: stakingAssetInfo?.type || position.type || "staking",
821
- token: false,
822
- decimal: stakingAssetInfo?.decimal,
823
- balance: position.balance.toString(),
824
- priceUsd: position.priceUsd || 0,
825
- valueUsd: position.valueUsd || position.balance * (position.priceUsd || 0),
826
- status: position.status || "active",
827
- validator: position.validatorAddress || position.validator || "",
828
- updated: new Date().getTime()
829
- };
830
- return stakingBalance;
831
- }
832
-
833
- // src/charts/index.ts
834
- var tag5 = "| getCharts |";
835
- var getCharts = async (blockchains, pioneer, pubkeys, context) => {
836
- try {
837
- const balances = [];
838
- console.log(tag5, "init");
839
- const params = {
840
- blockchains,
841
- pioneer,
842
- pubkeys,
843
- context
844
- };
845
- const evmBalances = await getEvmCharts(params);
846
- balances.push(...evmBalances);
847
- const mayaBalances = await getMayaCharts(params, balances);
848
- balances.push(...mayaBalances);
849
- const stakingBalances = await getCosmosStakingCharts(params);
850
- balances.push(...stakingBalances);
851
- return balances;
852
- } catch (error) {
853
- console.error(tag5, "Error processing charts:", error);
854
- throw error;
855
- }
856
- };
857
-
858
397
  // src/getPubkey.ts
859
398
  var import_pioneer_caip = require("@pioneer-platform/pioneer-caip");
860
399
  var import_pioneer_coins = require("@pioneer-platform/pioneer-coins");
@@ -1419,7 +958,7 @@ async function fetchTokenPriceInUsd(pioneer, caip) {
1419
958
  }
1420
959
  }
1421
960
  async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, feeLevel = 5) {
1422
- const tag6 = TAG2 + " | createUnsignedEvmTx | ";
961
+ const tag = TAG2 + " | createUnsignedEvmTx | ";
1423
962
  try {
1424
963
  if (!pioneer)
1425
964
  throw new Error("Failed to initialize Pioneer");
@@ -1440,11 +979,11 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1440
979
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
1441
980
  }
1442
981
  const address = pubkeyContext.address || pubkeyContext.pubkey;
1443
- console.log(tag6, "✅ Using FROM address from pubkeyContext:", address, "note:", pubkeyContext.note);
982
+ console.log(tag, "✅ Using FROM address from pubkeyContext:", address, "note:", pubkeyContext.note);
1444
983
  if (!address)
1445
984
  throw new Error("No address found for the specified network");
1446
985
  const gasPriceData = await pioneer.GetGasPriceByNetwork({ networkId });
1447
- console.log(tag6, "Gas price data from API:", JSON.stringify(gasPriceData.data));
986
+ console.log(tag, "Gas price data from API:", JSON.stringify(gasPriceData.data));
1448
987
  let gasPrice;
1449
988
  const defaultGasPrices = {
1450
989
  1: 30,
@@ -1460,75 +999,75 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1460
999
  let selectedGasPrice;
1461
1000
  if (feeLevel <= 2) {
1462
1001
  selectedGasPrice = gasPriceData.data.slow || gasPriceData.data.average || gasPriceData.data.fastest;
1463
- console.log(tag6, "Selecting SLOW gas price from API");
1002
+ console.log(tag, "Selecting SLOW gas price from API");
1464
1003
  } else if (feeLevel >= 8) {
1465
1004
  selectedGasPrice = gasPriceData.data.fastest || gasPriceData.data.fast || gasPriceData.data.average;
1466
- console.log(tag6, "Selecting FAST gas price from API");
1005
+ console.log(tag, "Selecting FAST gas price from API");
1467
1006
  } else {
1468
1007
  selectedGasPrice = gasPriceData.data.average || gasPriceData.data.fast || gasPriceData.data.fastest;
1469
- console.log(tag6, "Selecting AVERAGE gas price from API");
1008
+ console.log(tag, "Selecting AVERAGE gas price from API");
1470
1009
  }
1471
1010
  let gasPriceNum;
1472
1011
  if (selectedGasPrice === undefined || selectedGasPrice === null) {
1473
- console.warn(tag6, "No valid gas price found in API response, using fallback:", fallbackGasGwei, "gwei");
1012
+ console.warn(tag, "No valid gas price found in API response, using fallback:", fallbackGasGwei, "gwei");
1474
1013
  gasPriceNum = fallbackGasGwei;
1475
1014
  } else {
1476
1015
  gasPriceNum = typeof selectedGasPrice === "string" ? parseFloat(selectedGasPrice) : selectedGasPrice;
1477
1016
  if (isNaN(gasPriceNum) || !isFinite(gasPriceNum)) {
1478
- console.warn(tag6, "Invalid gas price (NaN or Infinite):", selectedGasPrice, "- using fallback:", fallbackGasGwei, "gwei");
1017
+ console.warn(tag, "Invalid gas price (NaN or Infinite):", selectedGasPrice, "- using fallback:", fallbackGasGwei, "gwei");
1479
1018
  gasPriceNum = fallbackGasGwei;
1480
1019
  }
1481
1020
  }
1482
1021
  gasPrice = BigInt(Math.round(gasPriceNum * 1e9));
1483
1022
  if (gasPrice < MIN_GAS_PRICE_WEI) {
1484
- console.warn(tag6, "Gas price from API too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1023
+ console.warn(tag, "Gas price from API too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1485
1024
  gasPrice = MIN_GAS_PRICE_WEI;
1486
1025
  }
1487
1026
  } else {
1488
1027
  let gasPriceNum;
1489
1028
  if (gasPriceData.data === undefined || gasPriceData.data === null) {
1490
- console.warn(tag6, "Gas price API returned null/undefined, using fallback:", fallbackGasGwei, "gwei");
1029
+ console.warn(tag, "Gas price API returned null/undefined, using fallback:", fallbackGasGwei, "gwei");
1491
1030
  gasPriceNum = fallbackGasGwei;
1492
1031
  } else {
1493
1032
  gasPriceNum = typeof gasPriceData.data === "string" ? parseFloat(gasPriceData.data) : gasPriceData.data;
1494
1033
  if (isNaN(gasPriceNum) || !isFinite(gasPriceNum)) {
1495
- console.warn(tag6, "Invalid gas price (NaN or Infinite):", gasPriceData.data, "- using fallback:", fallbackGasGwei, "gwei");
1034
+ console.warn(tag, "Invalid gas price (NaN or Infinite):", gasPriceData.data, "- using fallback:", fallbackGasGwei, "gwei");
1496
1035
  gasPriceNum = fallbackGasGwei;
1497
1036
  }
1498
1037
  }
1499
1038
  const baseGasPrice = BigInt(Math.round(gasPriceNum * 1e9));
1500
1039
  if (feeLevel <= 2) {
1501
1040
  gasPrice = baseGasPrice * BigInt(80) / BigInt(100);
1502
- console.log(tag6, "Using SLOW gas price (80% of base)");
1041
+ console.log(tag, "Using SLOW gas price (80% of base)");
1503
1042
  } else if (feeLevel >= 8) {
1504
1043
  gasPrice = baseGasPrice * BigInt(150) / BigInt(100);
1505
- console.log(tag6, "Using FAST gas price (150% of base)");
1044
+ console.log(tag, "Using FAST gas price (150% of base)");
1506
1045
  } else {
1507
1046
  gasPrice = baseGasPrice;
1508
- console.log(tag6, "Using AVERAGE gas price (100% of base)");
1047
+ console.log(tag, "Using AVERAGE gas price (100% of base)");
1509
1048
  }
1510
1049
  if (gasPrice < MIN_GAS_PRICE_WEI) {
1511
- console.warn(tag6, "Gas price too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1050
+ console.warn(tag, "Gas price too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1512
1051
  gasPrice = MIN_GAS_PRICE_WEI;
1513
1052
  }
1514
1053
  }
1515
- console.log(tag6, "Final gasPrice:", gasPrice.toString(), "wei (", Number(gasPrice) / 1e9, "gwei)");
1054
+ console.log(tag, "Final gasPrice:", gasPrice.toString(), "wei (", Number(gasPrice) / 1e9, "gwei)");
1516
1055
  let nonce;
1517
1056
  try {
1518
1057
  const nonceData = await pioneer.GetNonceByNetwork({ networkId, address });
1519
1058
  nonce = nonceData.data.nonce;
1520
1059
  if (nonce === undefined || nonce === null) {
1521
- console.log(tag6, "No nonce found for address (likely fresh address), defaulting to 0");
1060
+ console.log(tag, "No nonce found for address (likely fresh address), defaulting to 0");
1522
1061
  nonce = 0;
1523
1062
  }
1524
1063
  } catch (nonceError) {
1525
- console.log(tag6, "Failed to fetch nonce (likely fresh address):", nonceError.message, "- defaulting to 0");
1064
+ console.log(tag, "Failed to fetch nonce (likely fresh address):", nonceError.message, "- defaulting to 0");
1526
1065
  nonce = 0;
1527
1066
  }
1528
1067
  const balanceData = await pioneer.GetBalanceAddressByNetwork({ networkId, address });
1529
1068
  const balanceEth = parseFloat(balanceData.data.nativeBalance || balanceData.data.balance || "0");
1530
1069
  const balance = BigInt(Math.round(balanceEth * 1000000000000000000));
1531
- console.log(tag6, "Native ETH balance from API:", balanceData.data.nativeBalance || balanceData.data.balance, "ETH (", balance.toString(), "wei)");
1070
+ console.log(tag, "Native ETH balance from API:", balanceData.data.nativeBalance || balanceData.data.balance, "ETH (", balance.toString(), "wei)");
1532
1071
  if (balance <= 0n)
1533
1072
  throw new Error("Wallet balance is zero");
1534
1073
  const assetType = classifyCaipEvm(caip);
@@ -1541,7 +1080,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1541
1080
  let gasLimit;
1542
1081
  if (isThorchainOperation) {
1543
1082
  gasLimit = BigInt(120000);
1544
- console.log(tag6, "Using higher gas limit for THORChain swap:", gasLimit.toString());
1083
+ console.log(tag, "Using higher gas limit for THORChain swap:", gasLimit.toString());
1545
1084
  } else {
1546
1085
  gasLimit = chainId === 1 ? BigInt(21000) : BigInt(25000);
1547
1086
  }
@@ -1557,7 +1096,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1557
1096
  }
1558
1097
  const buffer = BigInt(100);
1559
1098
  amountWei = balance - gasFee - buffer;
1560
- console.log(tag6, "isMax calculation - balance:", balance.toString(), "gasFee:", gasFee.toString(), "buffer:", buffer.toString(), "amountWei:", amountWei.toString());
1099
+ console.log(tag, "isMax calculation - balance:", balance.toString(), "gasFee:", gasFee.toString(), "buffer:", buffer.toString(), "amountWei:", amountWei.toString());
1561
1100
  } else {
1562
1101
  amountWei = BigInt(Math.round(amount * 1000000000000000000));
1563
1102
  if (amountWei + gasFee > balance) {
@@ -1567,14 +1106,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1567
1106
  const isThorchainSwap = memo && (memo.startsWith("=") || memo.startsWith("SWAP") || memo.includes(":"));
1568
1107
  let txData = "0x";
1569
1108
  if (isThorchainSwap) {
1570
- console.log(tag6, "Detected THORChain swap, encoding deposit data for memo:", memo);
1109
+ console.log(tag, "Detected THORChain swap, encoding deposit data for memo:", memo);
1571
1110
  let fixedMemo = memo;
1572
1111
  if (memo.startsWith("=:b:") || memo.startsWith("=:btc:")) {
1573
1112
  fixedMemo = memo.replace(/^=:(b|btc):/, "=:BTC.BTC:");
1574
- console.log(tag6, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
1113
+ console.log(tag, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
1575
1114
  } else if (memo.startsWith("=:e:") || memo.startsWith("=:eth:")) {
1576
1115
  fixedMemo = memo.replace(/^=:(e|eth):/, "=:ETH.ETH:");
1577
- console.log(tag6, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
1116
+ console.log(tag, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
1578
1117
  }
1579
1118
  if (fixedMemo.length > 250) {
1580
1119
  throw new Error(`Memo too long for THORChain: ${fixedMemo.length} bytes (max 250)`);
@@ -1590,14 +1129,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1590
1129
  if (ethInbound) {
1591
1130
  vaultAddress = ethInbound.address;
1592
1131
  routerAddress = ethInbound.router || to;
1593
- console.log(tag6, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
1132
+ console.log(tag, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
1594
1133
  to = routerAddress;
1595
1134
  } else {
1596
1135
  throw new Error("ETH inbound is halted or not found - cannot proceed with swap");
1597
1136
  }
1598
1137
  }
1599
1138
  } catch (fetchError) {
1600
- console.error(tag6, "Failed to fetch inbound addresses:", fetchError);
1139
+ console.error(tag, "Failed to fetch inbound addresses:", fetchError);
1601
1140
  throw new Error(`Cannot proceed with THORChain swap - failed to fetch inbound addresses: ${fetchError.message}`);
1602
1141
  }
1603
1142
  if (vaultAddress === "0x0000000000000000000000000000000000000000") {
@@ -1617,7 +1156,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1617
1156
  const paddingLength = (32 - memoBytes.length % 32) % 32;
1618
1157
  const memoPadded = memoHex + "0".repeat(paddingLength * 2);
1619
1158
  txData = "0x" + functionSelector + vaultPadded + assetPadded + amountPadded + stringOffset + expiryPadded + stringLength + memoPadded;
1620
- console.log(tag6, "Encoded THORChain depositWithExpiry data:", {
1159
+ console.log(tag, "Encoded THORChain depositWithExpiry data:", {
1621
1160
  functionSelector: "0x" + functionSelector,
1622
1161
  vault: vaultAddress,
1623
1162
  asset: assetAddress,
@@ -1627,9 +1166,9 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1627
1166
  stringOffset: "0x" + stringOffset,
1628
1167
  fullData: txData
1629
1168
  });
1630
- console.log(tag6, "Native ETH swap - value will be set to:", amountWei.toString(), "wei");
1169
+ console.log(tag, "Native ETH swap - value will be set to:", amountWei.toString(), "wei");
1631
1170
  } catch (error) {
1632
- console.error(tag6, "Error encoding THORChain deposit:", error);
1171
+ console.error(tag, "Error encoding THORChain deposit:", error);
1633
1172
  throw new Error(`Failed to encode THORChain swap: ${error.message}`);
1634
1173
  }
1635
1174
  } else if (memo) {
@@ -1648,19 +1187,19 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1648
1187
  }
1649
1188
  case "erc20": {
1650
1189
  const contractAddress = extractContractAddressFromCaip(caip);
1651
- console.log(tag6, "Fetching token decimals from contract:", contractAddress, "on network:", networkId);
1190
+ console.log(tag, "Fetching token decimals from contract:", contractAddress, "on network:", networkId);
1652
1191
  let tokenDecimals;
1653
1192
  try {
1654
- console.log(tag6, "Fetching token decimals via pioneer-server API for", contractAddress, "on", networkId);
1193
+ console.log(tag, "Fetching token decimals via pioneer-server API for", contractAddress, "on", networkId);
1655
1194
  const decimalsResponse = await pioneer.GetTokenDecimals({
1656
1195
  networkId,
1657
1196
  contractAddress
1658
1197
  });
1659
1198
  tokenDecimals = Number(decimalsResponse.data.decimals);
1660
- console.log(tag6, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
1199
+ console.log(tag, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
1661
1200
  } catch (error) {
1662
- console.error(tag6, "Failed to fetch token decimals from pioneer-server:", error);
1663
- console.warn(tag6, "⚠️ FALLBACK: Using default 18 decimals - THIS MAY BE INCORRECT!");
1201
+ console.error(tag, "Failed to fetch token decimals from pioneer-server:", error);
1202
+ console.warn(tag, "⚠️ FALLBACK: Using default 18 decimals - THIS MAY BE INCORRECT!");
1664
1203
  tokenDecimals = 18;
1665
1204
  }
1666
1205
  const tokenMultiplier = 10n ** BigInt(tokenDecimals);
@@ -1681,7 +1220,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1681
1220
  amountWei = tokenBalance;
1682
1221
  } else {
1683
1222
  amountWei = BigInt(Math.round(amount * Number(tokenMultiplier)));
1684
- console.log(tag6, "Token amount calculation:", {
1223
+ console.log(tag, "Token amount calculation:", {
1685
1224
  inputAmount: amount,
1686
1225
  decimals: tokenDecimals,
1687
1226
  multiplier: tokenMultiplier,
@@ -1717,23 +1256,23 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1717
1256
  }
1718
1257
  if (pubkeyContext.addressNListMaster) {
1719
1258
  unsignedTx.addressNList = pubkeyContext.addressNListMaster;
1720
- console.log(tag6, "✅ Using addressNListMaster from pubkey context:", unsignedTx.addressNList, "for address:", address);
1259
+ console.log(tag, "✅ Using addressNListMaster from pubkey context:", unsignedTx.addressNList, "for address:", address);
1721
1260
  } else if (pubkeyContext.pathMaster) {
1722
1261
  unsignedTx.addressNList = import_pioneer_coins2.bip32ToAddressNList(pubkeyContext.pathMaster);
1723
- console.log(tag6, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
1262
+ console.log(tag, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
1724
1263
  } else if (pubkeyContext.addressNList) {
1725
1264
  unsignedTx.addressNList = pubkeyContext.addressNList;
1726
- console.log(tag6, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
1265
+ console.log(tag, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
1727
1266
  } else if (pubkeyContext.path) {
1728
1267
  unsignedTx.addressNList = import_pioneer_coins2.bip32ToAddressNList(pubkeyContext.path);
1729
- console.log(tag6, "⚠️ Using regular path (not master):", pubkeyContext.path, "→", unsignedTx.addressNList);
1268
+ console.log(tag, "⚠️ Using regular path (not master):", pubkeyContext.path, "→", unsignedTx.addressNList);
1730
1269
  } else {
1731
1270
  unsignedTx.addressNList = [2147483648 + 44, 2147483648 + 60, 2147483648, 0, 0];
1732
- console.warn(tag6, "⚠️ No path info in pubkey context, using default account 0");
1271
+ console.warn(tag, "⚠️ No path info in pubkey context, using default account 0");
1733
1272
  }
1734
1273
  return unsignedTx;
1735
1274
  } catch (error) {
1736
- console.error(tag6, "Error:", error.message);
1275
+ console.error(tag, "Error:", error.message);
1737
1276
  throw error;
1738
1277
  }
1739
1278
  }
@@ -1742,7 +1281,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1742
1281
  var import_pioneer_caip3 = require("@pioneer-platform/pioneer-caip");
1743
1282
  var TAG3 = " | createUnsignedUxtoTx | ";
1744
1283
  async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax) {
1745
- let tag6 = TAG3 + " | createUnsignedRippleTx | ";
1284
+ let tag = TAG3 + " | createUnsignedRippleTx | ";
1746
1285
  try {
1747
1286
  if (!pioneer)
1748
1287
  throw new Error("Failed to init! pioneer");
@@ -1753,7 +1292,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
1753
1292
  if (!pubkeyContext.networks?.includes(networkId)) {
1754
1293
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
1755
1294
  }
1756
- console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
1295
+ console.log(tag, `✅ Using pubkeyContext for network ${networkId}:`, {
1757
1296
  address: pubkeyContext.address
1758
1297
  });
1759
1298
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
@@ -1821,7 +1360,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
1821
1360
  };
1822
1361
  return unsignedTx;
1823
1362
  } catch (error) {
1824
- console.error(tag6, "Error:", error);
1363
+ console.error(tag, "Error:", error);
1825
1364
  throw error;
1826
1365
  }
1827
1366
  }
@@ -1961,7 +1500,7 @@ var thorchainDepositTemplate = (params) => ({
1961
1500
  // src/txbuilder/createUnsignedTendermintTx.ts
1962
1501
  var TAG4 = " | createUnsignedTendermintTx | ";
1963
1502
  async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, to) {
1964
- const tag6 = TAG4 + " | createUnsignedTendermintTx | ";
1503
+ const tag = TAG4 + " | createUnsignedTendermintTx | ";
1965
1504
  try {
1966
1505
  if (!pioneer)
1967
1506
  throw new Error("Failed to init! pioneer");
@@ -1972,7 +1511,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
1972
1511
  if (!pubkeyContext.networks?.includes(networkId)) {
1973
1512
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
1974
1513
  }
1975
- console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
1514
+ console.log(tag, `✅ Using pubkeyContext for network ${networkId}:`, {
1976
1515
  address: pubkeyContext.address,
1977
1516
  addressNList: pubkeyContext.addressNList || pubkeyContext.addressNListMaster
1978
1517
  });
@@ -1995,11 +1534,11 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
1995
1534
  }
1996
1535
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
1997
1536
  let asset = caip.split(":")[1];
1998
- console.log(tag6, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
1537
+ console.log(tag, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
1999
1538
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
2000
- console.log(tag6, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
1539
+ console.log(tag, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
2001
1540
  let balanceInfo = await pioneer.GetPubkeyBalance({ asset: chain, pubkey: fromAddress });
2002
- console.log(tag6, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
1541
+ console.log(tag, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
2003
1542
  let account_number, sequence;
2004
1543
  if (accountInfo.account) {
2005
1544
  account_number = accountInfo.account.account_number || "0";
@@ -2010,13 +1549,13 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2010
1549
  } else {
2011
1550
  throw new Error(`Unexpected account info format for ${networkId}: ${JSON.stringify(accountInfo)}`);
2012
1551
  }
2013
- console.log(tag6, `\uD83D\uDCCA Extracted account_number: ${account_number}, sequence: ${sequence}`);
1552
+ console.log(tag, `\uD83D\uDCCA Extracted account_number: ${account_number}, sequence: ${sequence}`);
2014
1553
  if (account_number === "0" || account_number === 0) {
2015
- console.log(tag6, `⚠️ WARNING: Account number is 0 from Pioneer API`);
2016
- console.log(tag6, ` This is likely due to stale Pioneer API cache`);
2017
- console.log(tag6, ` The mayachain-network module queries nodes directly but Pioneer API may be cached`);
2018
- console.log(tag6, ` Proceeding with account_number: 0 but transaction will likely fail`);
2019
- console.log(tag6, ` TODO: Fix Pioneer API to use fresh data from mayachain-network module`);
1554
+ console.log(tag, `⚠️ WARNING: Account number is 0 from Pioneer API`);
1555
+ console.log(tag, ` This is likely due to stale Pioneer API cache`);
1556
+ console.log(tag, ` The mayachain-network module queries nodes directly but Pioneer API may be cached`);
1557
+ console.log(tag, ` Proceeding with account_number: 0 but transaction will likely fail`);
1558
+ console.log(tag, ` TODO: Fix Pioneer API to use fresh data from mayachain-network module`);
2020
1559
  }
2021
1560
  const fees = {
2022
1561
  "cosmos:thorchain-mainnet-v1": 0.02,
@@ -2171,7 +1710,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2171
1710
  }
2172
1711
  }
2173
1712
  } catch (error) {
2174
- console.error(tag6, "Error:", error);
1713
+ console.error(tag, "Error:", error);
2175
1714
  throw error;
2176
1715
  }
2177
1716
  }
@@ -2200,7 +1739,7 @@ function getCoinTypeFromNetworkId(networkId) {
2200
1739
  return coinType;
2201
1740
  }
2202
1741
  async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, feeLevel = 5, changeScriptType) {
2203
- let tag6 = " | createUnsignedUxtoTx | ";
1742
+ let tag = " | createUnsignedUxtoTx | ";
2204
1743
  try {
2205
1744
  if (!pioneer)
2206
1745
  throw Error("Failed to init! pioneer");
@@ -2211,7 +1750,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2211
1750
  if (!pubkeyContext.networks?.includes(networkId)) {
2212
1751
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2213
1752
  }
2214
- console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
1753
+ console.log(tag, `✅ Using pubkeyContext for network ${networkId}:`, {
2215
1754
  address: pubkeyContext.address,
2216
1755
  scriptType: pubkeyContext.scriptType
2217
1756
  });
@@ -2222,15 +1761,15 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2222
1761
  const isSegwit = segwitNetworks.includes(networkId);
2223
1762
  let chain = import_pioneer_caip5.NetworkIdToChain[networkId];
2224
1763
  const coinType = getCoinTypeFromNetworkId(networkId);
2225
- console.log(`${tag6}: Using SLIP-44 coin type ${coinType} for ${chain}`);
1764
+ console.log(`${tag}: Using SLIP-44 coin type ${coinType} for ${chain}`);
2226
1765
  const utxos = [];
2227
1766
  for (const pubkey of relevantPubkeys) {
2228
1767
  try {
2229
1768
  let utxosResp = await pioneer.ListUnspent({ network: chain, xpub: pubkey.pubkey });
2230
1769
  utxosResp = utxosResp.data;
2231
- console.log(`${tag6}: ListUnspent response for ${pubkey.scriptType}:`, utxosResp?.length || 0, "UTXOs");
1770
+ console.log(`${tag}: ListUnspent response for ${pubkey.scriptType}:`, utxosResp?.length || 0, "UTXOs");
2232
1771
  if (!utxosResp || !Array.isArray(utxosResp)) {
2233
- console.warn(`${tag6}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
1772
+ console.warn(`${tag}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
2234
1773
  continue;
2235
1774
  }
2236
1775
  let scriptType = pubkey.scriptType;
@@ -2239,10 +1778,10 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2239
1778
  }
2240
1779
  utxos.push(...utxosResp);
2241
1780
  } catch (error) {
2242
- console.error(`${tag6}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
1781
+ console.error(`${tag}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
2243
1782
  }
2244
1783
  }
2245
- console.log(`${tag6}: Total UTXOs collected:`, utxos.length);
1784
+ console.log(`${tag}: Total UTXOs collected:`, utxos.length);
2246
1785
  if (!utxos || utxos.length === 0)
2247
1786
  throw Error("No UTXOs found across all addresses");
2248
1787
  for (const utxo of utxos) {
@@ -2255,14 +1794,14 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2255
1794
  }, {});
2256
1795
  const mostCommonInputType = Object.entries(scriptTypeCount).sort(([, a], [, b]) => b - a)[0]?.[0] || "p2pkh";
2257
1796
  const actualChangeScriptType = changeScriptType || mostCommonInputType || relevantPubkeys[0]?.scriptType || "p2pkh";
2258
- console.log(`${tag6}: Input script types:`, scriptTypeCount);
2259
- console.log(`${tag6}: Using change script type: ${actualChangeScriptType} (matches inputs: ${mostCommonInputType})`);
1797
+ console.log(`${tag}: Input script types:`, scriptTypeCount);
1798
+ console.log(`${tag}: Using change script type: ${actualChangeScriptType} (matches inputs: ${mostCommonInputType})`);
2260
1799
  const changeXpubInfo = relevantPubkeys.find((pk) => pk.scriptType === actualChangeScriptType);
2261
1800
  if (!changeXpubInfo) {
2262
1801
  throw new Error(`No ${actualChangeScriptType} xpub available for change address. ` + `Available types: ${relevantPubkeys.map((pk) => pk.scriptType).join(", ")}. ` + `Cannot create change output with mismatched script type.`);
2263
1802
  }
2264
1803
  const changeXpub = changeXpubInfo.pubkey;
2265
- console.log(`${tag6}: Change xpub selected for ${actualChangeScriptType}:`, changeXpub?.substring(0, 10) + "...");
1804
+ console.log(`${tag}: Change xpub selected for ${actualChangeScriptType}:`, changeXpub?.substring(0, 10) + "...");
2266
1805
  let changeAddressIndex = await pioneer.GetChangeAddress({
2267
1806
  network: chain,
2268
1807
  xpub: changeXpub
@@ -2282,7 +1821,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2282
1821
  break;
2283
1822
  }
2284
1823
  const path = bipPath;
2285
- console.log(`${tag6}: Change address path: ${path} (coin type: ${coinType}, index: ${changeAddressIndex})`);
1824
+ console.log(`${tag}: Change address path: ${path} (coin type: ${coinType}, index: ${changeAddressIndex})`);
2286
1825
  const changeAddress = {
2287
1826
  path,
2288
1827
  isChange: true,
@@ -2292,7 +1831,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2292
1831
  };
2293
1832
  let feeRateFromNode;
2294
1833
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
2295
- console.log(`${tag6}: Using hardcoded fees for DOGE (10 sat/byte)`);
1834
+ console.log(`${tag}: Using hardcoded fees for DOGE (10 sat/byte)`);
2296
1835
  feeRateFromNode = {
2297
1836
  slow: 10,
2298
1837
  average: 10,
@@ -2305,19 +1844,19 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2305
1844
  try {
2306
1845
  let feeResponse;
2307
1846
  if (pioneer.GetFeeRateByNetwork) {
2308
- console.log(`${tag6}: Trying GetFeeRateByNetwork for ${networkId}`);
1847
+ console.log(`${tag}: Trying GetFeeRateByNetwork for ${networkId}`);
2309
1848
  feeResponse = await pioneer.GetFeeRateByNetwork({ networkId });
2310
1849
  } else {
2311
- console.log(`${tag6}: Using GetFeeRate for ${networkId}`);
1850
+ console.log(`${tag}: Using GetFeeRate for ${networkId}`);
2312
1851
  feeResponse = await pioneer.GetFeeRate({ networkId });
2313
1852
  }
2314
1853
  feeRateFromNode = feeResponse.data;
2315
- console.log(`${tag6}: Got fee rates from API:`, JSON.stringify(feeRateFromNode, null, 2));
1854
+ console.log(`${tag}: Got fee rates from API:`, JSON.stringify(feeRateFromNode, null, 2));
2316
1855
  const conversionThreshold = 500;
2317
1856
  const needsConversion = feeRateFromNode.slow && feeRateFromNode.slow > conversionThreshold || feeRateFromNode.average && feeRateFromNode.average > conversionThreshold || feeRateFromNode.fast && feeRateFromNode.fast > conversionThreshold || feeRateFromNode.fastest && feeRateFromNode.fastest > conversionThreshold;
2318
1857
  if (needsConversion) {
2319
- console.warn(`${tag6}: Detected wrong units - values appear to be in sat/kB instead of sat/byte`);
2320
- console.warn(`${tag6}: Original values:`, {
1858
+ console.warn(`${tag}: Detected wrong units - values appear to be in sat/kB instead of sat/byte`);
1859
+ console.warn(`${tag}: Original values:`, {
2321
1860
  slow: feeRateFromNode.slow,
2322
1861
  average: feeRateFromNode.average,
2323
1862
  fast: feeRateFromNode.fast,
@@ -2331,12 +1870,12 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2331
1870
  feeRateFromNode.fast = feeRateFromNode.fast / 1000;
2332
1871
  if (feeRateFromNode.fastest)
2333
1872
  feeRateFromNode.fastest = feeRateFromNode.fastest / 1000;
2334
- console.warn(`${tag6}: Converted to sat/byte:`, feeRateFromNode);
1873
+ console.warn(`${tag}: Converted to sat/byte:`, feeRateFromNode);
2335
1874
  }
2336
1875
  if (!feeRateFromNode || typeof feeRateFromNode !== "object") {
2337
1876
  throw new Error(`Invalid fee rate response from API: ${JSON.stringify(feeRateFromNode)}`);
2338
1877
  }
2339
- console.log(`${tag6}: Available fee rates:`, {
1878
+ console.log(`${tag}: Available fee rates:`, {
2340
1879
  slow: feeRateFromNode.slow,
2341
1880
  average: feeRateFromNode.average,
2342
1881
  fast: feeRateFromNode.fast,
@@ -2346,33 +1885,33 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2346
1885
  throw new Error(`No valid fee rates in API response: ${JSON.stringify(feeRateFromNode)}`);
2347
1886
  }
2348
1887
  } catch (error) {
2349
- console.error(`${tag6}: Failed to get fee rates from Pioneer API:`, error.message || error);
1888
+ console.error(`${tag}: Failed to get fee rates from Pioneer API:`, error.message || error);
2350
1889
  throw new Error(`Unable to get fee rate for network ${networkId}: ${error.message || "API unavailable"}`);
2351
1890
  }
2352
1891
  }
2353
1892
  let effectiveFeeRate;
2354
- console.log(`${tag6}: Using fee level ${feeLevel}`);
1893
+ console.log(`${tag}: Using fee level ${feeLevel}`);
2355
1894
  switch (feeLevel) {
2356
1895
  case 1:
2357
1896
  case 2:
2358
1897
  effectiveFeeRate = feeRateFromNode.slow || feeRateFromNode.average;
2359
- console.log(`${tag6}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
1898
+ console.log(`${tag}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
2360
1899
  break;
2361
1900
  case 3:
2362
1901
  case 4:
2363
1902
  effectiveFeeRate = feeRateFromNode.average || feeRateFromNode.fast;
2364
- console.log(`${tag6}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
1903
+ console.log(`${tag}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
2365
1904
  break;
2366
1905
  case 5:
2367
1906
  effectiveFeeRate = feeRateFromNode.fastest || feeRateFromNode.fast;
2368
- console.log(`${tag6}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
1907
+ console.log(`${tag}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
2369
1908
  break;
2370
1909
  default:
2371
1910
  throw new Error(`Invalid fee level: ${feeLevel}. Must be 1-5`);
2372
1911
  }
2373
1912
  if (!effectiveFeeRate)
2374
1913
  throw new Error("Unable to get fee rate for network");
2375
- console.log(`${tag6}: Using fee rate from API:`, {
1914
+ console.log(`${tag}: Using fee rate from API:`, {
2376
1915
  feeLevel,
2377
1916
  selectedRate: effectiveFeeRate,
2378
1917
  description: feeLevel <= 2 ? "slow" : feeLevel <= 4 ? "average" : "fast"
@@ -2382,22 +1921,22 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2382
1921
  effectiveFeeRate = Math.ceil(effectiveFeeRate);
2383
1922
  const MIN_RELAY_FEE_RATE = 3;
2384
1923
  if (effectiveFeeRate < MIN_RELAY_FEE_RATE) {
2385
- console.log(`${tag6}: Fee rate ${effectiveFeeRate} is below minimum relay fee, increasing to ${MIN_RELAY_FEE_RATE} sat/vB`);
1924
+ console.log(`${tag}: Fee rate ${effectiveFeeRate} is below minimum relay fee, increasing to ${MIN_RELAY_FEE_RATE} sat/vB`);
2386
1925
  effectiveFeeRate = MIN_RELAY_FEE_RATE;
2387
1926
  }
2388
- console.log(`${tag6}: Final fee rate to use (rounded, with minimums): ${effectiveFeeRate} sat/vB`);
1927
+ console.log(`${tag}: Final fee rate to use (rounded, with minimums): ${effectiveFeeRate} sat/vB`);
2389
1928
  amount = parseInt(String(amount * 1e8));
2390
1929
  if (amount <= 0 && !isMax)
2391
1930
  throw Error("Invalid amount! 0");
2392
1931
  const totalBalance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
2393
- console.log(`${tag6}: Coin selection inputs:`, {
1932
+ console.log(`${tag}: Coin selection inputs:`, {
2394
1933
  utxoCount: utxos.length,
2395
1934
  totalBalance: totalBalance / 1e8,
2396
1935
  requestedAmount: amount / 1e8,
2397
1936
  isMax,
2398
1937
  feeRate: effectiveFeeRate
2399
1938
  });
2400
- console.log(`${tag6}: UTXO details for coin selection:`, utxos.map((u) => ({
1939
+ console.log(`${tag}: UTXO details for coin selection:`, utxos.map((u) => ({
2401
1940
  value: u.value,
2402
1941
  txid: u.txid?.substring(0, 10) + "...",
2403
1942
  vout: u.vout,
@@ -2411,8 +1950,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2411
1950
  } else {
2412
1951
  result = import_coinselect.default(utxos, [{ address: to, value: amount }], effectiveFeeRate);
2413
1952
  }
2414
- console.log(tag6, "coinSelect result object:", result);
2415
- console.log(tag6, "coinSelect result.inputs:", result?.inputs);
1953
+ console.log(tag, "coinSelect result object:", result);
1954
+ console.log(tag, "coinSelect result.inputs:", result?.inputs);
2416
1955
  if (!result || !result.inputs) {
2417
1956
  const errorDetails = {
2418
1957
  utxoCount: utxos.length,
@@ -2421,7 +1960,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2421
1960
  feeRate: effectiveFeeRate,
2422
1961
  insufficientFunds: totalBalance < amount
2423
1962
  };
2424
- console.error(`${tag6}: Coin selection failed:`, errorDetails);
1963
+ console.error(`${tag}: Coin selection failed:`, errorDetails);
2425
1964
  if (utxos.length === 0) {
2426
1965
  throw Error("No UTXOs available for coin selection");
2427
1966
  } else if (totalBalance < amount) {
@@ -2437,7 +1976,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2437
1976
  throw Error("Failed to create transaction: Missing outputs");
2438
1977
  if (fee === undefined)
2439
1978
  throw Error("Failed to calculate transaction fee");
2440
- console.log(`${tag6}: Transaction built with:`, {
1979
+ console.log(`${tag}: Transaction built with:`, {
2441
1980
  feeLevel,
2442
1981
  effectiveFeeRate: `${effectiveFeeRate} sat/vB`,
2443
1982
  calculatedFee: `${fee} satoshis`,
@@ -2445,8 +1984,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2445
1984
  outputCount: outputs.length
2446
1985
  });
2447
1986
  const uniqueInputSet = new Set;
2448
- console.log(tag6, "inputs:", inputs);
2449
- console.log(tag6, "inputs:", inputs[0]);
1987
+ console.log(tag, "inputs:", inputs);
1988
+ console.log(tag, "inputs:", inputs[0]);
2450
1989
  const preparedInputs = inputs.map(transformInput).filter(({ hash, index }) => uniqueInputSet.has(`${hash}:${index}`) ? false : uniqueInputSet.add(`${hash}:${index}`)).map(({ value, index, hash, txHex, path: path2, scriptType }) => ({
2451
1990
  addressNList: import_pioneer_coins3.bip32ToAddressNList(path2),
2452
1991
  scriptType,
@@ -2575,7 +2114,7 @@ class TransactionManager {
2575
2114
  throw new Error(`Unsupported CAIP: ${caipString}`);
2576
2115
  }
2577
2116
  async transfer({ caip, to, amount, memo, isMax = false, feeLevel = 5, changeScriptType }) {
2578
- let tag6 = TAG5 + " | transfer | ";
2117
+ let tag = TAG5 + " | transfer | ";
2579
2118
  try {
2580
2119
  if (!this.pioneer)
2581
2120
  throw Error("Failed to init! pioneer");
@@ -2613,12 +2152,12 @@ class TransactionManager {
2613
2152
  }
2614
2153
  return unsignedTx;
2615
2154
  } catch (e) {
2616
- console.error(tag6, e);
2155
+ console.error(tag, e);
2617
2156
  throw e;
2618
2157
  }
2619
2158
  }
2620
2159
  async sign({ caip, unsignedTx }) {
2621
- let tag6 = TAG5 + " | sign | ";
2160
+ let tag = TAG5 + " | sign | ";
2622
2161
  try {
2623
2162
  if (!this.pioneer)
2624
2163
  throw Error("Failed to init! pioneer");
@@ -2704,20 +2243,20 @@ class TransactionManager {
2704
2243
  }
2705
2244
  case "cosmos:mayachain-mainnet-v1/slip44:931":
2706
2245
  case "cosmos:mayachain-mainnet-v1/denom:maya": {
2707
- console.log(tag6, "\uD83D\uDD0D ===== MAYACHAIN SIGNING AUDIT =====");
2708
- console.log(tag6, "\uD83D\uDCCB unsignedTx:", JSON.stringify(unsignedTx, null, 2));
2709
- console.log(tag6, "\uD83D\uDD11 unsignedTx.addressNList:", unsignedTx.addressNList);
2710
- console.log(tag6, "\uD83D\uDCCD unsignedTx.signerAddress:", unsignedTx.signerAddress);
2711
- console.log(tag6, "\uD83C\uDF10 pubkeyContext:", this.pubkeyContext);
2712
- console.log(tag6, "\uD83D\uDD10 pubkeyContext.addressNList:", this.pubkeyContext?.addressNList);
2713
- console.log(tag6, "\uD83D\uDD10 pubkeyContext.addressNListMaster:", this.pubkeyContext?.addressNListMaster);
2714
- console.log(tag6, "\uD83D\uDCEC pubkeyContext.address:", this.pubkeyContext?.address);
2715
- console.log(tag6, "=======================================");
2246
+ console.log(tag, "\uD83D\uDD0D ===== MAYACHAIN SIGNING AUDIT =====");
2247
+ console.log(tag, "\uD83D\uDCCB unsignedTx:", JSON.stringify(unsignedTx, null, 2));
2248
+ console.log(tag, "\uD83D\uDD11 unsignedTx.addressNList:", unsignedTx.addressNList);
2249
+ console.log(tag, "\uD83D\uDCCD unsignedTx.signerAddress:", unsignedTx.signerAddress);
2250
+ console.log(tag, "\uD83C\uDF10 pubkeyContext:", this.pubkeyContext);
2251
+ console.log(tag, "\uD83D\uDD10 pubkeyContext.addressNList:", this.pubkeyContext?.addressNList);
2252
+ console.log(tag, "\uD83D\uDD10 pubkeyContext.addressNListMaster:", this.pubkeyContext?.addressNListMaster);
2253
+ console.log(tag, "\uD83D\uDCEC pubkeyContext.address:", this.pubkeyContext?.address);
2254
+ console.log(tag, "=======================================");
2716
2255
  if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgSend") {
2717
2256
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoTransfer(unsignedTx);
2718
2257
  signedTx = responseSign.serialized;
2719
- console.log(tag6, "✅ Signing completed");
2720
- console.log(tag6, "\uD83D\uDCE6 responseSign:", responseSign);
2258
+ console.log(tag, "✅ Signing completed");
2259
+ console.log(tag, "\uD83D\uDCE6 responseSign:", responseSign);
2721
2260
  } else if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgDeposit") {
2722
2261
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoDeposit(unsignedTx);
2723
2262
  signedTx = responseSign.serialized;
@@ -2739,11 +2278,11 @@ class TransactionManager {
2739
2278
  if (serialized.length > 140) {
2740
2279
  signedTx = serialized;
2741
2280
  } else {
2742
- console.error(tag6, "EIP155 signing returned incomplete transaction - only signature components");
2281
+ console.error(tag, "EIP155 signing returned incomplete transaction - only signature components");
2743
2282
  throw new Error("KeepKey returned incomplete transaction - cannot reconstruct without r,s,v components");
2744
2283
  }
2745
2284
  } else {
2746
- console.error(tag6, "EIP155 signing failed - no valid signature in response:", responseSign);
2285
+ console.error(tag, "EIP155 signing failed - no valid signature in response:", responseSign);
2747
2286
  throw new Error("Failed to sign transaction - no valid signature in response");
2748
2287
  }
2749
2288
  break;
@@ -2764,19 +2303,19 @@ class TransactionManager {
2764
2303
  }
2765
2304
  }
2766
2305
  if (!signedTx) {
2767
- console.error(tag6, "CRITICAL ERROR: signedTx is missing after signing process");
2768
- console.error(tag6, "CAIP:", caip);
2769
- console.error(tag6, "Type:", type);
2306
+ console.error(tag, "CRITICAL ERROR: signedTx is missing after signing process");
2307
+ console.error(tag, "CAIP:", caip);
2308
+ console.error(tag, "Type:", type);
2770
2309
  throw Error("Failed to sign! missing signedTx");
2771
2310
  }
2772
2311
  return signedTx;
2773
2312
  } catch (e) {
2774
- console.error(tag6, e);
2313
+ console.error(tag, e);
2775
2314
  throw e;
2776
2315
  }
2777
2316
  }
2778
2317
  async broadcast({ networkId, serialized }) {
2779
- let tag6 = TAG5 + " | broadcast | ";
2318
+ let tag = TAG5 + " | broadcast | ";
2780
2319
  try {
2781
2320
  if (!this.pioneer)
2782
2321
  throw Error("Failed to init! pioneer");
@@ -2790,7 +2329,7 @@ class TransactionManager {
2790
2329
  return result.txid;
2791
2330
  }
2792
2331
  } catch (e) {
2793
- console.error(tag6, e);
2332
+ console.error(tag, e);
2794
2333
  throw e;
2795
2334
  }
2796
2335
  }
@@ -2910,7 +2449,7 @@ var cosmosClaimAllRewardsTemplate = (params) => ({
2910
2449
  // src/txbuilder/createUnsignedStakingTx.ts
2911
2450
  var TAG6 = " | createUnsignedStakingTx | ";
2912
2451
  async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyContext) {
2913
- const tag6 = TAG6 + " | createUnsignedStakingTx | ";
2452
+ const tag = TAG6 + " | createUnsignedStakingTx | ";
2914
2453
  try {
2915
2454
  if (!pioneer)
2916
2455
  throw new Error("Failed to init! pioneer");
@@ -2921,7 +2460,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
2921
2460
  if (!pubkeyContext.networks?.includes(networkId)) {
2922
2461
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2923
2462
  }
2924
- console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2463
+ console.log(tag, `✅ Using pubkeyContext for network ${networkId}:`, {
2925
2464
  address: pubkeyContext.address
2926
2465
  });
2927
2466
  let chain;
@@ -2953,10 +2492,10 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
2953
2492
  default:
2954
2493
  throw new Error(`Unsupported networkId for staking: ${networkId}`);
2955
2494
  }
2956
- console.log(tag6, `Building ${params.type} transaction for ${chain}`);
2495
+ console.log(tag, `Building ${params.type} transaction for ${chain}`);
2957
2496
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
2958
2497
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
2959
- console.log(tag6, "accountInfo: ", accountInfo);
2498
+ console.log(tag, "accountInfo: ", accountInfo);
2960
2499
  let account_number;
2961
2500
  let sequence;
2962
2501
  if (networkId === "cosmos:cosmoshub-4" || networkId === "cosmos:osmosis-1") {
@@ -3038,7 +2577,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3038
2577
  throw new Error(`Unsupported staking transaction type: ${params.type}`);
3039
2578
  }
3040
2579
  } catch (error) {
3041
- console.error(tag6, "Error:", error);
2580
+ console.error(tag, "Error:", error);
3042
2581
  throw error;
3043
2582
  }
3044
2583
  }
@@ -3084,16 +2623,16 @@ function withTimeout(promise, timeoutMs) {
3084
2623
  ]);
3085
2624
  }
3086
2625
  async function getFees(pioneer, networkId) {
3087
- const tag6 = TAG7 + " | getFees | ";
2626
+ const tag = TAG7 + " | getFees | ";
3088
2627
  try {
3089
- console.log(tag6, `Fetching fees for network: ${networkId}`);
2628
+ console.log(tag, `Fetching fees for network: ${networkId}`);
3090
2629
  const networkType = getNetworkType(networkId);
3091
2630
  if (networkType === "COSMOS") {
3092
- console.log(tag6, "Using hardcoded fees for Cosmos network:", networkId);
2631
+ console.log(tag, "Using hardcoded fees for Cosmos network:", networkId);
3093
2632
  return getCosmosFees(networkId);
3094
2633
  }
3095
2634
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
3096
- console.log(tag6, "Using hardcoded fees for Dogecoin: 10 sat/byte");
2635
+ console.log(tag, "Using hardcoded fees for Dogecoin: 10 sat/byte");
3097
2636
  return {
3098
2637
  slow: {
3099
2638
  label: "Slow",
@@ -3130,7 +2669,7 @@ async function getFees(pioneer, networkId) {
3130
2669
  const apiCall = pioneer.GetFeeRateByNetwork ? pioneer.GetFeeRateByNetwork({ networkId }) : pioneer.GetFeeRate({ networkId });
3131
2670
  feeResponse = await withTimeout(apiCall, 3000);
3132
2671
  } catch (timeoutError) {
3133
- console.warn(tag6, "Dash fee API timeout, using fallback fees");
2672
+ console.warn(tag, "Dash fee API timeout, using fallback fees");
3134
2673
  return {
3135
2674
  slow: {
3136
2675
  label: "Economy",
@@ -3163,10 +2702,10 @@ async function getFees(pioneer, networkId) {
3163
2702
  }
3164
2703
  } else {
3165
2704
  if (networkType === "EVM") {
3166
- console.log(tag6, "Using GetGasPriceByNetwork for EVM network:", networkId);
2705
+ console.log(tag, "Using GetGasPriceByNetwork for EVM network:", networkId);
3167
2706
  feeResponse = await (pioneer.GetGasPriceByNetwork ? pioneer.GetGasPriceByNetwork({ networkId }) : Promise.reject(new Error("GetGasPriceByNetwork not available")));
3168
2707
  } else {
3169
- console.log(tag6, "Using GetFeeRateByNetwork for UTXO network:", networkId);
2708
+ console.log(tag, "Using GetFeeRateByNetwork for UTXO network:", networkId);
3170
2709
  feeResponse = await (pioneer.GetFeeRateByNetwork ? pioneer.GetFeeRateByNetwork({ networkId }) : pioneer.GetFeeRate({ networkId }));
3171
2710
  }
3172
2711
  }
@@ -3174,17 +2713,17 @@ async function getFees(pioneer, networkId) {
3174
2713
  throw new Error(`No fee data returned for ${networkId}`);
3175
2714
  }
3176
2715
  const feeData = feeResponse.data;
3177
- console.log(tag6, "Raw fee data:", feeData);
2716
+ console.log(tag, "Raw fee data:", feeData);
3178
2717
  const networkName = getNetworkName(networkId);
3179
2718
  let normalizedFees = normalizeFeeData(feeData, networkType, networkName, networkId);
3180
2719
  normalizedFees = ensureFeeDifferentiation(normalizedFees, networkType);
3181
2720
  normalizedFees.networkId = networkId;
3182
2721
  normalizedFees.networkType = networkType;
3183
2722
  normalizedFees.raw = feeData;
3184
- console.log(tag6, "Normalized fees:", normalizedFees);
2723
+ console.log(tag, "Normalized fees:", normalizedFees);
3185
2724
  return normalizedFees;
3186
2725
  } catch (error) {
3187
- console.error(tag6, "Failed to fetch fees:", error);
2726
+ console.error(tag, "Failed to fetch fees:", error);
3188
2727
  return getFallbackFees(networkId);
3189
2728
  }
3190
2729
  }
@@ -3493,7 +3032,7 @@ function estimateTransactionFee(feeRate, unit, networkType, txSize) {
3493
3032
 
3494
3033
  // src/utils/kkapi-detection.ts
3495
3034
  async function detectKkApiAvailability(forceLocalhost) {
3496
- const tag6 = " | detectKkApiAvailability | ";
3035
+ const tag = " | detectKkApiAvailability | ";
3497
3036
  try {
3498
3037
  const isTauri = typeof window !== "undefined" && "__TAURI__" in window;
3499
3038
  const isBrowser = typeof window !== "undefined";
@@ -3652,11 +3191,11 @@ function buildDashboardFromBalances(balances, blockchains, assetsMap) {
3652
3191
  // src/utils/sync-market.ts
3653
3192
  var TAG8 = " | sync-market | ";
3654
3193
  async function syncMarket(balances, pioneer) {
3655
- const tag6 = `${TAG8} | syncMarket | `;
3194
+ const tag = `${TAG8} | syncMarket | `;
3656
3195
  try {
3657
3196
  const invalidBalances = balances.filter((b) => !b || !b.caip || typeof b.caip !== "string" || !b.caip.includes(":"));
3658
3197
  if (invalidBalances.length > 0) {
3659
- console.warn(tag6, `Found ${invalidBalances.length} balances with invalid CAIPs:`, invalidBalances.map((b) => ({
3198
+ console.warn(tag, `Found ${invalidBalances.length} balances with invalid CAIPs:`, invalidBalances.map((b) => ({
3660
3199
  caip: b?.caip,
3661
3200
  type: typeof b?.caip,
3662
3201
  symbol: b?.symbol,
@@ -3671,7 +3210,7 @@ async function syncMarket(balances, pioneer) {
3671
3210
  console.log("GetMarketInfo: payload length: ", allCaips.length);
3672
3211
  const invalidEntries = allCaips.filter((caip) => typeof caip !== "string");
3673
3212
  if (invalidEntries.length > 0) {
3674
- console.error(tag6, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
3213
+ console.error(tag, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
3675
3214
  throw new Error("Invalid CAIP entries detected - aborting market sync");
3676
3215
  }
3677
3216
  if (allCaips && allCaips.length > 0) {
@@ -3692,13 +3231,13 @@ async function syncMarket(balances, pioneer) {
3692
3231
  }
3693
3232
  }
3694
3233
  } catch (apiError) {
3695
- console.error(tag6, "API error fetching market info:", apiError);
3696
- console.warn(tag6, "Continuing without market prices");
3234
+ console.error(tag, "API error fetching market info:", apiError);
3235
+ console.warn(tag, "Continuing without market prices");
3697
3236
  }
3698
3237
  }
3699
3238
  return true;
3700
3239
  } catch (e) {
3701
- console.error(tag6, "e:", e);
3240
+ console.error(tag, "e:", e);
3702
3241
  throw e;
3703
3242
  }
3704
3243
  }
@@ -3813,7 +3352,7 @@ class SDK {
3813
3352
  this.appIcon = config.appIcon || "https://pioneers.dev/coins/keepkey.png";
3814
3353
  this.spec = spec || config.spec || "https://api.keepkey.info/spec/swagger";
3815
3354
  this.wss = config.wss || "wss://pioneers.dev";
3816
- this.assets = import_pioneer_discovery2.assetData;
3355
+ this.assets = import_pioneer_discovery.assetData;
3817
3356
  this.assetsMap = new Map;
3818
3357
  this.username = config.username;
3819
3358
  this.queryKey = config.queryKey;
@@ -3891,7 +3430,7 @@ class SDK {
3891
3430
  return true;
3892
3431
  };
3893
3432
  this.setPubkeys = (newPubkeys) => {
3894
- const tag6 = `${TAG9} | setPubkeys | `;
3433
+ const tag = `${TAG9} | setPubkeys | `;
3895
3434
  this.pubkeys = [];
3896
3435
  this.pubkeySet.clear();
3897
3436
  let added = 0;
@@ -3908,7 +3447,7 @@ class SDK {
3908
3447
  this.pubkeySet.clear();
3909
3448
  }
3910
3449
  this.getUnifiedPortfolio = async function() {
3911
- const tag6 = `${TAG9} | getUnifiedPortfolio | `;
3450
+ const tag = `${TAG9} | getUnifiedPortfolio | `;
3912
3451
  try {
3913
3452
  const startTime = performance.now();
3914
3453
  try {
@@ -3919,17 +3458,17 @@ class SDK {
3919
3458
  signal: AbortSignal.timeout(2000)
3920
3459
  });
3921
3460
  if (!portfolioResponse.ok) {
3922
- console.warn(tag6, "Portfolio endpoint returned", portfolioResponse.status);
3461
+ console.warn(tag, "Portfolio endpoint returned", portfolioResponse.status);
3923
3462
  return null;
3924
3463
  }
3925
3464
  const portfolioData = await portfolioResponse.json();
3926
3465
  const loadTime = performance.now() - startTime;
3927
3466
  if (!portfolioData.success) {
3928
- console.warn(tag6, "Portfolio API returned success=false");
3467
+ console.warn(tag, "Portfolio API returned success=false");
3929
3468
  return null;
3930
3469
  }
3931
3470
  if (portfolioData.totalValueUsd === 0 || !portfolioData.totalValueUsd) {
3932
- console.warn(tag6, "Portfolio value is $0.00 - may need device connection or sync");
3471
+ console.warn(tag, "Portfolio value is $0.00 - may need device connection or sync");
3933
3472
  return null;
3934
3473
  }
3935
3474
  let allBalances = [];
@@ -4016,14 +3555,14 @@ class SDK {
4016
3555
  };
4017
3556
  } catch (fetchError) {
4018
3557
  if (fetchError.name === "AbortError") {
4019
- console.log(tag6, "Unified portfolio request timed out (this is normal if vault not running)");
3558
+ console.log(tag, "Unified portfolio request timed out (this is normal if vault not running)");
4020
3559
  } else {
4021
- console.log(tag6, "Failed to fetch unified portfolio:", fetchError.message);
3560
+ console.log(tag, "Failed to fetch unified portfolio:", fetchError.message);
4022
3561
  }
4023
3562
  return null;
4024
3563
  }
4025
3564
  } catch (e) {
4026
- console.error(tag6, "Error:", e);
3565
+ console.error(tag, "Error:", e);
4027
3566
  return null;
4028
3567
  }
4029
3568
  };
@@ -4034,7 +3573,7 @@ class SDK {
4034
3573
  return this.syncState.isSynced;
4035
3574
  };
4036
3575
  this.init = async function(walletsVerbose, setup) {
4037
- const tag6 = `${TAG9} | init | `;
3576
+ const tag = `${TAG9} | init | `;
4038
3577
  try {
4039
3578
  if (!this.username)
4040
3579
  throw Error("username required!");
@@ -4090,11 +3629,11 @@ class SDK {
4090
3629
  this.events.emit("message", request);
4091
3630
  });
4092
3631
  clientEvents.events.on("balance:update", (data) => {
4093
- const tag7 = TAG9 + " | balance:update | ";
3632
+ const tag2 = TAG9 + " | balance:update | ";
4094
3633
  try {
4095
3634
  const payload = typeof data === "string" ? JSON.parse(data) : data;
4096
3635
  const balance = payload.balance;
4097
- console.log(tag7, "Received balance update:", balance.caip);
3636
+ console.log(tag2, "Received balance update:", balance.caip);
4098
3637
  const exists = this.balances.find((b) => b.caip === balance.caip && b.pubkey === balance.pubkey);
4099
3638
  if (!exists) {
4100
3639
  this.balances.push(balance);
@@ -4104,27 +3643,27 @@ class SDK {
4104
3643
  }
4105
3644
  this.events.emit("BALANCE_UPDATE", balance);
4106
3645
  } catch (e) {
4107
- console.error(tag7, "Error processing balance update:", e);
3646
+ console.error(tag2, "Error processing balance update:", e);
4108
3647
  }
4109
3648
  });
4110
3649
  clientEvents.events.on("sync:progress", (data) => {
4111
- const tag7 = TAG9 + " | sync:progress | ";
3650
+ const tag2 = TAG9 + " | sync:progress | ";
4112
3651
  try {
4113
3652
  const payload = typeof data === "string" ? JSON.parse(data) : data;
4114
- console.log(tag7, `Sync progress: ${payload.percentage}%`);
3653
+ console.log(tag2, `Sync progress: ${payload.percentage}%`);
4115
3654
  this.syncState.syncProgress = payload.percentage;
4116
3655
  this.syncState.syncedChains = payload.completed;
4117
3656
  this.syncState.totalChains = payload.total;
4118
3657
  this.events.emit("SYNC_PROGRESS", this.syncState);
4119
3658
  } catch (e) {
4120
- console.error(tag7, "Error processing sync progress:", e);
3659
+ console.error(tag2, "Error processing sync progress:", e);
4121
3660
  }
4122
3661
  });
4123
3662
  clientEvents.events.on("sync:complete", (data) => {
4124
- const tag7 = TAG9 + " | sync:complete | ";
3663
+ const tag2 = TAG9 + " | sync:complete | ";
4125
3664
  try {
4126
3665
  const payload = typeof data === "string" ? JSON.parse(data) : data;
4127
- console.log(tag7, `Sync complete: ${payload.balances} balances in ${payload.duration}ms`);
3666
+ console.log(tag2, `Sync complete: ${payload.balances} balances in ${payload.duration}ms`);
4128
3667
  this.syncState.isSynced = true;
4129
3668
  this.syncState.isInitialSync = false;
4130
3669
  this.syncState.syncProgress = 100;
@@ -4133,7 +3672,7 @@ class SDK {
4133
3672
  this.events.emit("SYNC_COMPLETE", this.syncState);
4134
3673
  this.events.emit("SYNC_STATE_CHANGED", this.syncState);
4135
3674
  } catch (e) {
4136
- console.error(tag7, "Error processing sync complete:", e);
3675
+ console.error(tag2, "Error processing sync complete:", e);
4137
3676
  }
4138
3677
  });
4139
3678
  this.events.emit("SET_STATUS", "init");
@@ -4165,7 +3704,7 @@ class SDK {
4165
3704
  }
4166
3705
  return this.pioneer;
4167
3706
  } catch (e) {
4168
- console.error(tag6, "e: ", e);
3707
+ console.error(tag, "e: ", e);
4169
3708
  throw e;
4170
3709
  }
4171
3710
  };
@@ -4176,7 +3715,7 @@ class SDK {
4176
3715
  return syncMarket(this.balances, this.pioneer);
4177
3716
  };
4178
3717
  this.sync = async function() {
4179
- const tag6 = `${TAG9} | sync | `;
3718
+ const tag = `${TAG9} | sync | `;
4180
3719
  try {
4181
3720
  const matchesNetwork = (item, networkId) => {
4182
3721
  if (!item.networks || !Array.isArray(item.networks))
@@ -4308,7 +3847,7 @@ class SDK {
4308
3847
  this.events.emit("SYNC_COMPLETE", this.syncState);
4309
3848
  return true;
4310
3849
  } catch (e) {
4311
- console.error(tag6, "Error in sync:", e);
3850
+ console.error(tag, "Error in sync:", e);
4312
3851
  throw e;
4313
3852
  }
4314
3853
  };
@@ -4322,7 +3861,7 @@ class SDK {
4322
3861
  }
4323
3862
  };
4324
3863
  this.buildTx = async function(sendPayload) {
4325
- let tag6 = TAG9 + " | buildTx | ";
3864
+ let tag = TAG9 + " | buildTx | ";
4326
3865
  try {
4327
3866
  const transactionDependencies = {
4328
3867
  context: this.context,
@@ -4336,7 +3875,7 @@ class SDK {
4336
3875
  };
4337
3876
  let txManager = new TransactionManager(transactionDependencies, this.events);
4338
3877
  let unsignedTx = await txManager.transfer(sendPayload);
4339
- console.log(tag6, "unsignedTx: ", unsignedTx);
3878
+ console.log(tag, "unsignedTx: ", unsignedTx);
4340
3879
  return unsignedTx;
4341
3880
  } catch (e) {
4342
3881
  console.error(e);
@@ -4344,14 +3883,14 @@ class SDK {
4344
3883
  }
4345
3884
  };
4346
3885
  this.buildDelegateTx = async function(caip, params) {
4347
- let tag6 = TAG9 + " | buildDelegateTx | ";
3886
+ let tag = TAG9 + " | buildDelegateTx | ";
4348
3887
  try {
4349
3888
  const delegateParams = {
4350
3889
  ...params,
4351
3890
  type: "delegate"
4352
3891
  };
4353
3892
  let unsignedTx = await createUnsignedStakingTx(caip, delegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4354
- console.log(tag6, "unsignedTx: ", unsignedTx);
3893
+ console.log(tag, "unsignedTx: ", unsignedTx);
4355
3894
  return unsignedTx;
4356
3895
  } catch (e) {
4357
3896
  console.error(e);
@@ -4359,14 +3898,14 @@ class SDK {
4359
3898
  }
4360
3899
  };
4361
3900
  this.buildUndelegateTx = async function(caip, params) {
4362
- let tag6 = TAG9 + " | buildUndelegateTx | ";
3901
+ let tag = TAG9 + " | buildUndelegateTx | ";
4363
3902
  try {
4364
3903
  const undelegateParams = {
4365
3904
  ...params,
4366
3905
  type: "undelegate"
4367
3906
  };
4368
3907
  let unsignedTx = await createUnsignedStakingTx(caip, undelegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4369
- console.log(tag6, "unsignedTx: ", unsignedTx);
3908
+ console.log(tag, "unsignedTx: ", unsignedTx);
4370
3909
  return unsignedTx;
4371
3910
  } catch (e) {
4372
3911
  console.error(e);
@@ -4374,14 +3913,14 @@ class SDK {
4374
3913
  }
4375
3914
  };
4376
3915
  this.buildClaimRewardsTx = async function(caip, params) {
4377
- let tag6 = TAG9 + " | buildClaimRewardsTx | ";
3916
+ let tag = TAG9 + " | buildClaimRewardsTx | ";
4378
3917
  try {
4379
3918
  const claimParams = {
4380
3919
  ...params,
4381
3920
  type: "claim_rewards"
4382
3921
  };
4383
3922
  let unsignedTx = await createUnsignedStakingTx(caip, claimParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4384
- console.log(tag6, "unsignedTx: ", unsignedTx);
3923
+ console.log(tag, "unsignedTx: ", unsignedTx);
4385
3924
  return unsignedTx;
4386
3925
  } catch (e) {
4387
3926
  console.error(e);
@@ -4389,7 +3928,7 @@ class SDK {
4389
3928
  }
4390
3929
  };
4391
3930
  this.buildClaimAllRewardsTx = async function(caip, params) {
4392
- let tag6 = TAG9 + " | buildClaimAllRewardsTx | ";
3931
+ let tag = TAG9 + " | buildClaimAllRewardsTx | ";
4393
3932
  try {
4394
3933
  const claimAllParams = {
4395
3934
  ...params,
@@ -4403,7 +3942,7 @@ class SDK {
4403
3942
  }
4404
3943
  };
4405
3944
  this.signTx = async function(caip, unsignedTx) {
4406
- let tag6 = TAG9 + " | signTx | ";
3945
+ let tag = TAG9 + " | signTx | ";
4407
3946
  try {
4408
3947
  const transactionDependencies = {
4409
3948
  context: this.context,
@@ -4424,7 +3963,7 @@ class SDK {
4424
3963
  }
4425
3964
  };
4426
3965
  this.broadcastTx = async function(caip, signedTx) {
4427
- let tag6 = TAG9 + " | broadcastTx | ";
3966
+ let tag = TAG9 + " | broadcastTx | ";
4428
3967
  try {
4429
3968
  const transactionDependencies = {
4430
3969
  context: this.context,
@@ -4448,7 +3987,7 @@ class SDK {
4448
3987
  }
4449
3988
  };
4450
3989
  this.swap = async function(swapPayload) {
4451
- let tag6 = `${TAG9} | swap | `;
3990
+ let tag = `${TAG9} | swap | `;
4452
3991
  try {
4453
3992
  if (!swapPayload)
4454
3993
  throw Error("swapPayload required!");
@@ -4497,15 +4036,15 @@ class SDK {
4497
4036
  throw new Error(`Cannot use max amount: no balance found for ${swapPayload.caipIn}`);
4498
4037
  }
4499
4038
  let totalBalance = 0;
4500
- console.log(tag6, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4039
+ console.log(tag, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4501
4040
  for (const balanceEntry of inputBalances) {
4502
4041
  const balance = parseFloat(balanceEntry.balance) || 0;
4503
4042
  totalBalance += balance;
4504
- console.log(tag6, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4043
+ console.log(tag, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4505
4044
  }
4506
4045
  this.assetContext.balance = totalBalance.toString();
4507
4046
  this.assetContext.valueUsd = (totalBalance * parseFloat(this.assetContext.priceUsd || "0")).toFixed(2);
4508
- console.log(tag6, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4047
+ console.log(tag, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4509
4048
  const feeReserves = {
4510
4049
  "bip122:000000000019d6689c085ae165831e93/slip44:0": 0.00005,
4511
4050
  "eip155:1/slip44:60": 0.001,
@@ -4516,7 +4055,7 @@ class SDK {
4516
4055
  };
4517
4056
  const reserve = feeReserves[swapPayload.caipIn] || 0.0001;
4518
4057
  inputAmount = Math.max(0, totalBalance - reserve);
4519
- console.log(tag6, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4058
+ console.log(tag, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4520
4059
  } else {
4521
4060
  inputAmount = typeof swapPayload.amount === "string" ? parseFloat(swapPayload.amount) : swapPayload.amount;
4522
4061
  if (isNaN(inputAmount) || inputAmount <= 0) {
@@ -4536,7 +4075,7 @@ class SDK {
4536
4075
  result = await this.pioneer.Quote(quote);
4537
4076
  result = result.data;
4538
4077
  } catch (e) {
4539
- console.error(tag6, "Failed to get quote: ", e);
4078
+ console.error(tag, "Failed to get quote: ", e);
4540
4079
  throw Error("Quote API failed for path: " + quote.sellAsset + " -> " + quote.buyAsset + ". Error: " + e);
4541
4080
  }
4542
4081
  if (!result || result.length === 0)
@@ -4563,7 +4102,7 @@ class SDK {
4563
4102
  if (tx.type === "deposit") {
4564
4103
  unsignedTx = await createUnsignedTendermintTx(caip, tx.type, tx.txParams.amount, tx.txParams.memo, this.pubkeys, this.pioneer, this.pubkeyContext, false, undefined);
4565
4104
  } else if (tx.type === "EVM" || tx.type === "evm") {
4566
- console.log(tag6, "Using pre-built EVM transaction from integration");
4105
+ console.log(tag, "Using pre-built EVM transaction from integration");
4567
4106
  unsignedTx = tx.txParams;
4568
4107
  } else {
4569
4108
  if (!tx.txParams.memo)
@@ -4582,12 +4121,12 @@ class SDK {
4582
4121
  return unsignedTx;
4583
4122
  }
4584
4123
  } catch (e) {
4585
- console.error(tag6, "Error: ", e);
4124
+ console.error(tag, "Error: ", e);
4586
4125
  throw e;
4587
4126
  }
4588
4127
  };
4589
4128
  this.transfer = async function(sendPayload) {
4590
- let tag6 = `${TAG9} | transfer | `;
4129
+ let tag = `${TAG9} | transfer | `;
4591
4130
  try {
4592
4131
  if (!sendPayload)
4593
4132
  throw Error("sendPayload required!");
@@ -4621,15 +4160,15 @@ class SDK {
4621
4160
  return { txid, events: this.events };
4622
4161
  } catch (error) {
4623
4162
  if (error instanceof Error) {
4624
- console.error(tag6, "An error occurred during the transfer process:", error.message);
4163
+ console.error(tag, "An error occurred during the transfer process:", error.message);
4625
4164
  } else {
4626
- console.error(tag6, "An unknown error occurred during the transfer process");
4165
+ console.error(tag, "An unknown error occurred during the transfer process");
4627
4166
  }
4628
4167
  throw error;
4629
4168
  }
4630
4169
  };
4631
4170
  this.followTransaction = async function(caip, txid) {
4632
- let tag6 = " | followTransaction | ";
4171
+ let tag = " | followTransaction | ";
4633
4172
  try {
4634
4173
  const finalConfirmationBlocksByCaip = {
4635
4174
  dogecoin: 3,
@@ -4659,7 +4198,7 @@ class SDK {
4659
4198
  }
4660
4199
  }
4661
4200
  } catch (error) {
4662
- console.error(tag6, "Error:", error);
4201
+ console.error(tag, "Error:", error);
4663
4202
  }
4664
4203
  if (!isConfirmed) {
4665
4204
  await new Promise((resolve) => setTimeout(resolve, 8000));
@@ -4677,18 +4216,18 @@ class SDK {
4677
4216
  requiredConfirmations
4678
4217
  };
4679
4218
  } catch (error) {
4680
- console.error(tag6, "Error:", error);
4219
+ console.error(tag, "Error:", error);
4681
4220
  throw new Error("Failed to follow transaction");
4682
4221
  }
4683
4222
  };
4684
4223
  this.setBlockchains = async function(blockchains) {
4685
- const tag6 = `${TAG9} | setBlockchains | `;
4224
+ const tag = `${TAG9} | setBlockchains | `;
4686
4225
  try {
4687
4226
  if (!blockchains)
4688
4227
  throw Error("blockchains required!");
4689
4228
  const uniqueBlockchains = [...new Set(blockchains)];
4690
4229
  if (blockchains.length !== uniqueBlockchains.length) {
4691
- console.warn(tag6, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
4230
+ console.warn(tag, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
4692
4231
  }
4693
4232
  this.blockchains = uniqueBlockchains;
4694
4233
  this.events.emit("SET_BLOCKCHAINS", this.blockchains);
@@ -4698,12 +4237,12 @@ class SDK {
4698
4237
  }
4699
4238
  };
4700
4239
  this.addAsset = async function(caip, data) {
4701
- let tag6 = TAG9 + " | addAsset | ";
4240
+ let tag = TAG9 + " | addAsset | ";
4702
4241
  try {
4703
4242
  let success = false;
4704
4243
  if (!caip)
4705
4244
  throw new Error("caip required!");
4706
- let dataLocal = import_pioneer_discovery2.assetData[caip];
4245
+ let dataLocal = import_pioneer_discovery.assetData[caip];
4707
4246
  if (!dataLocal) {
4708
4247
  if (!data.networkId)
4709
4248
  throw new Error("networkId required! can not build asset");
@@ -4736,22 +4275,22 @@ class SDK {
4736
4275
  }
4737
4276
  };
4738
4277
  this.clearWalletState = async function() {
4739
- const tag6 = `${TAG9} | clearWalletState | `;
4278
+ const tag = `${TAG9} | clearWalletState | `;
4740
4279
  try {
4741
4280
  this.context = null;
4742
4281
  this.paths = [];
4743
4282
  this.blockchains = [];
4744
4283
  this.pubkeys = [];
4745
4284
  this.pubkeySet.clear();
4746
- console.log(tag6, "Cleared wallet state including pubkeys and tracking set");
4285
+ console.log(tag, "Cleared wallet state including pubkeys and tracking set");
4747
4286
  return true;
4748
4287
  } catch (e) {
4749
- console.error(tag6, "e: ", e);
4288
+ console.error(tag, "e: ", e);
4750
4289
  throw e;
4751
4290
  }
4752
4291
  };
4753
4292
  this.addPath = async function(path) {
4754
- const tag6 = `${TAG9} | addPath | `;
4293
+ const tag = `${TAG9} | addPath | `;
4755
4294
  try {
4756
4295
  this.paths.push(path);
4757
4296
  const pubkey = await getPubkey(path.networks[0], path, this.keepKeySdk, this.context);
@@ -4760,14 +4299,14 @@ class SDK {
4760
4299
  this.buildDashboardFromBalances();
4761
4300
  return { success: true, pubkey };
4762
4301
  } catch (e) {
4763
- console.error(tag6, "Failed:", e);
4302
+ console.error(tag, "Failed:", e);
4764
4303
  throw e;
4765
4304
  }
4766
4305
  };
4767
4306
  this.addPaths = async function(paths) {
4768
- const tag6 = `${TAG9} | addPaths | `;
4307
+ const tag = `${TAG9} | addPaths | `;
4769
4308
  try {
4770
- console.log(tag6, `Adding ${paths.length} paths in batch mode...`);
4309
+ console.log(tag, `Adding ${paths.length} paths in batch mode...`);
4771
4310
  this.paths.push(...paths);
4772
4311
  const newPubkeys = [];
4773
4312
  for (const path of paths) {
@@ -4776,10 +4315,10 @@ class SDK {
4776
4315
  this.addPubkey(pubkey);
4777
4316
  newPubkeys.push(pubkey);
4778
4317
  } catch (error) {
4779
- console.warn(tag6, `Failed to get pubkey for path ${path.note}:`, error.message);
4318
+ console.warn(tag, `Failed to get pubkey for path ${path.note}:`, error.message);
4780
4319
  }
4781
4320
  }
4782
- console.log(tag6, `Successfully added ${newPubkeys.length} pubkeys`);
4321
+ console.log(tag, `Successfully added ${newPubkeys.length} pubkeys`);
4783
4322
  const networkSet = new Set;
4784
4323
  for (const path of paths) {
4785
4324
  if (path.networks && Array.isArray(path.networks)) {
@@ -4787,13 +4326,13 @@ class SDK {
4787
4326
  }
4788
4327
  }
4789
4328
  const uniqueNetworks = [...networkSet];
4790
- console.log(tag6, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
4329
+ console.log(tag, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
4791
4330
  await this.getBalancesForNetworks(uniqueNetworks);
4792
4331
  this.buildDashboardFromBalances();
4793
- console.log(tag6, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
4332
+ console.log(tag, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
4794
4333
  return { success: true, pubkeys: newPubkeys };
4795
4334
  } catch (e) {
4796
- console.error(tag6, "Failed:", e);
4335
+ console.error(tag, "Failed:", e);
4797
4336
  throw e;
4798
4337
  }
4799
4338
  };
@@ -4801,12 +4340,12 @@ class SDK {
4801
4340
  return this.getGasAssets();
4802
4341
  };
4803
4342
  this.getGasAssets = async function() {
4804
- const tag6 = `${TAG9} | getGasAssets | `;
4343
+ const tag = `${TAG9} | getGasAssets | `;
4805
4344
  try {
4806
4345
  for (let i = 0;i < this.blockchains.length; i++) {
4807
4346
  let networkId = this.blockchains[i];
4808
4347
  let caip = import_pioneer_caip8.networkIdToCaip(networkId);
4809
- let asset = await import_pioneer_discovery2.assetData[caip.toLowerCase()];
4348
+ let asset = await import_pioneer_discovery.assetData[caip.toLowerCase()];
4810
4349
  if (asset) {
4811
4350
  asset.caip = caip.toLowerCase();
4812
4351
  asset.networkId = networkId;
@@ -4835,7 +4374,7 @@ class SDK {
4835
4374
  denom: "maya"
4836
4375
  };
4837
4376
  this.assetsMap.set(mayaTokenCaip, mayaToken);
4838
- console.log(tag6, "Added MAYA token to assetsMap");
4377
+ console.log(tag, "Added MAYA token to assetsMap");
4839
4378
  }
4840
4379
  return this.assetsMap;
4841
4380
  } catch (e) {
@@ -4844,7 +4383,7 @@ class SDK {
4844
4383
  }
4845
4384
  };
4846
4385
  this.getPubkeys = async function() {
4847
- const tag6 = `${TAG9} | getPubkeys | `;
4386
+ const tag = `${TAG9} | getPubkeys | `;
4848
4387
  try {
4849
4388
  if (this.paths.length === 0)
4850
4389
  throw new Error("No paths found!");
@@ -4858,41 +4397,41 @@ class SDK {
4858
4397
  }
4859
4398
  const pubkeysWithoutNetworks = this.pubkeys.filter((pk) => !pk.networks || !Array.isArray(pk.networks) || pk.networks.length === 0);
4860
4399
  if (pubkeysWithoutNetworks.length > 0) {
4861
- console.error(tag6, "ERROR: Some pubkeys missing networks field!");
4862
- console.error(tag6, "Affected pubkeys:", pubkeysWithoutNetworks.length);
4400
+ console.error(tag, "ERROR: Some pubkeys missing networks field!");
4401
+ console.error(tag, "Affected pubkeys:", pubkeysWithoutNetworks.length);
4863
4402
  pubkeysWithoutNetworks.forEach((pk) => {
4864
- console.error(tag6, ` - ${pk.note || pk.pubkey}: networks=${pk.networks}`);
4403
+ console.error(tag, ` - ${pk.note || pk.pubkey}: networks=${pk.networks}`);
4865
4404
  });
4866
4405
  for (const pubkey of pubkeysWithoutNetworks) {
4867
4406
  const matchingPath = this.paths.find((p) => JSON.stringify(p.addressNList) === JSON.stringify(pubkey.addressNList));
4868
4407
  if (matchingPath && matchingPath.networks) {
4869
- console.warn(tag6, ` ⚠️ Auto-fixing: Adding networks from path ${matchingPath.note}`);
4408
+ console.warn(tag, ` ⚠️ Auto-fixing: Adding networks from path ${matchingPath.note}`);
4870
4409
  pubkey.networks = matchingPath.networks;
4871
4410
  }
4872
4411
  }
4873
4412
  const stillMissing = this.pubkeys.filter((pk) => !pk.networks || !Array.isArray(pk.networks) || pk.networks.length === 0);
4874
4413
  if (stillMissing.length > 0) {
4875
- console.error(tag6, `❌ CRITICAL: ${stillMissing.length} pubkeys still missing networks after auto-fix!`);
4414
+ console.error(tag, `❌ CRITICAL: ${stillMissing.length} pubkeys still missing networks after auto-fix!`);
4876
4415
  stillMissing.forEach((pk) => {
4877
- console.error(tag6, ` - ${pk.note || pk.pubkey}`);
4416
+ console.error(tag, ` - ${pk.note || pk.pubkey}`);
4878
4417
  });
4879
4418
  } else {
4880
- console.log(tag6, `✅ Auto-fix successful: All pubkeys now have networks field`);
4419
+ console.log(tag, `✅ Auto-fix successful: All pubkeys now have networks field`);
4881
4420
  }
4882
4421
  }
4883
4422
  this.events.emit("SET_PUBKEYS", this.pubkeys);
4884
4423
  return pubkeys;
4885
4424
  } catch (error) {
4886
4425
  console.error("Error in getPubkeys:", error);
4887
- console.error(tag6, "Error in getPubkeys:", error);
4426
+ console.error(tag, "Error in getPubkeys:", error);
4888
4427
  throw error;
4889
4428
  }
4890
4429
  };
4891
4430
  this.getBalancesForNetworks = async function(networkIds) {
4892
- const tag6 = `${TAG9} | getBalancesForNetworks | `;
4431
+ const tag = `${TAG9} | getBalancesForNetworks | `;
4893
4432
  try {
4894
4433
  if (!this.pioneer) {
4895
- console.error(tag6, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
4434
+ console.error(tag, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
4896
4435
  throw new Error("Pioneer client not initialized. Call init() first.");
4897
4436
  }
4898
4437
  console.log("\uD83D\uDD0D [DIAGNOSTIC] Input networks:", networkIds);
@@ -4920,20 +4459,20 @@ class SDK {
4920
4459
  return network === adjustedNetworkId;
4921
4460
  }));
4922
4461
  if (pubkeys.length === 0) {
4923
- console.warn(tag6, `⚠️ No pubkeys found for ${networkId} with networks field`);
4924
- console.warn(tag6, "Attempting fallback: finding pubkeys by path matching");
4462
+ console.warn(tag, `⚠️ No pubkeys found for ${networkId} with networks field`);
4463
+ console.warn(tag, "Attempting fallback: finding pubkeys by path matching");
4925
4464
  const pathsForNetwork = this.paths.filter((p) => p.networks?.includes(networkId) || networkId.startsWith("eip155:") && p.networks?.includes("eip155:*"));
4926
4465
  for (const path of pathsForNetwork) {
4927
4466
  const matchingPubkey = this.pubkeys.find((pk) => JSON.stringify(pk.addressNList) === JSON.stringify(path.addressNList));
4928
4467
  if (matchingPubkey) {
4929
- console.warn(tag6, ` ✓ Found pubkey via path matching: ${matchingPubkey.note || matchingPubkey.pubkey.slice(0, 10)}`);
4468
+ console.warn(tag, ` ✓ Found pubkey via path matching: ${matchingPubkey.note || matchingPubkey.pubkey.slice(0, 10)}`);
4930
4469
  pubkeys.push(matchingPubkey);
4931
4470
  }
4932
4471
  }
4933
4472
  if (pubkeys.length > 0) {
4934
- console.warn(tag6, ` ✅ Fallback successful: Found ${pubkeys.length} pubkeys for ${networkId}`);
4473
+ console.warn(tag, ` ✅ Fallback successful: Found ${pubkeys.length} pubkeys for ${networkId}`);
4935
4474
  } else {
4936
- console.error(tag6, ` ❌ Fallback failed: No pubkeys found for ${networkId}`);
4475
+ console.error(tag, ` ❌ Fallback failed: No pubkeys found for ${networkId}`);
4937
4476
  }
4938
4477
  }
4939
4478
  const caipNative = await import_pioneer_caip8.networkIdToCaip(networkId);
@@ -4951,11 +4490,18 @@ class SDK {
4951
4490
  caipCounts.forEach((count, caip) => {
4952
4491
  console.log(` - ${caip}: ${count} queries`);
4953
4492
  });
4493
+ console.log(`⏱️ [PERF] Starting GetPortfolioBalances API call...`);
4494
+ const apiCallStart = performance.now();
4954
4495
  console.time("GetPortfolioBalances Response Time");
4955
4496
  try {
4956
- let marketInfo = await this.pioneer.GetPortfolioBalances(assetQuery);
4497
+ let marketInfo = await this.pioneer.GetPortfolioBalances({ pubkeys: assetQuery });
4498
+ const apiCallTime = performance.now() - apiCallStart;
4957
4499
  console.timeEnd("GetPortfolioBalances Response Time");
4500
+ console.log(`⏱️ [PERF] API call completed in ${apiCallTime.toFixed(0)}ms`);
4501
+ const enrichStart = performance.now();
4958
4502
  let balances = marketInfo.data;
4503
+ console.log(`⏱️ [PERF] Received ${balances?.length || 0} balances from server`);
4504
+ console.log(`⏱️ [PERF] Starting balance enrichment...`);
4959
4505
  for (let balance of balances) {
4960
4506
  const assetInfo = this.assetsMap.get(balance.caip.toLowerCase()) || this.assetsMap.get(balance.caip);
4961
4507
  if (!assetInfo)
@@ -4969,47 +4515,50 @@ class SDK {
4969
4515
  color
4970
4516
  });
4971
4517
  }
4518
+ const enrichTime = performance.now() - enrichStart;
4519
+ console.log(`⏱️ [PERF] Enrichment completed in ${enrichTime.toFixed(0)}ms`);
4972
4520
  this.balances = balances;
4973
4521
  this.events.emit("SET_BALANCES", this.balances);
4522
+ console.log(`⏱️ [PERF] Total getBalancesForNetworks: ${(performance.now() - apiCallStart).toFixed(0)}ms`);
4974
4523
  return this.balances;
4975
4524
  } catch (apiError) {
4976
- console.error(tag6, "GetPortfolioBalances API call failed:", apiError);
4525
+ console.error(tag, "GetPortfolioBalances API call failed:", apiError);
4977
4526
  throw new Error(`GetPortfolioBalances API call failed: ${apiError?.message || "Unknown error"}`);
4978
4527
  }
4979
4528
  } catch (e) {
4980
- console.error(tag6, "Error: ", e);
4529
+ console.error(tag, "Error: ", e);
4981
4530
  throw e;
4982
4531
  }
4983
4532
  };
4984
4533
  this.getBalances = async function() {
4985
- const tag6 = `${TAG9} | getBalances | `;
4534
+ const tag = `${TAG9} | getBalances | `;
4986
4535
  try {
4987
4536
  return await this.getBalancesForNetworks(this.blockchains);
4988
4537
  } catch (e) {
4989
- console.error(tag6, "Error in getBalances: ", e);
4538
+ console.error(tag, "Error in getBalances: ", e);
4990
4539
  throw e;
4991
4540
  }
4992
4541
  };
4993
4542
  this.getBalance = async function(networkId) {
4994
- const tag6 = `${TAG9} | getBalance | `;
4543
+ const tag = `${TAG9} | getBalance | `;
4995
4544
  try {
4996
4545
  const results = await this.getBalancesForNetworks([networkId]);
4997
4546
  const filtered = results.filter(async (b) => b.networkId === await import_pioneer_caip8.networkIdToCaip(networkId));
4998
4547
  return filtered;
4999
4548
  } catch (e) {
5000
- console.error(tag6, "Error: ", e);
4549
+ console.error(tag, "Error: ", e);
5001
4550
  throw e;
5002
4551
  }
5003
4552
  };
5004
4553
  this.getFees = async function(networkId) {
5005
- const tag6 = `${TAG9} | getFees | `;
4554
+ const tag = `${TAG9} | getFees | `;
5006
4555
  try {
5007
4556
  if (!this.pioneer) {
5008
4557
  throw new Error("Pioneer client not initialized. Call init() first.");
5009
4558
  }
5010
4559
  return await getFees(this.pioneer, networkId);
5011
4560
  } catch (e) {
5012
- console.error(tag6, "Error getting fees: ", e);
4561
+ console.error(tag, "Error getting fees: ", e);
5013
4562
  throw e;
5014
4563
  }
5015
4564
  };
@@ -5017,29 +4566,55 @@ class SDK {
5017
4566
  return estimateTransactionFee(feeRate, unit, networkType, txSize);
5018
4567
  };
5019
4568
  this.getCharts = async function() {
5020
- const tag6 = `${TAG9} | getCharts | `;
4569
+ const tag = `${TAG9} | getCharts | `;
5021
4570
  try {
5022
- console.log(tag6, "Fetching charts");
5023
- const newBalances = await getCharts(this.blockchains, this.pioneer, this.pubkeys, this.context);
5024
- console.log(tag6, "newBalances: ", newBalances);
4571
+ console.log(tag, "Fetching charts from batch endpoint");
4572
+ const pubkeysForBatch = [];
4573
+ for (const pubkey of this.pubkeys) {
4574
+ const address = pubkey.address || pubkey.master || pubkey.pubkey;
4575
+ if (!address)
4576
+ continue;
4577
+ const supportedNetworks = pubkey.networks || [];
4578
+ for (const blockchain of this.blockchains) {
4579
+ const supportsNetwork = supportedNetworks.some((net) => net === blockchain || net.endsWith(":*") && blockchain.startsWith(net.replace(":*", ":")));
4580
+ if (supportsNetwork) {
4581
+ let caip;
4582
+ if (blockchain.startsWith("eip155:")) {
4583
+ caip = `${blockchain}/slip44:60`;
4584
+ } else {
4585
+ caip = `${blockchain}/slip44:0`;
4586
+ }
4587
+ pubkeysForBatch.push({
4588
+ pubkey: address,
4589
+ caip
4590
+ });
4591
+ }
4592
+ }
4593
+ }
4594
+ console.log(tag, `Calling batch GetCharts with ${pubkeysForBatch.length} pubkeys`);
4595
+ const chartsResponse = await this.pioneer.GetCharts({
4596
+ pubkeys: pubkeysForBatch
4597
+ });
4598
+ const newBalances = chartsResponse?.data?.balances || [];
4599
+ console.log(tag, `Received ${newBalances.length} balances from batch endpoint`);
5025
4600
  const uniqueBalances = new Map([...this.balances, ...newBalances].map((balance) => [
5026
- balance.identifier,
4601
+ balance.identifier || `${balance.caip}:${balance.pubkey}`,
5027
4602
  {
5028
4603
  ...balance,
5029
4604
  type: balance.type || "balance"
5030
4605
  }
5031
4606
  ]));
5032
- console.log(tag6, "uniqueBalances: ", uniqueBalances);
4607
+ console.log(tag, "uniqueBalances: ", uniqueBalances.size);
5033
4608
  this.balances = Array.from(uniqueBalances.values());
5034
- console.log(tag6, "Updated this.balances: ", this.balances);
4609
+ console.log(tag, "Updated this.balances: ", this.balances.length);
5035
4610
  return this.balances;
5036
4611
  } catch (e) {
5037
- console.error(tag6, "Error in getCharts:", e);
4612
+ console.error(tag, "Error in getCharts:", e);
5038
4613
  throw e;
5039
4614
  }
5040
4615
  };
5041
4616
  this.setContext = async (context) => {
5042
- const tag6 = `${TAG9} | setContext | `;
4617
+ const tag = `${TAG9} | setContext | `;
5043
4618
  try {
5044
4619
  if (!context)
5045
4620
  throw Error("context required!");
@@ -5047,12 +4622,12 @@ class SDK {
5047
4622
  this.events.emit("SET_CONTEXT", context);
5048
4623
  return { success: true };
5049
4624
  } catch (e) {
5050
- console.error(tag6, "e: ", e);
4625
+ console.error(tag, "e: ", e);
5051
4626
  return { success: false };
5052
4627
  }
5053
4628
  };
5054
4629
  this.setContextType = async (contextType) => {
5055
- const tag6 = `${TAG9} | setContextType | `;
4630
+ const tag = `${TAG9} | setContextType | `;
5056
4631
  try {
5057
4632
  if (!contextType)
5058
4633
  throw Error("contextType required!");
@@ -5060,22 +4635,22 @@ class SDK {
5060
4635
  this.events.emit("SET_CONTEXT_TYPE", contextType);
5061
4636
  return { success: true };
5062
4637
  } catch (e) {
5063
- console.error(tag6, "e: ", e);
4638
+ console.error(tag, "e: ", e);
5064
4639
  return { success: false };
5065
4640
  }
5066
4641
  };
5067
4642
  this.refresh = async () => {
5068
- const tag6 = `${TAG9} | refresh | `;
4643
+ const tag = `${TAG9} | refresh | `;
5069
4644
  try {
5070
4645
  await this.sync();
5071
4646
  return this.balances;
5072
4647
  } catch (e) {
5073
- console.error(tag6, "e: ", e);
4648
+ console.error(tag, "e: ", e);
5074
4649
  throw e;
5075
4650
  }
5076
4651
  };
5077
4652
  this.setAssetContext = async function(asset) {
5078
- const tag6 = `${TAG9} | setAssetContext | `;
4653
+ const tag = `${TAG9} | setAssetContext | `;
5079
4654
  try {
5080
4655
  if (!asset) {
5081
4656
  this.assetContext = null;
@@ -5087,7 +4662,7 @@ class SDK {
5087
4662
  asset.networkId = import_pioneer_caip8.caipToNetworkId(asset.caip);
5088
4663
  if (!this.pubkeys || this.pubkeys.length === 0) {
5089
4664
  const errorMsg = `Cannot set asset context for ${asset.caip} - no pubkeys loaded. Please initialize wallet first.`;
5090
- console.error(tag6, errorMsg);
4665
+ console.error(tag, errorMsg);
5091
4666
  throw new Error(errorMsg);
5092
4667
  }
5093
4668
  const pubkeysForNetwork = this.pubkeys.filter((e) => {
@@ -5102,8 +4677,8 @@ class SDK {
5102
4677
  });
5103
4678
  if (pubkeysForNetwork.length === 0) {
5104
4679
  const errorMsg = `Cannot set asset context for ${asset.caip} - no address/xpub found for network ${asset.networkId}`;
5105
- console.error(tag6, errorMsg);
5106
- console.error(tag6, "Available networks in pubkeys:", [
4680
+ console.error(tag, errorMsg);
4681
+ console.error(tag, "Available networks in pubkeys:", [
5107
4682
  ...new Set(this.pubkeys.flatMap((p) => p.networks || []))
5108
4683
  ]);
5109
4684
  throw new Error(errorMsg);
@@ -5113,43 +4688,43 @@ class SDK {
5113
4688
  const xpubFound = pubkeysForNetwork.some((p) => p.type === "xpub" && p.pubkey);
5114
4689
  if (!xpubFound) {
5115
4690
  const errorMsg = `Cannot set asset context for UTXO chain ${asset.caip} - xpub required but not found`;
5116
- console.error(tag6, errorMsg);
4691
+ console.error(tag, errorMsg);
5117
4692
  throw new Error(errorMsg);
5118
4693
  }
5119
4694
  }
5120
4695
  const hasValidAddress = pubkeysForNetwork.some((p) => p.address || p.master || p.pubkey);
5121
4696
  if (!hasValidAddress) {
5122
4697
  const errorMsg = `Cannot set asset context for ${asset.caip} - no valid address found in pubkeys`;
5123
- console.error(tag6, errorMsg);
4698
+ console.error(tag, errorMsg);
5124
4699
  throw new Error(errorMsg);
5125
4700
  }
5126
- console.log(tag6, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
4701
+ console.log(tag, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5127
4702
  let freshPriceUsd = 0;
5128
4703
  try {
5129
4704
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5130
- console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
4705
+ console.warn(tag, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5131
4706
  } else {
5132
- console.log(tag6, "Fetching fresh market price for:", asset.caip);
4707
+ console.log(tag, "Fetching fresh market price for:", asset.caip);
5133
4708
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5134
- console.log(tag6, "Market data response:", marketData);
4709
+ console.log(tag, "Market data response:", marketData);
5135
4710
  if (marketData && marketData.data && marketData.data.length > 0) {
5136
4711
  freshPriceUsd = marketData.data[0];
5137
- console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
4712
+ console.log(tag, "✅ Fresh market price:", freshPriceUsd);
5138
4713
  } else {
5139
- console.warn(tag6, "No market data returned for:", asset.caip);
4714
+ console.warn(tag, "No market data returned for:", asset.caip);
5140
4715
  }
5141
4716
  }
5142
4717
  } catch (marketError) {
5143
- console.error(tag6, "Error fetching market price:", marketError);
4718
+ console.error(tag, "Error fetching market price:", marketError);
5144
4719
  }
5145
4720
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5146
- console.log(tag6, "assetInfo: ", assetInfo);
5147
- let assetInfoDiscovery = import_pioneer_discovery2.assetData[asset.caip];
5148
- console.log(tag6, "assetInfoDiscovery: ", assetInfoDiscovery);
4721
+ console.log(tag, "assetInfo: ", assetInfo);
4722
+ let assetInfoDiscovery = import_pioneer_discovery.assetData[asset.caip];
4723
+ console.log(tag, "assetInfoDiscovery: ", assetInfoDiscovery);
5149
4724
  if (assetInfoDiscovery)
5150
4725
  assetInfo = assetInfoDiscovery;
5151
4726
  if (!assetInfo) {
5152
- console.log(tag6, "Building placeholder asset!");
4727
+ console.log(tag, "Building placeholder asset!");
5153
4728
  assetInfo = {
5154
4729
  caip: asset.caip.toLowerCase(),
5155
4730
  networkId: asset.networkId,
@@ -5166,30 +4741,30 @@ class SDK {
5166
4741
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5167
4742
  if (balance > 0 && valueUsd > 0) {
5168
4743
  priceValue = valueUsd / balance;
5169
- console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
4744
+ console.log(tag, "calculated priceUsd from valueUsd/balance:", priceValue);
5170
4745
  }
5171
4746
  }
5172
4747
  if (priceValue && priceValue > 0) {
5173
- console.log(tag6, "detected priceUsd from balance:", priceValue);
4748
+ console.log(tag, "detected priceUsd from balance:", priceValue);
5174
4749
  assetInfo.priceUsd = priceValue;
5175
4750
  }
5176
4751
  }
5177
4752
  if (freshPriceUsd && freshPriceUsd > 0) {
5178
4753
  assetInfo.priceUsd = freshPriceUsd;
5179
- console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
4754
+ console.log(tag, "✅ Using fresh market price:", freshPriceUsd);
5180
4755
  let totalBalance = 0;
5181
4756
  let totalValueUsd = 0;
5182
- console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
4757
+ console.log(tag, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5183
4758
  for (const balanceEntry of matchingBalances) {
5184
4759
  const balance = parseFloat(balanceEntry.balance) || 0;
5185
4760
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5186
4761
  totalBalance += balance;
5187
4762
  totalValueUsd += valueUsd;
5188
- console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
4763
+ console.log(tag, ` Balance entry: ${balance} (${valueUsd} USD)`);
5189
4764
  }
5190
4765
  assetInfo.balance = totalBalance.toString();
5191
4766
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5192
- console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
4767
+ console.log(tag, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5193
4768
  }
5194
4769
  const assetBalances = this.balances.filter((b) => b.caip === asset.caip);
5195
4770
  const assetPubkeys = this.pubkeys.filter((p) => p.networks && Array.isArray(p.networks) && p.networks.includes(import_pioneer_caip8.caipToNetworkId(asset.caip)) || import_pioneer_caip8.caipToNetworkId(asset.caip).includes("eip155") && p.networks && Array.isArray(p.networks) && p.networks.some((n) => n.startsWith("eip155")));
@@ -5209,7 +4784,7 @@ class SDK {
5209
4784
  const balanceAmount = parseFloat(balance.balance || 0);
5210
4785
  balance.valueUsd = (balanceAmount * freshPriceUsd).toString();
5211
4786
  }
5212
- console.log(tag6, "Updated all balances with fresh price data");
4787
+ console.log(tag, "Updated all balances with fresh price data");
5213
4788
  }
5214
4789
  this.assetContext = finalAssetContext;
5215
4790
  if (asset.isToken || asset.type === "token" || assetInfo.isToken || assetInfo.type === "token") {
@@ -5261,20 +4836,20 @@ class SDK {
5261
4836
  const currentContextValid = this.pubkeyContext?.networks?.includes(networkId);
5262
4837
  if (!this.pubkeyContext || !currentContextValid) {
5263
4838
  this.pubkeyContext = assetPubkeys[0];
5264
- console.log(tag6, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
4839
+ console.log(tag, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5265
4840
  } else {
5266
- console.log(tag6, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
4841
+ console.log(tag, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5267
4842
  }
5268
4843
  }
5269
4844
  this.events.emit("SET_ASSET_CONTEXT", this.assetContext);
5270
4845
  return this.assetContext;
5271
4846
  } catch (e) {
5272
- console.error(tag6, "e: ", e);
4847
+ console.error(tag, "e: ", e);
5273
4848
  throw e;
5274
4849
  }
5275
4850
  };
5276
4851
  this.setPubkeyContext = async function(pubkey) {
5277
- let tag6 = `${TAG9} | setPubkeyContext | `;
4852
+ let tag = `${TAG9} | setPubkeyContext | `;
5278
4853
  try {
5279
4854
  if (!pubkey)
5280
4855
  throw Error("pubkey is required");
@@ -5282,31 +4857,31 @@ class SDK {
5282
4857
  throw Error("invalid pubkey: missing pubkey or address");
5283
4858
  const exists = this.pubkeys.some((pk) => pk.pubkey === pubkey.pubkey || pk.address === pubkey.address || pk.pubkey === pubkey.address);
5284
4859
  if (!exists) {
5285
- console.warn(tag6, "Pubkey not found in current pubkeys array");
4860
+ console.warn(tag, "Pubkey not found in current pubkeys array");
5286
4861
  }
5287
4862
  this.pubkeyContext = pubkey;
5288
- console.log(tag6, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
4863
+ console.log(tag, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5289
4864
  return true;
5290
4865
  } catch (e) {
5291
- console.error(tag6, "e: ", e);
4866
+ console.error(tag, "e: ", e);
5292
4867
  throw e;
5293
4868
  }
5294
4869
  };
5295
4870
  this.setOutboundAssetContext = async function(asset) {
5296
- const tag6 = `${TAG9} | setOutputAssetContext | `;
4871
+ const tag = `${TAG9} | setOutputAssetContext | `;
5297
4872
  try {
5298
- console.log(tag6, "0. asset: ", asset);
4873
+ console.log(tag, "0. asset: ", asset);
5299
4874
  if (!asset) {
5300
4875
  this.outboundAssetContext = null;
5301
4876
  return;
5302
4877
  }
5303
- console.log(tag6, "1 asset: ", asset);
4878
+ console.log(tag, "1 asset: ", asset);
5304
4879
  if (!asset.caip)
5305
4880
  throw Error("Invalid Asset! missing caip!");
5306
4881
  if (!asset.networkId)
5307
4882
  asset.networkId = import_pioneer_caip8.caipToNetworkId(asset.caip);
5308
- console.log(tag6, "networkId: ", asset.networkId);
5309
- console.log(tag6, "this.pubkeys: ", this.pubkeys);
4883
+ console.log(tag, "networkId: ", asset.networkId);
4884
+ console.log(tag, "this.pubkeys: ", this.pubkeys);
5310
4885
  const pubkey = this.pubkeys.find((p) => {
5311
4886
  if (!p.networks || !Array.isArray(p.networks))
5312
4887
  return false;
@@ -5321,23 +4896,23 @@ class SDK {
5321
4896
  let freshPriceUsd = 0;
5322
4897
  try {
5323
4898
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5324
- console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
4899
+ console.warn(tag, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5325
4900
  } else {
5326
- console.log(tag6, "Fetching fresh market price for:", asset.caip);
4901
+ console.log(tag, "Fetching fresh market price for:", asset.caip);
5327
4902
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5328
- console.log(tag6, "Market data response:", marketData);
4903
+ console.log(tag, "Market data response:", marketData);
5329
4904
  if (marketData && marketData.data && marketData.data.length > 0) {
5330
4905
  freshPriceUsd = marketData.data[0];
5331
- console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
4906
+ console.log(tag, "✅ Fresh market price:", freshPriceUsd);
5332
4907
  } else {
5333
- console.warn(tag6, "No market data returned for:", asset.caip);
4908
+ console.warn(tag, "No market data returned for:", asset.caip);
5334
4909
  }
5335
4910
  }
5336
4911
  } catch (marketError) {
5337
- console.error(tag6, "Error fetching market price:", marketError);
4912
+ console.error(tag, "Error fetching market price:", marketError);
5338
4913
  }
5339
4914
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5340
- console.log(tag6, "assetInfo: ", assetInfo);
4915
+ console.log(tag, "assetInfo: ", assetInfo);
5341
4916
  if (!assetInfo) {
5342
4917
  assetInfo = {
5343
4918
  caip: asset.caip.toLowerCase(),
@@ -5355,45 +4930,45 @@ class SDK {
5355
4930
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5356
4931
  if (balance > 0 && valueUsd > 0) {
5357
4932
  priceValue = valueUsd / balance;
5358
- console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
4933
+ console.log(tag, "calculated priceUsd from valueUsd/balance:", priceValue);
5359
4934
  }
5360
4935
  }
5361
4936
  if (priceValue && priceValue > 0) {
5362
- console.log(tag6, "detected priceUsd from balance:", priceValue);
4937
+ console.log(tag, "detected priceUsd from balance:", priceValue);
5363
4938
  assetInfo.priceUsd = priceValue;
5364
4939
  }
5365
4940
  }
5366
4941
  if (freshPriceUsd && freshPriceUsd > 0) {
5367
4942
  assetInfo.priceUsd = freshPriceUsd;
5368
- console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
4943
+ console.log(tag, "✅ Using fresh market price:", freshPriceUsd);
5369
4944
  let totalBalance = 0;
5370
4945
  let totalValueUsd = 0;
5371
- console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
4946
+ console.log(tag, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5372
4947
  for (const balanceEntry of matchingBalances) {
5373
4948
  const balance = parseFloat(balanceEntry.balance) || 0;
5374
4949
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5375
4950
  totalBalance += balance;
5376
4951
  totalValueUsd += valueUsd;
5377
- console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
4952
+ console.log(tag, ` Balance entry: ${balance} (${valueUsd} USD)`);
5378
4953
  }
5379
4954
  assetInfo.balance = totalBalance.toString();
5380
4955
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5381
- console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
4956
+ console.log(tag, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5382
4957
  }
5383
- console.log(tag6, "CHECKPOINT 1");
4958
+ console.log(tag, "CHECKPOINT 1");
5384
4959
  this.outboundAssetContext = { ...assetInfo, ...asset, ...pubkey };
5385
- console.log(tag6, "CHECKPOINT 3");
5386
- console.log(tag6, "outboundAssetContext: assetInfo: ", assetInfo);
4960
+ console.log(tag, "CHECKPOINT 3");
4961
+ console.log(tag, "outboundAssetContext: assetInfo: ", assetInfo);
5387
4962
  if (asset.caip) {
5388
4963
  this.outboundBlockchainContext = import_pioneer_caip8.caipToNetworkId(asset.caip);
5389
4964
  } else if (asset.networkId) {
5390
4965
  this.outboundBlockchainContext = asset.networkId;
5391
4966
  }
5392
- console.log(tag6, "CHECKPOINT 4");
4967
+ console.log(tag, "CHECKPOINT 4");
5393
4968
  this.events.emit("SET_OUTBOUND_ASSET_CONTEXT", this.outboundAssetContext);
5394
4969
  return this.outboundAssetContext;
5395
4970
  } catch (e) {
5396
- console.error(tag6, "e: ", e);
4971
+ console.error(tag, "e: ", e);
5397
4972
  throw e;
5398
4973
  }
5399
4974
  };