@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.es.js CHANGED
@@ -367,7 +367,7 @@ class Pioneer {
367
367
 
368
368
  // src/index.ts
369
369
  import { addressNListToBIP32 as addressNListToBIP322, getPaths } from "@pioneer-platform/pioneer-coins";
370
- import { assetData as assetData2 } from "@pioneer-platform/pioneer-discovery";
370
+ import { assetData } from "@pioneer-platform/pioneer-discovery";
371
371
  import { Events } from "@pioneer-platform/pioneer-events";
372
372
 
373
373
  // node:events
@@ -566,467 +566,6 @@ function R(t) {
566
566
  var A = o;
567
567
  var P = o.prototype;
568
568
 
569
- // src/charts/utils.ts
570
- import { assetData } from "@pioneer-platform/pioneer-discovery";
571
- function hydrateAssetData(caip) {
572
- return assetData[caip] || assetData[caip.toLowerCase()];
573
- }
574
- function checkDuplicateBalance(balances, caip, pubkey, validator) {
575
- return balances.some((b2) => b2.caip === caip && b2.pubkey === pubkey && (!validator || b2.validator === validator));
576
- }
577
- function createBalanceIdentifier(caip, pubkey) {
578
- return `${caip}:${pubkey}`;
579
- }
580
-
581
- // src/charts/custom-tokens.ts
582
- var tag = "| charts-custom-tokens |";
583
- async function fetchCustomTokens(params, balances) {
584
- const { pioneer, pubkeys, blockchains, context } = params;
585
- console.log(tag, "Fetching custom tokens...");
586
- const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
587
- const primaryAddress = evmPubkey?.address || evmPubkey?.master;
588
- if (!primaryAddress) {
589
- console.log(tag, "No EVM address found, skipping custom tokens");
590
- return;
591
- }
592
- console.log(tag, "Using EVM address for custom tokens:", primaryAddress);
593
- const supportedNetworks = blockchains.filter((net) => net.startsWith("eip155:"));
594
- if (supportedNetworks.length === 0) {
595
- console.log(tag, "No EVM networks for custom tokens");
596
- return;
597
- }
598
- console.log(tag, `Checking custom tokens on ${supportedNetworks.length} networks`);
599
- for (const networkId of supportedNetworks) {
600
- try {
601
- const response = await pioneer.GetCustomTokens({ networkId, userAddress: primaryAddress });
602
- const customTokens = response?.data?.tokens || [];
603
- console.log(tag, `Found ${customTokens.length} custom tokens on ${networkId}`);
604
- for (const token of customTokens) {
605
- const chartBalance = processCustomToken(token, primaryAddress, context, blockchains);
606
- if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
607
- balances.push(chartBalance);
608
- console.log(tag, `Added custom token: ${chartBalance.symbol} = ${chartBalance.balance}`);
609
- }
610
- }
611
- } catch (error) {
612
- console.error(tag, `Error fetching custom tokens for ${networkId}:`, error.message);
613
- }
614
- }
615
- console.log(tag, `Custom tokens complete. Total balances: ${balances.length}`);
616
- }
617
- function processCustomToken(token, primaryAddress, context, blockchains) {
618
- if (!token.assetCaip || !token.networkId) {
619
- return null;
620
- }
621
- let extractedNetworkId = token.networkId;
622
- if (token.assetCaip.includes("/denom:")) {
623
- const parts = token.assetCaip.split("/denom:");
624
- if (parts.length > 0) {
625
- extractedNetworkId = parts[0];
626
- }
627
- } else if (token.networkId && token.networkId.includes("/")) {
628
- extractedNetworkId = token.networkId.split("/")[0];
629
- }
630
- const isEip155 = extractedNetworkId.startsWith("eip155:");
631
- if (!isEip155 && !blockchains.includes(extractedNetworkId)) {
632
- return null;
633
- }
634
- const tokenAssetInfo = hydrateAssetData(token.assetCaip);
635
- const tokenPubkey = token.pubkey || primaryAddress;
636
- const chartBalance = {
637
- context,
638
- chart: "pioneer",
639
- contextType: context.split(":")[0],
640
- name: tokenAssetInfo?.name || token.token?.name || "Unknown Custom Token",
641
- caip: token.assetCaip,
642
- icon: tokenAssetInfo?.icon || token.token?.icon || "",
643
- pubkey: tokenPubkey,
644
- ticker: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
645
- ref: `${context}${token.assetCaip}`,
646
- identifier: createBalanceIdentifier(token.assetCaip, tokenPubkey),
647
- networkId: extractedNetworkId,
648
- symbol: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
649
- type: tokenAssetInfo?.type || "erc20",
650
- token: true,
651
- decimal: tokenAssetInfo?.decimal || token.token?.decimal,
652
- balance: token.token?.balance?.toString() || "0",
653
- priceUsd: token.token?.price || 0,
654
- valueUsd: token.token?.balanceUSD || 0,
655
- updated: new Date().getTime()
656
- };
657
- return chartBalance;
658
- }
659
-
660
- // src/charts/evm.ts
661
- var tag2 = "| charts-evm |";
662
- async function getEvmCharts(params) {
663
- const { blockchains, pioneer, pubkeys, context } = params;
664
- const balances = [];
665
- const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
666
- const primaryAddress = evmPubkey?.address || evmPubkey?.master;
667
- console.log(tag2, "Total pubkeys available:", pubkeys.length);
668
- console.log(tag2, "Blockchains to process:", blockchains);
669
- if (!primaryAddress) {
670
- console.log(tag2, "No EVM address found, skipping portfolio lookup (Zapper only supports Ethereum)");
671
- return balances;
672
- }
673
- console.log(tag2, "Using EVM address for portfolio:", primaryAddress);
674
- await fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context);
675
- await fetchCustomTokens({ blockchains, pioneer, pubkeys, context }, balances);
676
- try {
677
- let portfolio = await pioneer.GetPortfolio({
678
- networkId: "eip155:1",
679
- address: primaryAddress
680
- });
681
- portfolio = portfolio.data?.data || portfolio.data;
682
- if (!portfolio || !portfolio.balances) {
683
- console.error(tag2, "No portfolio.balances found:", portfolio);
684
- return balances;
685
- }
686
- console.log(tag2, `Portfolio returned ${portfolio.balances.length} balances`);
687
- let processedCount = 0;
688
- let skippedCount = 0;
689
- for (const balance of portfolio.balances) {
690
- const processedBalance = processPortfolioBalance(balance, primaryAddress, context, blockchains);
691
- if (processedBalance) {
692
- if (!checkDuplicateBalance(balances, processedBalance.caip, processedBalance.pubkey)) {
693
- balances.push(processedBalance);
694
- processedCount++;
695
- }
696
- } else {
697
- skippedCount++;
698
- }
699
- }
700
- console.log(tag2, `Processed ${processedCount} balances, skipped ${skippedCount}`);
701
- if (portfolio.tokens && portfolio.tokens.length > 0) {
702
- console.log(tag2, "Processing portfolio.tokens:", portfolio.tokens.length);
703
- for (const token of portfolio.tokens) {
704
- const processedToken = processPortfolioToken(token, primaryAddress, context, blockchains);
705
- if (processedToken && !checkDuplicateBalance(balances, processedToken.caip, processedToken.pubkey)) {
706
- balances.push(processedToken);
707
- }
708
- }
709
- }
710
- } catch (e) {
711
- console.error(tag2, "Error fetching portfolio:", e);
712
- }
713
- return balances;
714
- }
715
- function processPortfolioBalance(balance, primaryAddress, context, blockchains) {
716
- if (!balance.caip) {
717
- console.error(tag2, "No caip found for:", balance);
718
- return null;
719
- }
720
- const networkId = balance.caip.split("/")[0];
721
- const isEip155 = networkId.startsWith("eip155:");
722
- if (!isEip155 && !blockchains.includes(networkId)) {
723
- return null;
724
- }
725
- const assetInfo = hydrateAssetData(balance.caip);
726
- const balancePubkey = balance.pubkey || primaryAddress;
727
- const balanceType = assetInfo?.type || balance.type || "native";
728
- const isToken = balanceType !== "native" && balance.caip.includes("/erc20:");
729
- let calculatedPrice = balance.priceUsd || balance.price || 0;
730
- if ((!calculatedPrice || calculatedPrice === 0) && balance.valueUsd && balance.balance) {
731
- const balanceNum = parseFloat(balance.balance.toString());
732
- const valueNum = parseFloat(balance.valueUsd.toString());
733
- if (balanceNum > 0 && valueNum > 0) {
734
- calculatedPrice = valueNum / balanceNum;
735
- console.log(tag2, `Calculated price from value/balance: ${calculatedPrice} for ${balance.caip}`);
736
- }
737
- }
738
- const chartBalance = {
739
- context,
740
- chart: "pioneer",
741
- contextType: "keepkey",
742
- name: assetInfo?.name || balance.name || "Unknown",
743
- caip: balance.caip,
744
- icon: assetInfo?.icon || balance.icon || "",
745
- pubkey: balancePubkey,
746
- ticker: assetInfo?.symbol || balance.symbol || "UNK",
747
- ref: `${context}${balance.caip}`,
748
- identifier: createBalanceIdentifier(balance.caip, balancePubkey),
749
- networkId,
750
- chain: networkId,
751
- symbol: assetInfo?.symbol || balance.symbol || "UNK",
752
- type: balanceType,
753
- token: isToken,
754
- decimal: assetInfo?.decimal || balance.decimal,
755
- balance: balance.balance.toString(),
756
- price: calculatedPrice,
757
- priceUsd: calculatedPrice,
758
- valueUsd: balance.valueUsd.toString(),
759
- updated: new Date().getTime()
760
- };
761
- if (balance.display) {
762
- chartBalance.icon = ["multi", chartBalance.icon, balance.display.toString()].toString();
763
- }
764
- return chartBalance;
765
- }
766
- function processPortfolioToken(token, primaryAddress, context, blockchains) {
767
- if (!token.assetCaip || !token.networkId) {
768
- return null;
769
- }
770
- let extractedNetworkId = token.networkId;
771
- if (token.assetCaip.includes("/denom:")) {
772
- const parts = token.assetCaip.split("/denom:");
773
- if (parts.length > 0) {
774
- extractedNetworkId = parts[0];
775
- }
776
- } else if (token.networkId && token.networkId.includes("/")) {
777
- extractedNetworkId = token.networkId.split("/")[0];
778
- }
779
- const isEip155 = extractedNetworkId.startsWith("eip155:");
780
- if (!isEip155 && !blockchains.includes(extractedNetworkId)) {
781
- return null;
782
- }
783
- const tokenAssetInfo = hydrateAssetData(token.assetCaip);
784
- const tokenPubkey = token.pubkey || primaryAddress;
785
- const chartBalance = {
786
- context,
787
- chart: "pioneer",
788
- contextType: context.split(":")[0],
789
- name: tokenAssetInfo?.name || token.token?.coingeckoId || token.token?.name || "Unknown",
790
- caip: token.assetCaip,
791
- icon: tokenAssetInfo?.icon || token.token?.icon || "",
792
- pubkey: tokenPubkey,
793
- ticker: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
794
- ref: `${context}${token.assetCaip}`,
795
- identifier: createBalanceIdentifier(token.assetCaip, tokenPubkey),
796
- networkId: extractedNetworkId,
797
- symbol: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
798
- type: tokenAssetInfo?.type || "token",
799
- token: true,
800
- decimal: tokenAssetInfo?.decimal || token.token?.decimal,
801
- balance: token.token?.balance?.toString() || "0",
802
- priceUsd: token.token?.price || 0,
803
- valueUsd: token.token?.balanceUSD || 0,
804
- updated: new Date().getTime()
805
- };
806
- return chartBalance;
807
- }
808
- async function fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context) {
809
- console.log(tag2, "Fetching stable coins for redundancy...");
810
- const supportedNetworks = ["eip155:1", "eip155:137", "eip155:8453", "eip155:56"];
811
- const networksToCheck = blockchains.filter((net) => supportedNetworks.includes(net));
812
- if (networksToCheck.length === 0) {
813
- console.log(tag2, "No supported networks for stable coins");
814
- return;
815
- }
816
- console.log(tag2, `Checking stable coins on ${networksToCheck.length} networks`);
817
- for (const networkId of networksToCheck) {
818
- try {
819
- const response = await pioneer.GetStableCoins({ networkId, address: primaryAddress });
820
- const stableCoins = response?.data?.tokens || [];
821
- console.log(tag2, `Found ${stableCoins.length} stable coins on ${networkId}`);
822
- for (const token of stableCoins) {
823
- const chartBalance = processPortfolioToken(token, primaryAddress, context, blockchains);
824
- if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
825
- balances.push(chartBalance);
826
- console.log(tag2, `Added stable coin: ${chartBalance.symbol} = ${chartBalance.balance}`);
827
- }
828
- }
829
- } catch (error) {
830
- console.error(tag2, `Error fetching stable coins for ${networkId}:`, error.message);
831
- }
832
- }
833
- console.log(tag2, `Stable coin redundancy complete. Total balances: ${balances.length}`);
834
- }
835
-
836
- // src/charts/maya.ts
837
- var tag3 = "| charts-maya |";
838
- async function getMayaCharts(params, existingBalances) {
839
- const { blockchains, pioneer, pubkeys, context } = params;
840
- const balances = [];
841
- try {
842
- const mayaPubkey = pubkeys.find((p) => p.networks && Array.isArray(p.networks) && p.networks.includes("cosmos:mayachain-mainnet-v1"));
843
- if (!mayaPubkey || !mayaPubkey.address) {
844
- console.log(tag3, "No MAYA pubkey found, skipping MAYA token fetch");
845
- return balances;
846
- }
847
- if (!blockchains.includes("cosmos:mayachain-mainnet-v1")) {
848
- console.log(tag3, "MAYA network not in blockchains list, skipping MAYA token fetch");
849
- return balances;
850
- }
851
- const hasMayaToken = existingBalances.some((b2) => b2.caip === "cosmos:mayachain-mainnet-v1/denom:maya");
852
- if (hasMayaToken) {
853
- console.log(tag3, "MAYA token already exists in balances, skipping");
854
- return balances;
855
- }
856
- console.log(tag3, "MAYA token not found in portfolio, fetching separately...");
857
- console.log(tag3, "MAYA pubkey address:", mayaPubkey.address);
858
- const mayaBalanceResponse = await pioneer.GetPortfolioBalances([
859
- {
860
- caip: "cosmos:mayachain-mainnet-v1/denom:maya",
861
- pubkey: mayaPubkey.address
862
- }
863
- ]);
864
- console.log(tag3, "MAYA balance response:", JSON.stringify(mayaBalanceResponse?.data, null, 2));
865
- if (!mayaBalanceResponse?.data || mayaBalanceResponse.data.length === 0) {
866
- console.log(tag3, "No MAYA token balance returned from GetPortfolioBalances API");
867
- return balances;
868
- }
869
- console.log(tag3, "Found MAYA token balances:", mayaBalanceResponse.data.length);
870
- for (const mayaBalance of mayaBalanceResponse.data) {
871
- if (mayaBalance.caip !== "cosmos:mayachain-mainnet-v1/denom:maya") {
872
- console.log(tag3, "Unexpected balance in MAYA response:", mayaBalance);
873
- continue;
874
- }
875
- const mayaAssetInfo = hydrateAssetData(mayaBalance.caip);
876
- const isToken = mayaBalance.caip.includes("/denom:") && !mayaBalance.caip.endsWith("/denom:cacao");
877
- const mayaTokenBalance = {
878
- context,
879
- chart: "pioneer",
880
- contextType: context.split(":")[0],
881
- name: mayaAssetInfo?.name || "Maya Token",
882
- caip: mayaBalance.caip,
883
- icon: mayaAssetInfo?.icon || "https://pioneers.dev/coins/maya.png",
884
- pubkey: mayaPubkey.address,
885
- ticker: mayaAssetInfo?.symbol || "MAYA",
886
- ref: `${context}${mayaBalance.caip}`,
887
- identifier: createBalanceIdentifier(mayaBalance.caip, mayaPubkey.address),
888
- networkId: "cosmos:mayachain-mainnet-v1",
889
- symbol: mayaAssetInfo?.symbol || "MAYA",
890
- type: mayaAssetInfo?.type || "token",
891
- token: isToken,
892
- decimal: mayaAssetInfo?.decimal,
893
- balance: mayaBalance.balance?.toString() || "0",
894
- priceUsd: parseFloat(mayaBalance.priceUsd) || 0,
895
- valueUsd: parseFloat(mayaBalance.valueUsd) || 0,
896
- updated: new Date().getTime()
897
- };
898
- console.log(tag3, "Adding MAYA token to balances:", mayaTokenBalance);
899
- balances.push(mayaTokenBalance);
900
- }
901
- } catch (mayaError) {
902
- console.error(tag3, "Error fetching MAYA token balance:", mayaError);
903
- }
904
- return balances;
905
- }
906
-
907
- // src/charts/cosmos-staking.ts
908
- var tag4 = "| charts-cosmos-staking |";
909
- async function getCosmosStakingCharts(params) {
910
- const { blockchains, pioneer, pubkeys, context } = params;
911
- const balances = [];
912
- try {
913
- console.log(tag4, "Adding Cosmos staking positions to charts...");
914
- const cosmosPubkeys = pubkeys.filter((p) => p.networks && Array.isArray(p.networks) && p.networks.some((n) => n.includes("cosmos:cosmoshub") || n.includes("cosmos:osmosis")));
915
- if (cosmosPubkeys.length === 0) {
916
- console.log(tag4, "No cosmos pubkeys found for staking positions");
917
- return balances;
918
- }
919
- console.log(tag4, "Found cosmos pubkeys for staking:", cosmosPubkeys.length);
920
- for (const cosmosPubkey of cosmosPubkeys) {
921
- if (!cosmosPubkey.address) {
922
- continue;
923
- }
924
- const cosmosNetworks = cosmosPubkey.networks.filter((n) => n.includes("cosmos:cosmoshub") || n.includes("cosmos:osmosis"));
925
- for (const networkId of cosmosNetworks) {
926
- if (!blockchains.includes(networkId)) {
927
- continue;
928
- }
929
- await fetchStakingPositionsForNetwork(networkId, cosmosPubkey.address, context, pioneer, balances);
930
- }
931
- }
932
- } catch (e) {
933
- console.error(tag4, "Error adding cosmos staking positions:", e);
934
- }
935
- return balances;
936
- }
937
- async function fetchStakingPositionsForNetwork(networkId, address, context, pioneer, balances) {
938
- try {
939
- console.log(tag4, `Fetching staking positions for ${address} on ${networkId}...`);
940
- let network;
941
- if (networkId === "cosmos:cosmoshub-4") {
942
- network = "cosmos";
943
- } else if (networkId === "cosmos:osmosis-1") {
944
- network = "osmosis";
945
- } else {
946
- console.error(tag4, `Unsupported networkId for staking: ${networkId}`);
947
- return;
948
- }
949
- const stakingResponse = await pioneer.GetStakingPositions({
950
- network,
951
- address
952
- });
953
- if (!stakingResponse?.data || !Array.isArray(stakingResponse.data)) {
954
- console.log(tag4, `No staking positions found for ${address} on ${networkId}`);
955
- return;
956
- }
957
- console.log(tag4, `Found ${stakingResponse.data.length} staking positions for ${networkId}`);
958
- for (const position of stakingResponse.data) {
959
- const processedPosition = processStakingPosition(position, address, context, networkId);
960
- if (processedPosition && !checkDuplicateBalance(balances, processedPosition.caip, processedPosition.pubkey, processedPosition.validator)) {
961
- balances.push(processedPosition);
962
- console.log(tag4, `Added ${position.type} position:`, {
963
- balance: processedPosition.balance,
964
- ticker: processedPosition.ticker,
965
- valueUsd: processedPosition.valueUsd,
966
- validator: processedPosition.validator
967
- });
968
- }
969
- }
970
- } catch (stakingError) {
971
- console.error(tag4, `Error fetching staking positions for ${address} on ${networkId}:`, stakingError);
972
- }
973
- }
974
- function processStakingPosition(position, address, context, networkId) {
975
- if (!position.balance || position.balance <= 0 || !position.caip) {
976
- return null;
977
- }
978
- const stakingAssetInfo = hydrateAssetData(position.caip);
979
- const stakingBalance = {
980
- context,
981
- chart: "staking",
982
- contextType: context.split(":")[0],
983
- name: stakingAssetInfo?.name || position.name || `${position.type} Position`,
984
- caip: position.caip,
985
- icon: stakingAssetInfo?.icon || position.icon || "",
986
- pubkey: address,
987
- ticker: stakingAssetInfo?.symbol || position.ticker || position.symbol || "UNK",
988
- ref: `${context}${position.caip}`,
989
- identifier: createBalanceIdentifier(position.caip, address),
990
- networkId,
991
- symbol: stakingAssetInfo?.symbol || position.symbol || position.ticker || "UNK",
992
- type: stakingAssetInfo?.type || position.type || "staking",
993
- token: false,
994
- decimal: stakingAssetInfo?.decimal,
995
- balance: position.balance.toString(),
996
- priceUsd: position.priceUsd || 0,
997
- valueUsd: position.valueUsd || position.balance * (position.priceUsd || 0),
998
- status: position.status || "active",
999
- validator: position.validatorAddress || position.validator || "",
1000
- updated: new Date().getTime()
1001
- };
1002
- return stakingBalance;
1003
- }
1004
-
1005
- // src/charts/index.ts
1006
- var tag5 = "| getCharts |";
1007
- var getCharts = async (blockchains, pioneer, pubkeys, context) => {
1008
- try {
1009
- const balances = [];
1010
- console.log(tag5, "init");
1011
- const params = {
1012
- blockchains,
1013
- pioneer,
1014
- pubkeys,
1015
- context
1016
- };
1017
- const evmBalances = await getEvmCharts(params);
1018
- balances.push(...evmBalances);
1019
- const mayaBalances = await getMayaCharts(params, balances);
1020
- balances.push(...mayaBalances);
1021
- const stakingBalances = await getCosmosStakingCharts(params);
1022
- balances.push(...stakingBalances);
1023
- return balances;
1024
- } catch (error) {
1025
- console.error(tag5, "Error processing charts:", error);
1026
- throw error;
1027
- }
1028
- };
1029
-
1030
569
  // src/getPubkey.ts
1031
570
  import { NetworkIdToChain } from "@pioneer-platform/pioneer-caip";
1032
571
  import {
@@ -1595,7 +1134,7 @@ async function fetchTokenPriceInUsd(pioneer, caip) {
1595
1134
  }
1596
1135
  }
1597
1136
  async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, feeLevel = 5) {
1598
- const tag6 = TAG2 + " | createUnsignedEvmTx | ";
1137
+ const tag = TAG2 + " | createUnsignedEvmTx | ";
1599
1138
  try {
1600
1139
  if (!pioneer)
1601
1140
  throw new Error("Failed to initialize Pioneer");
@@ -1616,11 +1155,11 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1616
1155
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
1617
1156
  }
1618
1157
  const address = pubkeyContext.address || pubkeyContext.pubkey;
1619
- console.log(tag6, "✅ Using FROM address from pubkeyContext:", address, "note:", pubkeyContext.note);
1158
+ console.log(tag, "✅ Using FROM address from pubkeyContext:", address, "note:", pubkeyContext.note);
1620
1159
  if (!address)
1621
1160
  throw new Error("No address found for the specified network");
1622
1161
  const gasPriceData = await pioneer.GetGasPriceByNetwork({ networkId });
1623
- console.log(tag6, "Gas price data from API:", JSON.stringify(gasPriceData.data));
1162
+ console.log(tag, "Gas price data from API:", JSON.stringify(gasPriceData.data));
1624
1163
  let gasPrice;
1625
1164
  const defaultGasPrices = {
1626
1165
  1: 30,
@@ -1636,75 +1175,75 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1636
1175
  let selectedGasPrice;
1637
1176
  if (feeLevel <= 2) {
1638
1177
  selectedGasPrice = gasPriceData.data.slow || gasPriceData.data.average || gasPriceData.data.fastest;
1639
- console.log(tag6, "Selecting SLOW gas price from API");
1178
+ console.log(tag, "Selecting SLOW gas price from API");
1640
1179
  } else if (feeLevel >= 8) {
1641
1180
  selectedGasPrice = gasPriceData.data.fastest || gasPriceData.data.fast || gasPriceData.data.average;
1642
- console.log(tag6, "Selecting FAST gas price from API");
1181
+ console.log(tag, "Selecting FAST gas price from API");
1643
1182
  } else {
1644
1183
  selectedGasPrice = gasPriceData.data.average || gasPriceData.data.fast || gasPriceData.data.fastest;
1645
- console.log(tag6, "Selecting AVERAGE gas price from API");
1184
+ console.log(tag, "Selecting AVERAGE gas price from API");
1646
1185
  }
1647
1186
  let gasPriceNum;
1648
1187
  if (selectedGasPrice === undefined || selectedGasPrice === null) {
1649
- console.warn(tag6, "No valid gas price found in API response, using fallback:", fallbackGasGwei, "gwei");
1188
+ console.warn(tag, "No valid gas price found in API response, using fallback:", fallbackGasGwei, "gwei");
1650
1189
  gasPriceNum = fallbackGasGwei;
1651
1190
  } else {
1652
1191
  gasPriceNum = typeof selectedGasPrice === "string" ? parseFloat(selectedGasPrice) : selectedGasPrice;
1653
1192
  if (isNaN(gasPriceNum) || !isFinite(gasPriceNum)) {
1654
- console.warn(tag6, "Invalid gas price (NaN or Infinite):", selectedGasPrice, "- using fallback:", fallbackGasGwei, "gwei");
1193
+ console.warn(tag, "Invalid gas price (NaN or Infinite):", selectedGasPrice, "- using fallback:", fallbackGasGwei, "gwei");
1655
1194
  gasPriceNum = fallbackGasGwei;
1656
1195
  }
1657
1196
  }
1658
1197
  gasPrice = BigInt(Math.round(gasPriceNum * 1e9));
1659
1198
  if (gasPrice < MIN_GAS_PRICE_WEI) {
1660
- console.warn(tag6, "Gas price from API too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1199
+ console.warn(tag, "Gas price from API too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1661
1200
  gasPrice = MIN_GAS_PRICE_WEI;
1662
1201
  }
1663
1202
  } else {
1664
1203
  let gasPriceNum;
1665
1204
  if (gasPriceData.data === undefined || gasPriceData.data === null) {
1666
- console.warn(tag6, "Gas price API returned null/undefined, using fallback:", fallbackGasGwei, "gwei");
1205
+ console.warn(tag, "Gas price API returned null/undefined, using fallback:", fallbackGasGwei, "gwei");
1667
1206
  gasPriceNum = fallbackGasGwei;
1668
1207
  } else {
1669
1208
  gasPriceNum = typeof gasPriceData.data === "string" ? parseFloat(gasPriceData.data) : gasPriceData.data;
1670
1209
  if (isNaN(gasPriceNum) || !isFinite(gasPriceNum)) {
1671
- console.warn(tag6, "Invalid gas price (NaN or Infinite):", gasPriceData.data, "- using fallback:", fallbackGasGwei, "gwei");
1210
+ console.warn(tag, "Invalid gas price (NaN or Infinite):", gasPriceData.data, "- using fallback:", fallbackGasGwei, "gwei");
1672
1211
  gasPriceNum = fallbackGasGwei;
1673
1212
  }
1674
1213
  }
1675
1214
  const baseGasPrice = BigInt(Math.round(gasPriceNum * 1e9));
1676
1215
  if (feeLevel <= 2) {
1677
1216
  gasPrice = baseGasPrice * BigInt(80) / BigInt(100);
1678
- console.log(tag6, "Using SLOW gas price (80% of base)");
1217
+ console.log(tag, "Using SLOW gas price (80% of base)");
1679
1218
  } else if (feeLevel >= 8) {
1680
1219
  gasPrice = baseGasPrice * BigInt(150) / BigInt(100);
1681
- console.log(tag6, "Using FAST gas price (150% of base)");
1220
+ console.log(tag, "Using FAST gas price (150% of base)");
1682
1221
  } else {
1683
1222
  gasPrice = baseGasPrice;
1684
- console.log(tag6, "Using AVERAGE gas price (100% of base)");
1223
+ console.log(tag, "Using AVERAGE gas price (100% of base)");
1685
1224
  }
1686
1225
  if (gasPrice < MIN_GAS_PRICE_WEI) {
1687
- console.warn(tag6, "Gas price too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1226
+ console.warn(tag, "Gas price too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1688
1227
  gasPrice = MIN_GAS_PRICE_WEI;
1689
1228
  }
1690
1229
  }
1691
- console.log(tag6, "Final gasPrice:", gasPrice.toString(), "wei (", Number(gasPrice) / 1e9, "gwei)");
1230
+ console.log(tag, "Final gasPrice:", gasPrice.toString(), "wei (", Number(gasPrice) / 1e9, "gwei)");
1692
1231
  let nonce;
1693
1232
  try {
1694
1233
  const nonceData = await pioneer.GetNonceByNetwork({ networkId, address });
1695
1234
  nonce = nonceData.data.nonce;
1696
1235
  if (nonce === undefined || nonce === null) {
1697
- console.log(tag6, "No nonce found for address (likely fresh address), defaulting to 0");
1236
+ console.log(tag, "No nonce found for address (likely fresh address), defaulting to 0");
1698
1237
  nonce = 0;
1699
1238
  }
1700
1239
  } catch (nonceError) {
1701
- console.log(tag6, "Failed to fetch nonce (likely fresh address):", nonceError.message, "- defaulting to 0");
1240
+ console.log(tag, "Failed to fetch nonce (likely fresh address):", nonceError.message, "- defaulting to 0");
1702
1241
  nonce = 0;
1703
1242
  }
1704
1243
  const balanceData = await pioneer.GetBalanceAddressByNetwork({ networkId, address });
1705
1244
  const balanceEth = parseFloat(balanceData.data.nativeBalance || balanceData.data.balance || "0");
1706
1245
  const balance = BigInt(Math.round(balanceEth * 1000000000000000000));
1707
- console.log(tag6, "Native ETH balance from API:", balanceData.data.nativeBalance || balanceData.data.balance, "ETH (", balance.toString(), "wei)");
1246
+ console.log(tag, "Native ETH balance from API:", balanceData.data.nativeBalance || balanceData.data.balance, "ETH (", balance.toString(), "wei)");
1708
1247
  if (balance <= 0n)
1709
1248
  throw new Error("Wallet balance is zero");
1710
1249
  const assetType = classifyCaipEvm(caip);
@@ -1717,7 +1256,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1717
1256
  let gasLimit;
1718
1257
  if (isThorchainOperation) {
1719
1258
  gasLimit = BigInt(120000);
1720
- console.log(tag6, "Using higher gas limit for THORChain swap:", gasLimit.toString());
1259
+ console.log(tag, "Using higher gas limit for THORChain swap:", gasLimit.toString());
1721
1260
  } else {
1722
1261
  gasLimit = chainId === 1 ? BigInt(21000) : BigInt(25000);
1723
1262
  }
@@ -1733,7 +1272,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1733
1272
  }
1734
1273
  const buffer = BigInt(100);
1735
1274
  amountWei = balance - gasFee - buffer;
1736
- console.log(tag6, "isMax calculation - balance:", balance.toString(), "gasFee:", gasFee.toString(), "buffer:", buffer.toString(), "amountWei:", amountWei.toString());
1275
+ console.log(tag, "isMax calculation - balance:", balance.toString(), "gasFee:", gasFee.toString(), "buffer:", buffer.toString(), "amountWei:", amountWei.toString());
1737
1276
  } else {
1738
1277
  amountWei = BigInt(Math.round(amount * 1000000000000000000));
1739
1278
  if (amountWei + gasFee > balance) {
@@ -1743,14 +1282,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1743
1282
  const isThorchainSwap = memo && (memo.startsWith("=") || memo.startsWith("SWAP") || memo.includes(":"));
1744
1283
  let txData = "0x";
1745
1284
  if (isThorchainSwap) {
1746
- console.log(tag6, "Detected THORChain swap, encoding deposit data for memo:", memo);
1285
+ console.log(tag, "Detected THORChain swap, encoding deposit data for memo:", memo);
1747
1286
  let fixedMemo = memo;
1748
1287
  if (memo.startsWith("=:b:") || memo.startsWith("=:btc:")) {
1749
1288
  fixedMemo = memo.replace(/^=:(b|btc):/, "=:BTC.BTC:");
1750
- console.log(tag6, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
1289
+ console.log(tag, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
1751
1290
  } else if (memo.startsWith("=:e:") || memo.startsWith("=:eth:")) {
1752
1291
  fixedMemo = memo.replace(/^=:(e|eth):/, "=:ETH.ETH:");
1753
- console.log(tag6, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
1292
+ console.log(tag, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
1754
1293
  }
1755
1294
  if (fixedMemo.length > 250) {
1756
1295
  throw new Error(`Memo too long for THORChain: ${fixedMemo.length} bytes (max 250)`);
@@ -1766,14 +1305,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1766
1305
  if (ethInbound) {
1767
1306
  vaultAddress = ethInbound.address;
1768
1307
  routerAddress = ethInbound.router || to;
1769
- console.log(tag6, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
1308
+ console.log(tag, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
1770
1309
  to = routerAddress;
1771
1310
  } else {
1772
1311
  throw new Error("ETH inbound is halted or not found - cannot proceed with swap");
1773
1312
  }
1774
1313
  }
1775
1314
  } catch (fetchError) {
1776
- console.error(tag6, "Failed to fetch inbound addresses:", fetchError);
1315
+ console.error(tag, "Failed to fetch inbound addresses:", fetchError);
1777
1316
  throw new Error(`Cannot proceed with THORChain swap - failed to fetch inbound addresses: ${fetchError.message}`);
1778
1317
  }
1779
1318
  if (vaultAddress === "0x0000000000000000000000000000000000000000") {
@@ -1793,7 +1332,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1793
1332
  const paddingLength = (32 - memoBytes.length % 32) % 32;
1794
1333
  const memoPadded = memoHex + "0".repeat(paddingLength * 2);
1795
1334
  txData = "0x" + functionSelector + vaultPadded + assetPadded + amountPadded + stringOffset + expiryPadded + stringLength + memoPadded;
1796
- console.log(tag6, "Encoded THORChain depositWithExpiry data:", {
1335
+ console.log(tag, "Encoded THORChain depositWithExpiry data:", {
1797
1336
  functionSelector: "0x" + functionSelector,
1798
1337
  vault: vaultAddress,
1799
1338
  asset: assetAddress,
@@ -1803,9 +1342,9 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1803
1342
  stringOffset: "0x" + stringOffset,
1804
1343
  fullData: txData
1805
1344
  });
1806
- console.log(tag6, "Native ETH swap - value will be set to:", amountWei.toString(), "wei");
1345
+ console.log(tag, "Native ETH swap - value will be set to:", amountWei.toString(), "wei");
1807
1346
  } catch (error) {
1808
- console.error(tag6, "Error encoding THORChain deposit:", error);
1347
+ console.error(tag, "Error encoding THORChain deposit:", error);
1809
1348
  throw new Error(`Failed to encode THORChain swap: ${error.message}`);
1810
1349
  }
1811
1350
  } else if (memo) {
@@ -1824,19 +1363,19 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1824
1363
  }
1825
1364
  case "erc20": {
1826
1365
  const contractAddress = extractContractAddressFromCaip(caip);
1827
- console.log(tag6, "Fetching token decimals from contract:", contractAddress, "on network:", networkId);
1366
+ console.log(tag, "Fetching token decimals from contract:", contractAddress, "on network:", networkId);
1828
1367
  let tokenDecimals;
1829
1368
  try {
1830
- console.log(tag6, "Fetching token decimals via pioneer-server API for", contractAddress, "on", networkId);
1369
+ console.log(tag, "Fetching token decimals via pioneer-server API for", contractAddress, "on", networkId);
1831
1370
  const decimalsResponse = await pioneer.GetTokenDecimals({
1832
1371
  networkId,
1833
1372
  contractAddress
1834
1373
  });
1835
1374
  tokenDecimals = Number(decimalsResponse.data.decimals);
1836
- console.log(tag6, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
1375
+ console.log(tag, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
1837
1376
  } catch (error) {
1838
- console.error(tag6, "Failed to fetch token decimals from pioneer-server:", error);
1839
- console.warn(tag6, "⚠️ FALLBACK: Using default 18 decimals - THIS MAY BE INCORRECT!");
1377
+ console.error(tag, "Failed to fetch token decimals from pioneer-server:", error);
1378
+ console.warn(tag, "⚠️ FALLBACK: Using default 18 decimals - THIS MAY BE INCORRECT!");
1840
1379
  tokenDecimals = 18;
1841
1380
  }
1842
1381
  const tokenMultiplier = 10n ** BigInt(tokenDecimals);
@@ -1857,7 +1396,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1857
1396
  amountWei = tokenBalance;
1858
1397
  } else {
1859
1398
  amountWei = BigInt(Math.round(amount * Number(tokenMultiplier)));
1860
- console.log(tag6, "Token amount calculation:", {
1399
+ console.log(tag, "Token amount calculation:", {
1861
1400
  inputAmount: amount,
1862
1401
  decimals: tokenDecimals,
1863
1402
  multiplier: tokenMultiplier,
@@ -1893,23 +1432,23 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1893
1432
  }
1894
1433
  if (pubkeyContext.addressNListMaster) {
1895
1434
  unsignedTx.addressNList = pubkeyContext.addressNListMaster;
1896
- console.log(tag6, "✅ Using addressNListMaster from pubkey context:", unsignedTx.addressNList, "for address:", address);
1435
+ console.log(tag, "✅ Using addressNListMaster from pubkey context:", unsignedTx.addressNList, "for address:", address);
1897
1436
  } else if (pubkeyContext.pathMaster) {
1898
1437
  unsignedTx.addressNList = bip32ToAddressNList(pubkeyContext.pathMaster);
1899
- console.log(tag6, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
1438
+ console.log(tag, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
1900
1439
  } else if (pubkeyContext.addressNList) {
1901
1440
  unsignedTx.addressNList = pubkeyContext.addressNList;
1902
- console.log(tag6, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
1441
+ console.log(tag, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
1903
1442
  } else if (pubkeyContext.path) {
1904
1443
  unsignedTx.addressNList = bip32ToAddressNList(pubkeyContext.path);
1905
- console.log(tag6, "⚠️ Using regular path (not master):", pubkeyContext.path, "→", unsignedTx.addressNList);
1444
+ console.log(tag, "⚠️ Using regular path (not master):", pubkeyContext.path, "→", unsignedTx.addressNList);
1906
1445
  } else {
1907
1446
  unsignedTx.addressNList = [2147483648 + 44, 2147483648 + 60, 2147483648, 0, 0];
1908
- console.warn(tag6, "⚠️ No path info in pubkey context, using default account 0");
1447
+ console.warn(tag, "⚠️ No path info in pubkey context, using default account 0");
1909
1448
  }
1910
1449
  return unsignedTx;
1911
1450
  } catch (error) {
1912
- console.error(tag6, "Error:", error.message);
1451
+ console.error(tag, "Error:", error.message);
1913
1452
  throw error;
1914
1453
  }
1915
1454
  }
@@ -1918,7 +1457,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1918
1457
  import { caipToNetworkId as caipToNetworkId2 } from "@pioneer-platform/pioneer-caip";
1919
1458
  var TAG3 = " | createUnsignedUxtoTx | ";
1920
1459
  async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax) {
1921
- let tag6 = TAG3 + " | createUnsignedRippleTx | ";
1460
+ let tag = TAG3 + " | createUnsignedRippleTx | ";
1922
1461
  try {
1923
1462
  if (!pioneer)
1924
1463
  throw new Error("Failed to init! pioneer");
@@ -1929,7 +1468,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
1929
1468
  if (!pubkeyContext.networks?.includes(networkId)) {
1930
1469
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
1931
1470
  }
1932
- console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
1471
+ console.log(tag, `✅ Using pubkeyContext for network ${networkId}:`, {
1933
1472
  address: pubkeyContext.address
1934
1473
  });
1935
1474
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
@@ -1997,7 +1536,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
1997
1536
  };
1998
1537
  return unsignedTx;
1999
1538
  } catch (error) {
2000
- console.error(tag6, "Error:", error);
1539
+ console.error(tag, "Error:", error);
2001
1540
  throw error;
2002
1541
  }
2003
1542
  }
@@ -2137,7 +1676,7 @@ var thorchainDepositTemplate = (params) => ({
2137
1676
  // src/txbuilder/createUnsignedTendermintTx.ts
2138
1677
  var TAG4 = " | createUnsignedTendermintTx | ";
2139
1678
  async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, to) {
2140
- const tag6 = TAG4 + " | createUnsignedTendermintTx | ";
1679
+ const tag = TAG4 + " | createUnsignedTendermintTx | ";
2141
1680
  try {
2142
1681
  if (!pioneer)
2143
1682
  throw new Error("Failed to init! pioneer");
@@ -2148,7 +1687,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2148
1687
  if (!pubkeyContext.networks?.includes(networkId)) {
2149
1688
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2150
1689
  }
2151
- console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
1690
+ console.log(tag, `✅ Using pubkeyContext for network ${networkId}:`, {
2152
1691
  address: pubkeyContext.address,
2153
1692
  addressNList: pubkeyContext.addressNList || pubkeyContext.addressNListMaster
2154
1693
  });
@@ -2171,11 +1710,11 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2171
1710
  }
2172
1711
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
2173
1712
  let asset = caip.split(":")[1];
2174
- console.log(tag6, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
1713
+ console.log(tag, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
2175
1714
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
2176
- console.log(tag6, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
1715
+ console.log(tag, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
2177
1716
  let balanceInfo = await pioneer.GetPubkeyBalance({ asset: chain, pubkey: fromAddress });
2178
- console.log(tag6, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
1717
+ console.log(tag, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
2179
1718
  let account_number, sequence;
2180
1719
  if (accountInfo.account) {
2181
1720
  account_number = accountInfo.account.account_number || "0";
@@ -2186,13 +1725,13 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2186
1725
  } else {
2187
1726
  throw new Error(`Unexpected account info format for ${networkId}: ${JSON.stringify(accountInfo)}`);
2188
1727
  }
2189
- console.log(tag6, `\uD83D\uDCCA Extracted account_number: ${account_number}, sequence: ${sequence}`);
1728
+ console.log(tag, `\uD83D\uDCCA Extracted account_number: ${account_number}, sequence: ${sequence}`);
2190
1729
  if (account_number === "0" || account_number === 0) {
2191
- console.log(tag6, `⚠️ WARNING: Account number is 0 from Pioneer API`);
2192
- console.log(tag6, ` This is likely due to stale Pioneer API cache`);
2193
- console.log(tag6, ` The mayachain-network module queries nodes directly but Pioneer API may be cached`);
2194
- console.log(tag6, ` Proceeding with account_number: 0 but transaction will likely fail`);
2195
- console.log(tag6, ` TODO: Fix Pioneer API to use fresh data from mayachain-network module`);
1730
+ console.log(tag, `⚠️ WARNING: Account number is 0 from Pioneer API`);
1731
+ console.log(tag, ` This is likely due to stale Pioneer API cache`);
1732
+ console.log(tag, ` The mayachain-network module queries nodes directly but Pioneer API may be cached`);
1733
+ console.log(tag, ` Proceeding with account_number: 0 but transaction will likely fail`);
1734
+ console.log(tag, ` TODO: Fix Pioneer API to use fresh data from mayachain-network module`);
2196
1735
  }
2197
1736
  const fees = {
2198
1737
  "cosmos:thorchain-mainnet-v1": 0.02,
@@ -2347,7 +1886,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2347
1886
  }
2348
1887
  }
2349
1888
  } catch (error) {
2350
- console.error(tag6, "Error:", error);
1889
+ console.error(tag, "Error:", error);
2351
1890
  throw error;
2352
1891
  }
2353
1892
  }
@@ -2376,7 +1915,7 @@ function getCoinTypeFromNetworkId(networkId) {
2376
1915
  return coinType;
2377
1916
  }
2378
1917
  async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, feeLevel = 5, changeScriptType) {
2379
- let tag6 = " | createUnsignedUxtoTx | ";
1918
+ let tag = " | createUnsignedUxtoTx | ";
2380
1919
  try {
2381
1920
  if (!pioneer)
2382
1921
  throw Error("Failed to init! pioneer");
@@ -2387,7 +1926,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2387
1926
  if (!pubkeyContext.networks?.includes(networkId)) {
2388
1927
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2389
1928
  }
2390
- console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
1929
+ console.log(tag, `✅ Using pubkeyContext for network ${networkId}:`, {
2391
1930
  address: pubkeyContext.address,
2392
1931
  scriptType: pubkeyContext.scriptType
2393
1932
  });
@@ -2398,15 +1937,15 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2398
1937
  const isSegwit = segwitNetworks.includes(networkId);
2399
1938
  let chain = NetworkIdToChain2[networkId];
2400
1939
  const coinType = getCoinTypeFromNetworkId(networkId);
2401
- console.log(`${tag6}: Using SLIP-44 coin type ${coinType} for ${chain}`);
1940
+ console.log(`${tag}: Using SLIP-44 coin type ${coinType} for ${chain}`);
2402
1941
  const utxos = [];
2403
1942
  for (const pubkey of relevantPubkeys) {
2404
1943
  try {
2405
1944
  let utxosResp = await pioneer.ListUnspent({ network: chain, xpub: pubkey.pubkey });
2406
1945
  utxosResp = utxosResp.data;
2407
- console.log(`${tag6}: ListUnspent response for ${pubkey.scriptType}:`, utxosResp?.length || 0, "UTXOs");
1946
+ console.log(`${tag}: ListUnspent response for ${pubkey.scriptType}:`, utxosResp?.length || 0, "UTXOs");
2408
1947
  if (!utxosResp || !Array.isArray(utxosResp)) {
2409
- console.warn(`${tag6}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
1948
+ console.warn(`${tag}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
2410
1949
  continue;
2411
1950
  }
2412
1951
  let scriptType = pubkey.scriptType;
@@ -2415,10 +1954,10 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2415
1954
  }
2416
1955
  utxos.push(...utxosResp);
2417
1956
  } catch (error) {
2418
- console.error(`${tag6}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
1957
+ console.error(`${tag}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
2419
1958
  }
2420
1959
  }
2421
- console.log(`${tag6}: Total UTXOs collected:`, utxos.length);
1960
+ console.log(`${tag}: Total UTXOs collected:`, utxos.length);
2422
1961
  if (!utxos || utxos.length === 0)
2423
1962
  throw Error("No UTXOs found across all addresses");
2424
1963
  for (const utxo of utxos) {
@@ -2431,14 +1970,14 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2431
1970
  }, {});
2432
1971
  const mostCommonInputType = Object.entries(scriptTypeCount).sort(([, a2], [, b2]) => b2 - a2)[0]?.[0] || "p2pkh";
2433
1972
  const actualChangeScriptType = changeScriptType || mostCommonInputType || relevantPubkeys[0]?.scriptType || "p2pkh";
2434
- console.log(`${tag6}: Input script types:`, scriptTypeCount);
2435
- console.log(`${tag6}: Using change script type: ${actualChangeScriptType} (matches inputs: ${mostCommonInputType})`);
1973
+ console.log(`${tag}: Input script types:`, scriptTypeCount);
1974
+ console.log(`${tag}: Using change script type: ${actualChangeScriptType} (matches inputs: ${mostCommonInputType})`);
2436
1975
  const changeXpubInfo = relevantPubkeys.find((pk) => pk.scriptType === actualChangeScriptType);
2437
1976
  if (!changeXpubInfo) {
2438
1977
  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.`);
2439
1978
  }
2440
1979
  const changeXpub = changeXpubInfo.pubkey;
2441
- console.log(`${tag6}: Change xpub selected for ${actualChangeScriptType}:`, changeXpub?.substring(0, 10) + "...");
1980
+ console.log(`${tag}: Change xpub selected for ${actualChangeScriptType}:`, changeXpub?.substring(0, 10) + "...");
2442
1981
  let changeAddressIndex = await pioneer.GetChangeAddress({
2443
1982
  network: chain,
2444
1983
  xpub: changeXpub
@@ -2458,7 +1997,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2458
1997
  break;
2459
1998
  }
2460
1999
  const path = bipPath;
2461
- console.log(`${tag6}: Change address path: ${path} (coin type: ${coinType}, index: ${changeAddressIndex})`);
2000
+ console.log(`${tag}: Change address path: ${path} (coin type: ${coinType}, index: ${changeAddressIndex})`);
2462
2001
  const changeAddress = {
2463
2002
  path,
2464
2003
  isChange: true,
@@ -2468,7 +2007,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2468
2007
  };
2469
2008
  let feeRateFromNode;
2470
2009
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
2471
- console.log(`${tag6}: Using hardcoded fees for DOGE (10 sat/byte)`);
2010
+ console.log(`${tag}: Using hardcoded fees for DOGE (10 sat/byte)`);
2472
2011
  feeRateFromNode = {
2473
2012
  slow: 10,
2474
2013
  average: 10,
@@ -2481,19 +2020,19 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2481
2020
  try {
2482
2021
  let feeResponse;
2483
2022
  if (pioneer.GetFeeRateByNetwork) {
2484
- console.log(`${tag6}: Trying GetFeeRateByNetwork for ${networkId}`);
2023
+ console.log(`${tag}: Trying GetFeeRateByNetwork for ${networkId}`);
2485
2024
  feeResponse = await pioneer.GetFeeRateByNetwork({ networkId });
2486
2025
  } else {
2487
- console.log(`${tag6}: Using GetFeeRate for ${networkId}`);
2026
+ console.log(`${tag}: Using GetFeeRate for ${networkId}`);
2488
2027
  feeResponse = await pioneer.GetFeeRate({ networkId });
2489
2028
  }
2490
2029
  feeRateFromNode = feeResponse.data;
2491
- console.log(`${tag6}: Got fee rates from API:`, JSON.stringify(feeRateFromNode, null, 2));
2030
+ console.log(`${tag}: Got fee rates from API:`, JSON.stringify(feeRateFromNode, null, 2));
2492
2031
  const conversionThreshold = 500;
2493
2032
  const needsConversion = feeRateFromNode.slow && feeRateFromNode.slow > conversionThreshold || feeRateFromNode.average && feeRateFromNode.average > conversionThreshold || feeRateFromNode.fast && feeRateFromNode.fast > conversionThreshold || feeRateFromNode.fastest && feeRateFromNode.fastest > conversionThreshold;
2494
2033
  if (needsConversion) {
2495
- console.warn(`${tag6}: Detected wrong units - values appear to be in sat/kB instead of sat/byte`);
2496
- console.warn(`${tag6}: Original values:`, {
2034
+ console.warn(`${tag}: Detected wrong units - values appear to be in sat/kB instead of sat/byte`);
2035
+ console.warn(`${tag}: Original values:`, {
2497
2036
  slow: feeRateFromNode.slow,
2498
2037
  average: feeRateFromNode.average,
2499
2038
  fast: feeRateFromNode.fast,
@@ -2507,12 +2046,12 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2507
2046
  feeRateFromNode.fast = feeRateFromNode.fast / 1000;
2508
2047
  if (feeRateFromNode.fastest)
2509
2048
  feeRateFromNode.fastest = feeRateFromNode.fastest / 1000;
2510
- console.warn(`${tag6}: Converted to sat/byte:`, feeRateFromNode);
2049
+ console.warn(`${tag}: Converted to sat/byte:`, feeRateFromNode);
2511
2050
  }
2512
2051
  if (!feeRateFromNode || typeof feeRateFromNode !== "object") {
2513
2052
  throw new Error(`Invalid fee rate response from API: ${JSON.stringify(feeRateFromNode)}`);
2514
2053
  }
2515
- console.log(`${tag6}: Available fee rates:`, {
2054
+ console.log(`${tag}: Available fee rates:`, {
2516
2055
  slow: feeRateFromNode.slow,
2517
2056
  average: feeRateFromNode.average,
2518
2057
  fast: feeRateFromNode.fast,
@@ -2522,33 +2061,33 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2522
2061
  throw new Error(`No valid fee rates in API response: ${JSON.stringify(feeRateFromNode)}`);
2523
2062
  }
2524
2063
  } catch (error) {
2525
- console.error(`${tag6}: Failed to get fee rates from Pioneer API:`, error.message || error);
2064
+ console.error(`${tag}: Failed to get fee rates from Pioneer API:`, error.message || error);
2526
2065
  throw new Error(`Unable to get fee rate for network ${networkId}: ${error.message || "API unavailable"}`);
2527
2066
  }
2528
2067
  }
2529
2068
  let effectiveFeeRate;
2530
- console.log(`${tag6}: Using fee level ${feeLevel}`);
2069
+ console.log(`${tag}: Using fee level ${feeLevel}`);
2531
2070
  switch (feeLevel) {
2532
2071
  case 1:
2533
2072
  case 2:
2534
2073
  effectiveFeeRate = feeRateFromNode.slow || feeRateFromNode.average;
2535
- console.log(`${tag6}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
2074
+ console.log(`${tag}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
2536
2075
  break;
2537
2076
  case 3:
2538
2077
  case 4:
2539
2078
  effectiveFeeRate = feeRateFromNode.average || feeRateFromNode.fast;
2540
- console.log(`${tag6}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
2079
+ console.log(`${tag}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
2541
2080
  break;
2542
2081
  case 5:
2543
2082
  effectiveFeeRate = feeRateFromNode.fastest || feeRateFromNode.fast;
2544
- console.log(`${tag6}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
2083
+ console.log(`${tag}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
2545
2084
  break;
2546
2085
  default:
2547
2086
  throw new Error(`Invalid fee level: ${feeLevel}. Must be 1-5`);
2548
2087
  }
2549
2088
  if (!effectiveFeeRate)
2550
2089
  throw new Error("Unable to get fee rate for network");
2551
- console.log(`${tag6}: Using fee rate from API:`, {
2090
+ console.log(`${tag}: Using fee rate from API:`, {
2552
2091
  feeLevel,
2553
2092
  selectedRate: effectiveFeeRate,
2554
2093
  description: feeLevel <= 2 ? "slow" : feeLevel <= 4 ? "average" : "fast"
@@ -2558,22 +2097,22 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2558
2097
  effectiveFeeRate = Math.ceil(effectiveFeeRate);
2559
2098
  const MIN_RELAY_FEE_RATE = 3;
2560
2099
  if (effectiveFeeRate < MIN_RELAY_FEE_RATE) {
2561
- console.log(`${tag6}: Fee rate ${effectiveFeeRate} is below minimum relay fee, increasing to ${MIN_RELAY_FEE_RATE} sat/vB`);
2100
+ console.log(`${tag}: Fee rate ${effectiveFeeRate} is below minimum relay fee, increasing to ${MIN_RELAY_FEE_RATE} sat/vB`);
2562
2101
  effectiveFeeRate = MIN_RELAY_FEE_RATE;
2563
2102
  }
2564
- console.log(`${tag6}: Final fee rate to use (rounded, with minimums): ${effectiveFeeRate} sat/vB`);
2103
+ console.log(`${tag}: Final fee rate to use (rounded, with minimums): ${effectiveFeeRate} sat/vB`);
2565
2104
  amount = parseInt(String(amount * 1e8));
2566
2105
  if (amount <= 0 && !isMax)
2567
2106
  throw Error("Invalid amount! 0");
2568
2107
  const totalBalance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
2569
- console.log(`${tag6}: Coin selection inputs:`, {
2108
+ console.log(`${tag}: Coin selection inputs:`, {
2570
2109
  utxoCount: utxos.length,
2571
2110
  totalBalance: totalBalance / 1e8,
2572
2111
  requestedAmount: amount / 1e8,
2573
2112
  isMax,
2574
2113
  feeRate: effectiveFeeRate
2575
2114
  });
2576
- console.log(`${tag6}: UTXO details for coin selection:`, utxos.map((u) => ({
2115
+ console.log(`${tag}: UTXO details for coin selection:`, utxos.map((u) => ({
2577
2116
  value: u.value,
2578
2117
  txid: u.txid?.substring(0, 10) + "...",
2579
2118
  vout: u.vout,
@@ -2587,8 +2126,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2587
2126
  } else {
2588
2127
  result = import_coinselect.default(utxos, [{ address: to, value: amount }], effectiveFeeRate);
2589
2128
  }
2590
- console.log(tag6, "coinSelect result object:", result);
2591
- console.log(tag6, "coinSelect result.inputs:", result?.inputs);
2129
+ console.log(tag, "coinSelect result object:", result);
2130
+ console.log(tag, "coinSelect result.inputs:", result?.inputs);
2592
2131
  if (!result || !result.inputs) {
2593
2132
  const errorDetails = {
2594
2133
  utxoCount: utxos.length,
@@ -2597,7 +2136,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2597
2136
  feeRate: effectiveFeeRate,
2598
2137
  insufficientFunds: totalBalance < amount
2599
2138
  };
2600
- console.error(`${tag6}: Coin selection failed:`, errorDetails);
2139
+ console.error(`${tag}: Coin selection failed:`, errorDetails);
2601
2140
  if (utxos.length === 0) {
2602
2141
  throw Error("No UTXOs available for coin selection");
2603
2142
  } else if (totalBalance < amount) {
@@ -2613,7 +2152,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2613
2152
  throw Error("Failed to create transaction: Missing outputs");
2614
2153
  if (fee === undefined)
2615
2154
  throw Error("Failed to calculate transaction fee");
2616
- console.log(`${tag6}: Transaction built with:`, {
2155
+ console.log(`${tag}: Transaction built with:`, {
2617
2156
  feeLevel,
2618
2157
  effectiveFeeRate: `${effectiveFeeRate} sat/vB`,
2619
2158
  calculatedFee: `${fee} satoshis`,
@@ -2621,8 +2160,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2621
2160
  outputCount: outputs.length
2622
2161
  });
2623
2162
  const uniqueInputSet = new Set;
2624
- console.log(tag6, "inputs:", inputs);
2625
- console.log(tag6, "inputs:", inputs[0]);
2163
+ console.log(tag, "inputs:", inputs);
2164
+ console.log(tag, "inputs:", inputs[0]);
2626
2165
  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 }) => ({
2627
2166
  addressNList: bip32ToAddressNList2(path2),
2628
2167
  scriptType,
@@ -2751,7 +2290,7 @@ class TransactionManager {
2751
2290
  throw new Error(`Unsupported CAIP: ${caipString}`);
2752
2291
  }
2753
2292
  async transfer({ caip, to, amount, memo, isMax = false, feeLevel = 5, changeScriptType }) {
2754
- let tag6 = TAG5 + " | transfer | ";
2293
+ let tag = TAG5 + " | transfer | ";
2755
2294
  try {
2756
2295
  if (!this.pioneer)
2757
2296
  throw Error("Failed to init! pioneer");
@@ -2789,12 +2328,12 @@ class TransactionManager {
2789
2328
  }
2790
2329
  return unsignedTx;
2791
2330
  } catch (e) {
2792
- console.error(tag6, e);
2331
+ console.error(tag, e);
2793
2332
  throw e;
2794
2333
  }
2795
2334
  }
2796
2335
  async sign({ caip, unsignedTx }) {
2797
- let tag6 = TAG5 + " | sign | ";
2336
+ let tag = TAG5 + " | sign | ";
2798
2337
  try {
2799
2338
  if (!this.pioneer)
2800
2339
  throw Error("Failed to init! pioneer");
@@ -2880,20 +2419,20 @@ class TransactionManager {
2880
2419
  }
2881
2420
  case "cosmos:mayachain-mainnet-v1/slip44:931":
2882
2421
  case "cosmos:mayachain-mainnet-v1/denom:maya": {
2883
- console.log(tag6, "\uD83D\uDD0D ===== MAYACHAIN SIGNING AUDIT =====");
2884
- console.log(tag6, "\uD83D\uDCCB unsignedTx:", JSON.stringify(unsignedTx, null, 2));
2885
- console.log(tag6, "\uD83D\uDD11 unsignedTx.addressNList:", unsignedTx.addressNList);
2886
- console.log(tag6, "\uD83D\uDCCD unsignedTx.signerAddress:", unsignedTx.signerAddress);
2887
- console.log(tag6, "\uD83C\uDF10 pubkeyContext:", this.pubkeyContext);
2888
- console.log(tag6, "\uD83D\uDD10 pubkeyContext.addressNList:", this.pubkeyContext?.addressNList);
2889
- console.log(tag6, "\uD83D\uDD10 pubkeyContext.addressNListMaster:", this.pubkeyContext?.addressNListMaster);
2890
- console.log(tag6, "\uD83D\uDCEC pubkeyContext.address:", this.pubkeyContext?.address);
2891
- console.log(tag6, "=======================================");
2422
+ console.log(tag, "\uD83D\uDD0D ===== MAYACHAIN SIGNING AUDIT =====");
2423
+ console.log(tag, "\uD83D\uDCCB unsignedTx:", JSON.stringify(unsignedTx, null, 2));
2424
+ console.log(tag, "\uD83D\uDD11 unsignedTx.addressNList:", unsignedTx.addressNList);
2425
+ console.log(tag, "\uD83D\uDCCD unsignedTx.signerAddress:", unsignedTx.signerAddress);
2426
+ console.log(tag, "\uD83C\uDF10 pubkeyContext:", this.pubkeyContext);
2427
+ console.log(tag, "\uD83D\uDD10 pubkeyContext.addressNList:", this.pubkeyContext?.addressNList);
2428
+ console.log(tag, "\uD83D\uDD10 pubkeyContext.addressNListMaster:", this.pubkeyContext?.addressNListMaster);
2429
+ console.log(tag, "\uD83D\uDCEC pubkeyContext.address:", this.pubkeyContext?.address);
2430
+ console.log(tag, "=======================================");
2892
2431
  if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgSend") {
2893
2432
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoTransfer(unsignedTx);
2894
2433
  signedTx = responseSign.serialized;
2895
- console.log(tag6, "✅ Signing completed");
2896
- console.log(tag6, "\uD83D\uDCE6 responseSign:", responseSign);
2434
+ console.log(tag, "✅ Signing completed");
2435
+ console.log(tag, "\uD83D\uDCE6 responseSign:", responseSign);
2897
2436
  } else if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgDeposit") {
2898
2437
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoDeposit(unsignedTx);
2899
2438
  signedTx = responseSign.serialized;
@@ -2915,11 +2454,11 @@ class TransactionManager {
2915
2454
  if (serialized.length > 140) {
2916
2455
  signedTx = serialized;
2917
2456
  } else {
2918
- console.error(tag6, "EIP155 signing returned incomplete transaction - only signature components");
2457
+ console.error(tag, "EIP155 signing returned incomplete transaction - only signature components");
2919
2458
  throw new Error("KeepKey returned incomplete transaction - cannot reconstruct without r,s,v components");
2920
2459
  }
2921
2460
  } else {
2922
- console.error(tag6, "EIP155 signing failed - no valid signature in response:", responseSign);
2461
+ console.error(tag, "EIP155 signing failed - no valid signature in response:", responseSign);
2923
2462
  throw new Error("Failed to sign transaction - no valid signature in response");
2924
2463
  }
2925
2464
  break;
@@ -2940,19 +2479,19 @@ class TransactionManager {
2940
2479
  }
2941
2480
  }
2942
2481
  if (!signedTx) {
2943
- console.error(tag6, "CRITICAL ERROR: signedTx is missing after signing process");
2944
- console.error(tag6, "CAIP:", caip);
2945
- console.error(tag6, "Type:", type);
2482
+ console.error(tag, "CRITICAL ERROR: signedTx is missing after signing process");
2483
+ console.error(tag, "CAIP:", caip);
2484
+ console.error(tag, "Type:", type);
2946
2485
  throw Error("Failed to sign! missing signedTx");
2947
2486
  }
2948
2487
  return signedTx;
2949
2488
  } catch (e) {
2950
- console.error(tag6, e);
2489
+ console.error(tag, e);
2951
2490
  throw e;
2952
2491
  }
2953
2492
  }
2954
2493
  async broadcast({ networkId, serialized }) {
2955
- let tag6 = TAG5 + " | broadcast | ";
2494
+ let tag = TAG5 + " | broadcast | ";
2956
2495
  try {
2957
2496
  if (!this.pioneer)
2958
2497
  throw Error("Failed to init! pioneer");
@@ -2966,7 +2505,7 @@ class TransactionManager {
2966
2505
  return result.txid;
2967
2506
  }
2968
2507
  } catch (e) {
2969
- console.error(tag6, e);
2508
+ console.error(tag, e);
2970
2509
  throw e;
2971
2510
  }
2972
2511
  }
@@ -3086,7 +2625,7 @@ var cosmosClaimAllRewardsTemplate = (params) => ({
3086
2625
  // src/txbuilder/createUnsignedStakingTx.ts
3087
2626
  var TAG6 = " | createUnsignedStakingTx | ";
3088
2627
  async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyContext) {
3089
- const tag6 = TAG6 + " | createUnsignedStakingTx | ";
2628
+ const tag = TAG6 + " | createUnsignedStakingTx | ";
3090
2629
  try {
3091
2630
  if (!pioneer)
3092
2631
  throw new Error("Failed to init! pioneer");
@@ -3097,7 +2636,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3097
2636
  if (!pubkeyContext.networks?.includes(networkId)) {
3098
2637
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
3099
2638
  }
3100
- console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2639
+ console.log(tag, `✅ Using pubkeyContext for network ${networkId}:`, {
3101
2640
  address: pubkeyContext.address
3102
2641
  });
3103
2642
  let chain;
@@ -3129,10 +2668,10 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3129
2668
  default:
3130
2669
  throw new Error(`Unsupported networkId for staking: ${networkId}`);
3131
2670
  }
3132
- console.log(tag6, `Building ${params.type} transaction for ${chain}`);
2671
+ console.log(tag, `Building ${params.type} transaction for ${chain}`);
3133
2672
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
3134
2673
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
3135
- console.log(tag6, "accountInfo: ", accountInfo);
2674
+ console.log(tag, "accountInfo: ", accountInfo);
3136
2675
  let account_number;
3137
2676
  let sequence;
3138
2677
  if (networkId === "cosmos:cosmoshub-4" || networkId === "cosmos:osmosis-1") {
@@ -3214,7 +2753,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3214
2753
  throw new Error(`Unsupported staking transaction type: ${params.type}`);
3215
2754
  }
3216
2755
  } catch (error) {
3217
- console.error(tag6, "Error:", error);
2756
+ console.error(tag, "Error:", error);
3218
2757
  throw error;
3219
2758
  }
3220
2759
  }
@@ -3260,16 +2799,16 @@ function withTimeout(promise, timeoutMs) {
3260
2799
  ]);
3261
2800
  }
3262
2801
  async function getFees(pioneer, networkId) {
3263
- const tag6 = TAG7 + " | getFees | ";
2802
+ const tag = TAG7 + " | getFees | ";
3264
2803
  try {
3265
- console.log(tag6, `Fetching fees for network: ${networkId}`);
2804
+ console.log(tag, `Fetching fees for network: ${networkId}`);
3266
2805
  const networkType = getNetworkType(networkId);
3267
2806
  if (networkType === "COSMOS") {
3268
- console.log(tag6, "Using hardcoded fees for Cosmos network:", networkId);
2807
+ console.log(tag, "Using hardcoded fees for Cosmos network:", networkId);
3269
2808
  return getCosmosFees(networkId);
3270
2809
  }
3271
2810
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
3272
- console.log(tag6, "Using hardcoded fees for Dogecoin: 10 sat/byte");
2811
+ console.log(tag, "Using hardcoded fees for Dogecoin: 10 sat/byte");
3273
2812
  return {
3274
2813
  slow: {
3275
2814
  label: "Slow",
@@ -3306,7 +2845,7 @@ async function getFees(pioneer, networkId) {
3306
2845
  const apiCall = pioneer.GetFeeRateByNetwork ? pioneer.GetFeeRateByNetwork({ networkId }) : pioneer.GetFeeRate({ networkId });
3307
2846
  feeResponse = await withTimeout(apiCall, 3000);
3308
2847
  } catch (timeoutError) {
3309
- console.warn(tag6, "Dash fee API timeout, using fallback fees");
2848
+ console.warn(tag, "Dash fee API timeout, using fallback fees");
3310
2849
  return {
3311
2850
  slow: {
3312
2851
  label: "Economy",
@@ -3339,10 +2878,10 @@ async function getFees(pioneer, networkId) {
3339
2878
  }
3340
2879
  } else {
3341
2880
  if (networkType === "EVM") {
3342
- console.log(tag6, "Using GetGasPriceByNetwork for EVM network:", networkId);
2881
+ console.log(tag, "Using GetGasPriceByNetwork for EVM network:", networkId);
3343
2882
  feeResponse = await (pioneer.GetGasPriceByNetwork ? pioneer.GetGasPriceByNetwork({ networkId }) : Promise.reject(new Error("GetGasPriceByNetwork not available")));
3344
2883
  } else {
3345
- console.log(tag6, "Using GetFeeRateByNetwork for UTXO network:", networkId);
2884
+ console.log(tag, "Using GetFeeRateByNetwork for UTXO network:", networkId);
3346
2885
  feeResponse = await (pioneer.GetFeeRateByNetwork ? pioneer.GetFeeRateByNetwork({ networkId }) : pioneer.GetFeeRate({ networkId }));
3347
2886
  }
3348
2887
  }
@@ -3350,17 +2889,17 @@ async function getFees(pioneer, networkId) {
3350
2889
  throw new Error(`No fee data returned for ${networkId}`);
3351
2890
  }
3352
2891
  const feeData = feeResponse.data;
3353
- console.log(tag6, "Raw fee data:", feeData);
2892
+ console.log(tag, "Raw fee data:", feeData);
3354
2893
  const networkName = getNetworkName(networkId);
3355
2894
  let normalizedFees = normalizeFeeData(feeData, networkType, networkName, networkId);
3356
2895
  normalizedFees = ensureFeeDifferentiation(normalizedFees, networkType);
3357
2896
  normalizedFees.networkId = networkId;
3358
2897
  normalizedFees.networkType = networkType;
3359
2898
  normalizedFees.raw = feeData;
3360
- console.log(tag6, "Normalized fees:", normalizedFees);
2899
+ console.log(tag, "Normalized fees:", normalizedFees);
3361
2900
  return normalizedFees;
3362
2901
  } catch (error) {
3363
- console.error(tag6, "Failed to fetch fees:", error);
2902
+ console.error(tag, "Failed to fetch fees:", error);
3364
2903
  return getFallbackFees(networkId);
3365
2904
  }
3366
2905
  }
@@ -3669,7 +3208,7 @@ function estimateTransactionFee(feeRate, unit, networkType, txSize) {
3669
3208
 
3670
3209
  // src/utils/kkapi-detection.ts
3671
3210
  async function detectKkApiAvailability(forceLocalhost) {
3672
- const tag6 = " | detectKkApiAvailability | ";
3211
+ const tag = " | detectKkApiAvailability | ";
3673
3212
  try {
3674
3213
  const isTauri = typeof window !== "undefined" && "__TAURI__" in window;
3675
3214
  const isBrowser = typeof window !== "undefined";
@@ -3828,11 +3367,11 @@ function buildDashboardFromBalances(balances, blockchains, assetsMap) {
3828
3367
  // src/utils/sync-market.ts
3829
3368
  var TAG8 = " | sync-market | ";
3830
3369
  async function syncMarket(balances, pioneer) {
3831
- const tag6 = `${TAG8} | syncMarket | `;
3370
+ const tag = `${TAG8} | syncMarket | `;
3832
3371
  try {
3833
3372
  const invalidBalances = balances.filter((b2) => !b2 || !b2.caip || typeof b2.caip !== "string" || !b2.caip.includes(":"));
3834
3373
  if (invalidBalances.length > 0) {
3835
- console.warn(tag6, `Found ${invalidBalances.length} balances with invalid CAIPs:`, invalidBalances.map((b2) => ({
3374
+ console.warn(tag, `Found ${invalidBalances.length} balances with invalid CAIPs:`, invalidBalances.map((b2) => ({
3836
3375
  caip: b2?.caip,
3837
3376
  type: typeof b2?.caip,
3838
3377
  symbol: b2?.symbol,
@@ -3847,7 +3386,7 @@ async function syncMarket(balances, pioneer) {
3847
3386
  console.log("GetMarketInfo: payload length: ", allCaips.length);
3848
3387
  const invalidEntries = allCaips.filter((caip) => typeof caip !== "string");
3849
3388
  if (invalidEntries.length > 0) {
3850
- console.error(tag6, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
3389
+ console.error(tag, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
3851
3390
  throw new Error("Invalid CAIP entries detected - aborting market sync");
3852
3391
  }
3853
3392
  if (allCaips && allCaips.length > 0) {
@@ -3868,13 +3407,13 @@ async function syncMarket(balances, pioneer) {
3868
3407
  }
3869
3408
  }
3870
3409
  } catch (apiError) {
3871
- console.error(tag6, "API error fetching market info:", apiError);
3872
- console.warn(tag6, "Continuing without market prices");
3410
+ console.error(tag, "API error fetching market info:", apiError);
3411
+ console.warn(tag, "Continuing without market prices");
3873
3412
  }
3874
3413
  }
3875
3414
  return true;
3876
3415
  } catch (e) {
3877
- console.error(tag6, "e:", e);
3416
+ console.error(tag, "e:", e);
3878
3417
  throw e;
3879
3418
  }
3880
3419
  }
@@ -3989,7 +3528,7 @@ class SDK {
3989
3528
  this.appIcon = config.appIcon || "https://pioneers.dev/coins/keepkey.png";
3990
3529
  this.spec = spec || config.spec || "https://api.keepkey.info/spec/swagger";
3991
3530
  this.wss = config.wss || "wss://pioneers.dev";
3992
- this.assets = assetData2;
3531
+ this.assets = assetData;
3993
3532
  this.assetsMap = new Map;
3994
3533
  this.username = config.username;
3995
3534
  this.queryKey = config.queryKey;
@@ -4067,7 +3606,7 @@ class SDK {
4067
3606
  return true;
4068
3607
  };
4069
3608
  this.setPubkeys = (newPubkeys) => {
4070
- const tag6 = `${TAG9} | setPubkeys | `;
3609
+ const tag = `${TAG9} | setPubkeys | `;
4071
3610
  this.pubkeys = [];
4072
3611
  this.pubkeySet.clear();
4073
3612
  let added = 0;
@@ -4084,7 +3623,7 @@ class SDK {
4084
3623
  this.pubkeySet.clear();
4085
3624
  }
4086
3625
  this.getUnifiedPortfolio = async function() {
4087
- const tag6 = `${TAG9} | getUnifiedPortfolio | `;
3626
+ const tag = `${TAG9} | getUnifiedPortfolio | `;
4088
3627
  try {
4089
3628
  const startTime = performance.now();
4090
3629
  try {
@@ -4095,17 +3634,17 @@ class SDK {
4095
3634
  signal: AbortSignal.timeout(2000)
4096
3635
  });
4097
3636
  if (!portfolioResponse.ok) {
4098
- console.warn(tag6, "Portfolio endpoint returned", portfolioResponse.status);
3637
+ console.warn(tag, "Portfolio endpoint returned", portfolioResponse.status);
4099
3638
  return null;
4100
3639
  }
4101
3640
  const portfolioData = await portfolioResponse.json();
4102
3641
  const loadTime = performance.now() - startTime;
4103
3642
  if (!portfolioData.success) {
4104
- console.warn(tag6, "Portfolio API returned success=false");
3643
+ console.warn(tag, "Portfolio API returned success=false");
4105
3644
  return null;
4106
3645
  }
4107
3646
  if (portfolioData.totalValueUsd === 0 || !portfolioData.totalValueUsd) {
4108
- console.warn(tag6, "Portfolio value is $0.00 - may need device connection or sync");
3647
+ console.warn(tag, "Portfolio value is $0.00 - may need device connection or sync");
4109
3648
  return null;
4110
3649
  }
4111
3650
  let allBalances = [];
@@ -4192,14 +3731,14 @@ class SDK {
4192
3731
  };
4193
3732
  } catch (fetchError) {
4194
3733
  if (fetchError.name === "AbortError") {
4195
- console.log(tag6, "Unified portfolio request timed out (this is normal if vault not running)");
3734
+ console.log(tag, "Unified portfolio request timed out (this is normal if vault not running)");
4196
3735
  } else {
4197
- console.log(tag6, "Failed to fetch unified portfolio:", fetchError.message);
3736
+ console.log(tag, "Failed to fetch unified portfolio:", fetchError.message);
4198
3737
  }
4199
3738
  return null;
4200
3739
  }
4201
3740
  } catch (e) {
4202
- console.error(tag6, "Error:", e);
3741
+ console.error(tag, "Error:", e);
4203
3742
  return null;
4204
3743
  }
4205
3744
  };
@@ -4210,7 +3749,7 @@ class SDK {
4210
3749
  return this.syncState.isSynced;
4211
3750
  };
4212
3751
  this.init = async function(walletsVerbose, setup) {
4213
- const tag6 = `${TAG9} | init | `;
3752
+ const tag = `${TAG9} | init | `;
4214
3753
  try {
4215
3754
  if (!this.username)
4216
3755
  throw Error("username required!");
@@ -4266,11 +3805,11 @@ class SDK {
4266
3805
  this.events.emit("message", request);
4267
3806
  });
4268
3807
  clientEvents.events.on("balance:update", (data) => {
4269
- const tag7 = TAG9 + " | balance:update | ";
3808
+ const tag2 = TAG9 + " | balance:update | ";
4270
3809
  try {
4271
3810
  const payload = typeof data === "string" ? JSON.parse(data) : data;
4272
3811
  const balance = payload.balance;
4273
- console.log(tag7, "Received balance update:", balance.caip);
3812
+ console.log(tag2, "Received balance update:", balance.caip);
4274
3813
  const exists = this.balances.find((b2) => b2.caip === balance.caip && b2.pubkey === balance.pubkey);
4275
3814
  if (!exists) {
4276
3815
  this.balances.push(balance);
@@ -4280,27 +3819,27 @@ class SDK {
4280
3819
  }
4281
3820
  this.events.emit("BALANCE_UPDATE", balance);
4282
3821
  } catch (e) {
4283
- console.error(tag7, "Error processing balance update:", e);
3822
+ console.error(tag2, "Error processing balance update:", e);
4284
3823
  }
4285
3824
  });
4286
3825
  clientEvents.events.on("sync:progress", (data) => {
4287
- const tag7 = TAG9 + " | sync:progress | ";
3826
+ const tag2 = TAG9 + " | sync:progress | ";
4288
3827
  try {
4289
3828
  const payload = typeof data === "string" ? JSON.parse(data) : data;
4290
- console.log(tag7, `Sync progress: ${payload.percentage}%`);
3829
+ console.log(tag2, `Sync progress: ${payload.percentage}%`);
4291
3830
  this.syncState.syncProgress = payload.percentage;
4292
3831
  this.syncState.syncedChains = payload.completed;
4293
3832
  this.syncState.totalChains = payload.total;
4294
3833
  this.events.emit("SYNC_PROGRESS", this.syncState);
4295
3834
  } catch (e) {
4296
- console.error(tag7, "Error processing sync progress:", e);
3835
+ console.error(tag2, "Error processing sync progress:", e);
4297
3836
  }
4298
3837
  });
4299
3838
  clientEvents.events.on("sync:complete", (data) => {
4300
- const tag7 = TAG9 + " | sync:complete | ";
3839
+ const tag2 = TAG9 + " | sync:complete | ";
4301
3840
  try {
4302
3841
  const payload = typeof data === "string" ? JSON.parse(data) : data;
4303
- console.log(tag7, `Sync complete: ${payload.balances} balances in ${payload.duration}ms`);
3842
+ console.log(tag2, `Sync complete: ${payload.balances} balances in ${payload.duration}ms`);
4304
3843
  this.syncState.isSynced = true;
4305
3844
  this.syncState.isInitialSync = false;
4306
3845
  this.syncState.syncProgress = 100;
@@ -4309,7 +3848,7 @@ class SDK {
4309
3848
  this.events.emit("SYNC_COMPLETE", this.syncState);
4310
3849
  this.events.emit("SYNC_STATE_CHANGED", this.syncState);
4311
3850
  } catch (e) {
4312
- console.error(tag7, "Error processing sync complete:", e);
3851
+ console.error(tag2, "Error processing sync complete:", e);
4313
3852
  }
4314
3853
  });
4315
3854
  this.events.emit("SET_STATUS", "init");
@@ -4341,7 +3880,7 @@ class SDK {
4341
3880
  }
4342
3881
  return this.pioneer;
4343
3882
  } catch (e) {
4344
- console.error(tag6, "e: ", e);
3883
+ console.error(tag, "e: ", e);
4345
3884
  throw e;
4346
3885
  }
4347
3886
  };
@@ -4352,7 +3891,7 @@ class SDK {
4352
3891
  return syncMarket(this.balances, this.pioneer);
4353
3892
  };
4354
3893
  this.sync = async function() {
4355
- const tag6 = `${TAG9} | sync | `;
3894
+ const tag = `${TAG9} | sync | `;
4356
3895
  try {
4357
3896
  const matchesNetwork = (item, networkId) => {
4358
3897
  if (!item.networks || !Array.isArray(item.networks))
@@ -4484,7 +4023,7 @@ class SDK {
4484
4023
  this.events.emit("SYNC_COMPLETE", this.syncState);
4485
4024
  return true;
4486
4025
  } catch (e) {
4487
- console.error(tag6, "Error in sync:", e);
4026
+ console.error(tag, "Error in sync:", e);
4488
4027
  throw e;
4489
4028
  }
4490
4029
  };
@@ -4498,7 +4037,7 @@ class SDK {
4498
4037
  }
4499
4038
  };
4500
4039
  this.buildTx = async function(sendPayload) {
4501
- let tag6 = TAG9 + " | buildTx | ";
4040
+ let tag = TAG9 + " | buildTx | ";
4502
4041
  try {
4503
4042
  const transactionDependencies = {
4504
4043
  context: this.context,
@@ -4512,7 +4051,7 @@ class SDK {
4512
4051
  };
4513
4052
  let txManager = new TransactionManager(transactionDependencies, this.events);
4514
4053
  let unsignedTx = await txManager.transfer(sendPayload);
4515
- console.log(tag6, "unsignedTx: ", unsignedTx);
4054
+ console.log(tag, "unsignedTx: ", unsignedTx);
4516
4055
  return unsignedTx;
4517
4056
  } catch (e) {
4518
4057
  console.error(e);
@@ -4520,14 +4059,14 @@ class SDK {
4520
4059
  }
4521
4060
  };
4522
4061
  this.buildDelegateTx = async function(caip, params) {
4523
- let tag6 = TAG9 + " | buildDelegateTx | ";
4062
+ let tag = TAG9 + " | buildDelegateTx | ";
4524
4063
  try {
4525
4064
  const delegateParams = {
4526
4065
  ...params,
4527
4066
  type: "delegate"
4528
4067
  };
4529
4068
  let unsignedTx = await createUnsignedStakingTx(caip, delegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4530
- console.log(tag6, "unsignedTx: ", unsignedTx);
4069
+ console.log(tag, "unsignedTx: ", unsignedTx);
4531
4070
  return unsignedTx;
4532
4071
  } catch (e) {
4533
4072
  console.error(e);
@@ -4535,14 +4074,14 @@ class SDK {
4535
4074
  }
4536
4075
  };
4537
4076
  this.buildUndelegateTx = async function(caip, params) {
4538
- let tag6 = TAG9 + " | buildUndelegateTx | ";
4077
+ let tag = TAG9 + " | buildUndelegateTx | ";
4539
4078
  try {
4540
4079
  const undelegateParams = {
4541
4080
  ...params,
4542
4081
  type: "undelegate"
4543
4082
  };
4544
4083
  let unsignedTx = await createUnsignedStakingTx(caip, undelegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4545
- console.log(tag6, "unsignedTx: ", unsignedTx);
4084
+ console.log(tag, "unsignedTx: ", unsignedTx);
4546
4085
  return unsignedTx;
4547
4086
  } catch (e) {
4548
4087
  console.error(e);
@@ -4550,14 +4089,14 @@ class SDK {
4550
4089
  }
4551
4090
  };
4552
4091
  this.buildClaimRewardsTx = async function(caip, params) {
4553
- let tag6 = TAG9 + " | buildClaimRewardsTx | ";
4092
+ let tag = TAG9 + " | buildClaimRewardsTx | ";
4554
4093
  try {
4555
4094
  const claimParams = {
4556
4095
  ...params,
4557
4096
  type: "claim_rewards"
4558
4097
  };
4559
4098
  let unsignedTx = await createUnsignedStakingTx(caip, claimParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4560
- console.log(tag6, "unsignedTx: ", unsignedTx);
4099
+ console.log(tag, "unsignedTx: ", unsignedTx);
4561
4100
  return unsignedTx;
4562
4101
  } catch (e) {
4563
4102
  console.error(e);
@@ -4565,7 +4104,7 @@ class SDK {
4565
4104
  }
4566
4105
  };
4567
4106
  this.buildClaimAllRewardsTx = async function(caip, params) {
4568
- let tag6 = TAG9 + " | buildClaimAllRewardsTx | ";
4107
+ let tag = TAG9 + " | buildClaimAllRewardsTx | ";
4569
4108
  try {
4570
4109
  const claimAllParams = {
4571
4110
  ...params,
@@ -4579,7 +4118,7 @@ class SDK {
4579
4118
  }
4580
4119
  };
4581
4120
  this.signTx = async function(caip, unsignedTx) {
4582
- let tag6 = TAG9 + " | signTx | ";
4121
+ let tag = TAG9 + " | signTx | ";
4583
4122
  try {
4584
4123
  const transactionDependencies = {
4585
4124
  context: this.context,
@@ -4600,7 +4139,7 @@ class SDK {
4600
4139
  }
4601
4140
  };
4602
4141
  this.broadcastTx = async function(caip, signedTx) {
4603
- let tag6 = TAG9 + " | broadcastTx | ";
4142
+ let tag = TAG9 + " | broadcastTx | ";
4604
4143
  try {
4605
4144
  const transactionDependencies = {
4606
4145
  context: this.context,
@@ -4624,7 +4163,7 @@ class SDK {
4624
4163
  }
4625
4164
  };
4626
4165
  this.swap = async function(swapPayload) {
4627
- let tag6 = `${TAG9} | swap | `;
4166
+ let tag = `${TAG9} | swap | `;
4628
4167
  try {
4629
4168
  if (!swapPayload)
4630
4169
  throw Error("swapPayload required!");
@@ -4673,15 +4212,15 @@ class SDK {
4673
4212
  throw new Error(`Cannot use max amount: no balance found for ${swapPayload.caipIn}`);
4674
4213
  }
4675
4214
  let totalBalance = 0;
4676
- console.log(tag6, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4215
+ console.log(tag, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4677
4216
  for (const balanceEntry of inputBalances) {
4678
4217
  const balance = parseFloat(balanceEntry.balance) || 0;
4679
4218
  totalBalance += balance;
4680
- console.log(tag6, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4219
+ console.log(tag, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4681
4220
  }
4682
4221
  this.assetContext.balance = totalBalance.toString();
4683
4222
  this.assetContext.valueUsd = (totalBalance * parseFloat(this.assetContext.priceUsd || "0")).toFixed(2);
4684
- console.log(tag6, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4223
+ console.log(tag, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4685
4224
  const feeReserves = {
4686
4225
  "bip122:000000000019d6689c085ae165831e93/slip44:0": 0.00005,
4687
4226
  "eip155:1/slip44:60": 0.001,
@@ -4692,7 +4231,7 @@ class SDK {
4692
4231
  };
4693
4232
  const reserve = feeReserves[swapPayload.caipIn] || 0.0001;
4694
4233
  inputAmount = Math.max(0, totalBalance - reserve);
4695
- console.log(tag6, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4234
+ console.log(tag, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4696
4235
  } else {
4697
4236
  inputAmount = typeof swapPayload.amount === "string" ? parseFloat(swapPayload.amount) : swapPayload.amount;
4698
4237
  if (isNaN(inputAmount) || inputAmount <= 0) {
@@ -4712,7 +4251,7 @@ class SDK {
4712
4251
  result = await this.pioneer.Quote(quote);
4713
4252
  result = result.data;
4714
4253
  } catch (e) {
4715
- console.error(tag6, "Failed to get quote: ", e);
4254
+ console.error(tag, "Failed to get quote: ", e);
4716
4255
  throw Error("Quote API failed for path: " + quote.sellAsset + " -> " + quote.buyAsset + ". Error: " + e);
4717
4256
  }
4718
4257
  if (!result || result.length === 0)
@@ -4739,7 +4278,7 @@ class SDK {
4739
4278
  if (tx.type === "deposit") {
4740
4279
  unsignedTx = await createUnsignedTendermintTx(caip, tx.type, tx.txParams.amount, tx.txParams.memo, this.pubkeys, this.pioneer, this.pubkeyContext, false, undefined);
4741
4280
  } else if (tx.type === "EVM" || tx.type === "evm") {
4742
- console.log(tag6, "Using pre-built EVM transaction from integration");
4281
+ console.log(tag, "Using pre-built EVM transaction from integration");
4743
4282
  unsignedTx = tx.txParams;
4744
4283
  } else {
4745
4284
  if (!tx.txParams.memo)
@@ -4758,12 +4297,12 @@ class SDK {
4758
4297
  return unsignedTx;
4759
4298
  }
4760
4299
  } catch (e) {
4761
- console.error(tag6, "Error: ", e);
4300
+ console.error(tag, "Error: ", e);
4762
4301
  throw e;
4763
4302
  }
4764
4303
  };
4765
4304
  this.transfer = async function(sendPayload) {
4766
- let tag6 = `${TAG9} | transfer | `;
4305
+ let tag = `${TAG9} | transfer | `;
4767
4306
  try {
4768
4307
  if (!sendPayload)
4769
4308
  throw Error("sendPayload required!");
@@ -4797,15 +4336,15 @@ class SDK {
4797
4336
  return { txid, events: this.events };
4798
4337
  } catch (error) {
4799
4338
  if (error instanceof Error) {
4800
- console.error(tag6, "An error occurred during the transfer process:", error.message);
4339
+ console.error(tag, "An error occurred during the transfer process:", error.message);
4801
4340
  } else {
4802
- console.error(tag6, "An unknown error occurred during the transfer process");
4341
+ console.error(tag, "An unknown error occurred during the transfer process");
4803
4342
  }
4804
4343
  throw error;
4805
4344
  }
4806
4345
  };
4807
4346
  this.followTransaction = async function(caip, txid) {
4808
- let tag6 = " | followTransaction | ";
4347
+ let tag = " | followTransaction | ";
4809
4348
  try {
4810
4349
  const finalConfirmationBlocksByCaip = {
4811
4350
  dogecoin: 3,
@@ -4835,7 +4374,7 @@ class SDK {
4835
4374
  }
4836
4375
  }
4837
4376
  } catch (error) {
4838
- console.error(tag6, "Error:", error);
4377
+ console.error(tag, "Error:", error);
4839
4378
  }
4840
4379
  if (!isConfirmed) {
4841
4380
  await new Promise((resolve) => setTimeout(resolve, 8000));
@@ -4853,18 +4392,18 @@ class SDK {
4853
4392
  requiredConfirmations
4854
4393
  };
4855
4394
  } catch (error) {
4856
- console.error(tag6, "Error:", error);
4395
+ console.error(tag, "Error:", error);
4857
4396
  throw new Error("Failed to follow transaction");
4858
4397
  }
4859
4398
  };
4860
4399
  this.setBlockchains = async function(blockchains) {
4861
- const tag6 = `${TAG9} | setBlockchains | `;
4400
+ const tag = `${TAG9} | setBlockchains | `;
4862
4401
  try {
4863
4402
  if (!blockchains)
4864
4403
  throw Error("blockchains required!");
4865
4404
  const uniqueBlockchains = [...new Set(blockchains)];
4866
4405
  if (blockchains.length !== uniqueBlockchains.length) {
4867
- console.warn(tag6, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
4406
+ console.warn(tag, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
4868
4407
  }
4869
4408
  this.blockchains = uniqueBlockchains;
4870
4409
  this.events.emit("SET_BLOCKCHAINS", this.blockchains);
@@ -4874,12 +4413,12 @@ class SDK {
4874
4413
  }
4875
4414
  };
4876
4415
  this.addAsset = async function(caip, data) {
4877
- let tag6 = TAG9 + " | addAsset | ";
4416
+ let tag = TAG9 + " | addAsset | ";
4878
4417
  try {
4879
4418
  let success = false;
4880
4419
  if (!caip)
4881
4420
  throw new Error("caip required!");
4882
- let dataLocal = assetData2[caip];
4421
+ let dataLocal = assetData[caip];
4883
4422
  if (!dataLocal) {
4884
4423
  if (!data.networkId)
4885
4424
  throw new Error("networkId required! can not build asset");
@@ -4912,22 +4451,22 @@ class SDK {
4912
4451
  }
4913
4452
  };
4914
4453
  this.clearWalletState = async function() {
4915
- const tag6 = `${TAG9} | clearWalletState | `;
4454
+ const tag = `${TAG9} | clearWalletState | `;
4916
4455
  try {
4917
4456
  this.context = null;
4918
4457
  this.paths = [];
4919
4458
  this.blockchains = [];
4920
4459
  this.pubkeys = [];
4921
4460
  this.pubkeySet.clear();
4922
- console.log(tag6, "Cleared wallet state including pubkeys and tracking set");
4461
+ console.log(tag, "Cleared wallet state including pubkeys and tracking set");
4923
4462
  return true;
4924
4463
  } catch (e) {
4925
- console.error(tag6, "e: ", e);
4464
+ console.error(tag, "e: ", e);
4926
4465
  throw e;
4927
4466
  }
4928
4467
  };
4929
4468
  this.addPath = async function(path) {
4930
- const tag6 = `${TAG9} | addPath | `;
4469
+ const tag = `${TAG9} | addPath | `;
4931
4470
  try {
4932
4471
  this.paths.push(path);
4933
4472
  const pubkey = await getPubkey(path.networks[0], path, this.keepKeySdk, this.context);
@@ -4936,14 +4475,14 @@ class SDK {
4936
4475
  this.buildDashboardFromBalances();
4937
4476
  return { success: true, pubkey };
4938
4477
  } catch (e) {
4939
- console.error(tag6, "Failed:", e);
4478
+ console.error(tag, "Failed:", e);
4940
4479
  throw e;
4941
4480
  }
4942
4481
  };
4943
4482
  this.addPaths = async function(paths) {
4944
- const tag6 = `${TAG9} | addPaths | `;
4483
+ const tag = `${TAG9} | addPaths | `;
4945
4484
  try {
4946
- console.log(tag6, `Adding ${paths.length} paths in batch mode...`);
4485
+ console.log(tag, `Adding ${paths.length} paths in batch mode...`);
4947
4486
  this.paths.push(...paths);
4948
4487
  const newPubkeys = [];
4949
4488
  for (const path of paths) {
@@ -4952,10 +4491,10 @@ class SDK {
4952
4491
  this.addPubkey(pubkey);
4953
4492
  newPubkeys.push(pubkey);
4954
4493
  } catch (error) {
4955
- console.warn(tag6, `Failed to get pubkey for path ${path.note}:`, error.message);
4494
+ console.warn(tag, `Failed to get pubkey for path ${path.note}:`, error.message);
4956
4495
  }
4957
4496
  }
4958
- console.log(tag6, `Successfully added ${newPubkeys.length} pubkeys`);
4497
+ console.log(tag, `Successfully added ${newPubkeys.length} pubkeys`);
4959
4498
  const networkSet = new Set;
4960
4499
  for (const path of paths) {
4961
4500
  if (path.networks && Array.isArray(path.networks)) {
@@ -4963,13 +4502,13 @@ class SDK {
4963
4502
  }
4964
4503
  }
4965
4504
  const uniqueNetworks = [...networkSet];
4966
- console.log(tag6, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
4505
+ console.log(tag, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
4967
4506
  await this.getBalancesForNetworks(uniqueNetworks);
4968
4507
  this.buildDashboardFromBalances();
4969
- console.log(tag6, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
4508
+ console.log(tag, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
4970
4509
  return { success: true, pubkeys: newPubkeys };
4971
4510
  } catch (e) {
4972
- console.error(tag6, "Failed:", e);
4511
+ console.error(tag, "Failed:", e);
4973
4512
  throw e;
4974
4513
  }
4975
4514
  };
@@ -4977,12 +4516,12 @@ class SDK {
4977
4516
  return this.getGasAssets();
4978
4517
  };
4979
4518
  this.getGasAssets = async function() {
4980
- const tag6 = `${TAG9} | getGasAssets | `;
4519
+ const tag = `${TAG9} | getGasAssets | `;
4981
4520
  try {
4982
4521
  for (let i = 0;i < this.blockchains.length; i++) {
4983
4522
  let networkId = this.blockchains[i];
4984
4523
  let caip = networkIdToCaip2(networkId);
4985
- let asset = await assetData2[caip.toLowerCase()];
4524
+ let asset = await assetData[caip.toLowerCase()];
4986
4525
  if (asset) {
4987
4526
  asset.caip = caip.toLowerCase();
4988
4527
  asset.networkId = networkId;
@@ -5011,7 +4550,7 @@ class SDK {
5011
4550
  denom: "maya"
5012
4551
  };
5013
4552
  this.assetsMap.set(mayaTokenCaip, mayaToken);
5014
- console.log(tag6, "Added MAYA token to assetsMap");
4553
+ console.log(tag, "Added MAYA token to assetsMap");
5015
4554
  }
5016
4555
  return this.assetsMap;
5017
4556
  } catch (e) {
@@ -5020,7 +4559,7 @@ class SDK {
5020
4559
  }
5021
4560
  };
5022
4561
  this.getPubkeys = async function() {
5023
- const tag6 = `${TAG9} | getPubkeys | `;
4562
+ const tag = `${TAG9} | getPubkeys | `;
5024
4563
  try {
5025
4564
  if (this.paths.length === 0)
5026
4565
  throw new Error("No paths found!");
@@ -5034,41 +4573,41 @@ class SDK {
5034
4573
  }
5035
4574
  const pubkeysWithoutNetworks = this.pubkeys.filter((pk) => !pk.networks || !Array.isArray(pk.networks) || pk.networks.length === 0);
5036
4575
  if (pubkeysWithoutNetworks.length > 0) {
5037
- console.error(tag6, "ERROR: Some pubkeys missing networks field!");
5038
- console.error(tag6, "Affected pubkeys:", pubkeysWithoutNetworks.length);
4576
+ console.error(tag, "ERROR: Some pubkeys missing networks field!");
4577
+ console.error(tag, "Affected pubkeys:", pubkeysWithoutNetworks.length);
5039
4578
  pubkeysWithoutNetworks.forEach((pk) => {
5040
- console.error(tag6, ` - ${pk.note || pk.pubkey}: networks=${pk.networks}`);
4579
+ console.error(tag, ` - ${pk.note || pk.pubkey}: networks=${pk.networks}`);
5041
4580
  });
5042
4581
  for (const pubkey of pubkeysWithoutNetworks) {
5043
4582
  const matchingPath = this.paths.find((p) => JSON.stringify(p.addressNList) === JSON.stringify(pubkey.addressNList));
5044
4583
  if (matchingPath && matchingPath.networks) {
5045
- console.warn(tag6, ` ⚠️ Auto-fixing: Adding networks from path ${matchingPath.note}`);
4584
+ console.warn(tag, ` ⚠️ Auto-fixing: Adding networks from path ${matchingPath.note}`);
5046
4585
  pubkey.networks = matchingPath.networks;
5047
4586
  }
5048
4587
  }
5049
4588
  const stillMissing = this.pubkeys.filter((pk) => !pk.networks || !Array.isArray(pk.networks) || pk.networks.length === 0);
5050
4589
  if (stillMissing.length > 0) {
5051
- console.error(tag6, `❌ CRITICAL: ${stillMissing.length} pubkeys still missing networks after auto-fix!`);
4590
+ console.error(tag, `❌ CRITICAL: ${stillMissing.length} pubkeys still missing networks after auto-fix!`);
5052
4591
  stillMissing.forEach((pk) => {
5053
- console.error(tag6, ` - ${pk.note || pk.pubkey}`);
4592
+ console.error(tag, ` - ${pk.note || pk.pubkey}`);
5054
4593
  });
5055
4594
  } else {
5056
- console.log(tag6, `✅ Auto-fix successful: All pubkeys now have networks field`);
4595
+ console.log(tag, `✅ Auto-fix successful: All pubkeys now have networks field`);
5057
4596
  }
5058
4597
  }
5059
4598
  this.events.emit("SET_PUBKEYS", this.pubkeys);
5060
4599
  return pubkeys;
5061
4600
  } catch (error) {
5062
4601
  console.error("Error in getPubkeys:", error);
5063
- console.error(tag6, "Error in getPubkeys:", error);
4602
+ console.error(tag, "Error in getPubkeys:", error);
5064
4603
  throw error;
5065
4604
  }
5066
4605
  };
5067
4606
  this.getBalancesForNetworks = async function(networkIds) {
5068
- const tag6 = `${TAG9} | getBalancesForNetworks | `;
4607
+ const tag = `${TAG9} | getBalancesForNetworks | `;
5069
4608
  try {
5070
4609
  if (!this.pioneer) {
5071
- console.error(tag6, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
4610
+ console.error(tag, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
5072
4611
  throw new Error("Pioneer client not initialized. Call init() first.");
5073
4612
  }
5074
4613
  console.log("\uD83D\uDD0D [DIAGNOSTIC] Input networks:", networkIds);
@@ -5096,20 +4635,20 @@ class SDK {
5096
4635
  return network === adjustedNetworkId;
5097
4636
  }));
5098
4637
  if (pubkeys.length === 0) {
5099
- console.warn(tag6, `⚠️ No pubkeys found for ${networkId} with networks field`);
5100
- console.warn(tag6, "Attempting fallback: finding pubkeys by path matching");
4638
+ console.warn(tag, `⚠️ No pubkeys found for ${networkId} with networks field`);
4639
+ console.warn(tag, "Attempting fallback: finding pubkeys by path matching");
5101
4640
  const pathsForNetwork = this.paths.filter((p) => p.networks?.includes(networkId) || networkId.startsWith("eip155:") && p.networks?.includes("eip155:*"));
5102
4641
  for (const path of pathsForNetwork) {
5103
4642
  const matchingPubkey = this.pubkeys.find((pk) => JSON.stringify(pk.addressNList) === JSON.stringify(path.addressNList));
5104
4643
  if (matchingPubkey) {
5105
- console.warn(tag6, ` ✓ Found pubkey via path matching: ${matchingPubkey.note || matchingPubkey.pubkey.slice(0, 10)}`);
4644
+ console.warn(tag, ` ✓ Found pubkey via path matching: ${matchingPubkey.note || matchingPubkey.pubkey.slice(0, 10)}`);
5106
4645
  pubkeys.push(matchingPubkey);
5107
4646
  }
5108
4647
  }
5109
4648
  if (pubkeys.length > 0) {
5110
- console.warn(tag6, ` ✅ Fallback successful: Found ${pubkeys.length} pubkeys for ${networkId}`);
4649
+ console.warn(tag, ` ✅ Fallback successful: Found ${pubkeys.length} pubkeys for ${networkId}`);
5111
4650
  } else {
5112
- console.error(tag6, ` ❌ Fallback failed: No pubkeys found for ${networkId}`);
4651
+ console.error(tag, ` ❌ Fallback failed: No pubkeys found for ${networkId}`);
5113
4652
  }
5114
4653
  }
5115
4654
  const caipNative = await networkIdToCaip2(networkId);
@@ -5127,11 +4666,18 @@ class SDK {
5127
4666
  caipCounts.forEach((count, caip) => {
5128
4667
  console.log(` - ${caip}: ${count} queries`);
5129
4668
  });
4669
+ console.log(`⏱️ [PERF] Starting GetPortfolioBalances API call...`);
4670
+ const apiCallStart = performance.now();
5130
4671
  console.time("GetPortfolioBalances Response Time");
5131
4672
  try {
5132
- let marketInfo = await this.pioneer.GetPortfolioBalances(assetQuery);
4673
+ let marketInfo = await this.pioneer.GetPortfolioBalances({ pubkeys: assetQuery });
4674
+ const apiCallTime = performance.now() - apiCallStart;
5133
4675
  console.timeEnd("GetPortfolioBalances Response Time");
4676
+ console.log(`⏱️ [PERF] API call completed in ${apiCallTime.toFixed(0)}ms`);
4677
+ const enrichStart = performance.now();
5134
4678
  let balances = marketInfo.data;
4679
+ console.log(`⏱️ [PERF] Received ${balances?.length || 0} balances from server`);
4680
+ console.log(`⏱️ [PERF] Starting balance enrichment...`);
5135
4681
  for (let balance of balances) {
5136
4682
  const assetInfo = this.assetsMap.get(balance.caip.toLowerCase()) || this.assetsMap.get(balance.caip);
5137
4683
  if (!assetInfo)
@@ -5145,47 +4691,50 @@ class SDK {
5145
4691
  color
5146
4692
  });
5147
4693
  }
4694
+ const enrichTime = performance.now() - enrichStart;
4695
+ console.log(`⏱️ [PERF] Enrichment completed in ${enrichTime.toFixed(0)}ms`);
5148
4696
  this.balances = balances;
5149
4697
  this.events.emit("SET_BALANCES", this.balances);
4698
+ console.log(`⏱️ [PERF] Total getBalancesForNetworks: ${(performance.now() - apiCallStart).toFixed(0)}ms`);
5150
4699
  return this.balances;
5151
4700
  } catch (apiError) {
5152
- console.error(tag6, "GetPortfolioBalances API call failed:", apiError);
4701
+ console.error(tag, "GetPortfolioBalances API call failed:", apiError);
5153
4702
  throw new Error(`GetPortfolioBalances API call failed: ${apiError?.message || "Unknown error"}`);
5154
4703
  }
5155
4704
  } catch (e) {
5156
- console.error(tag6, "Error: ", e);
4705
+ console.error(tag, "Error: ", e);
5157
4706
  throw e;
5158
4707
  }
5159
4708
  };
5160
4709
  this.getBalances = async function() {
5161
- const tag6 = `${TAG9} | getBalances | `;
4710
+ const tag = `${TAG9} | getBalances | `;
5162
4711
  try {
5163
4712
  return await this.getBalancesForNetworks(this.blockchains);
5164
4713
  } catch (e) {
5165
- console.error(tag6, "Error in getBalances: ", e);
4714
+ console.error(tag, "Error in getBalances: ", e);
5166
4715
  throw e;
5167
4716
  }
5168
4717
  };
5169
4718
  this.getBalance = async function(networkId) {
5170
- const tag6 = `${TAG9} | getBalance | `;
4719
+ const tag = `${TAG9} | getBalance | `;
5171
4720
  try {
5172
4721
  const results = await this.getBalancesForNetworks([networkId]);
5173
4722
  const filtered = results.filter(async (b2) => b2.networkId === await networkIdToCaip2(networkId));
5174
4723
  return filtered;
5175
4724
  } catch (e) {
5176
- console.error(tag6, "Error: ", e);
4725
+ console.error(tag, "Error: ", e);
5177
4726
  throw e;
5178
4727
  }
5179
4728
  };
5180
4729
  this.getFees = async function(networkId) {
5181
- const tag6 = `${TAG9} | getFees | `;
4730
+ const tag = `${TAG9} | getFees | `;
5182
4731
  try {
5183
4732
  if (!this.pioneer) {
5184
4733
  throw new Error("Pioneer client not initialized. Call init() first.");
5185
4734
  }
5186
4735
  return await getFees(this.pioneer, networkId);
5187
4736
  } catch (e) {
5188
- console.error(tag6, "Error getting fees: ", e);
4737
+ console.error(tag, "Error getting fees: ", e);
5189
4738
  throw e;
5190
4739
  }
5191
4740
  };
@@ -5193,29 +4742,55 @@ class SDK {
5193
4742
  return estimateTransactionFee(feeRate, unit, networkType, txSize);
5194
4743
  };
5195
4744
  this.getCharts = async function() {
5196
- const tag6 = `${TAG9} | getCharts | `;
4745
+ const tag = `${TAG9} | getCharts | `;
5197
4746
  try {
5198
- console.log(tag6, "Fetching charts");
5199
- const newBalances = await getCharts(this.blockchains, this.pioneer, this.pubkeys, this.context);
5200
- console.log(tag6, "newBalances: ", newBalances);
4747
+ console.log(tag, "Fetching charts from batch endpoint");
4748
+ const pubkeysForBatch = [];
4749
+ for (const pubkey of this.pubkeys) {
4750
+ const address = pubkey.address || pubkey.master || pubkey.pubkey;
4751
+ if (!address)
4752
+ continue;
4753
+ const supportedNetworks = pubkey.networks || [];
4754
+ for (const blockchain of this.blockchains) {
4755
+ const supportsNetwork = supportedNetworks.some((net) => net === blockchain || net.endsWith(":*") && blockchain.startsWith(net.replace(":*", ":")));
4756
+ if (supportsNetwork) {
4757
+ let caip;
4758
+ if (blockchain.startsWith("eip155:")) {
4759
+ caip = `${blockchain}/slip44:60`;
4760
+ } else {
4761
+ caip = `${blockchain}/slip44:0`;
4762
+ }
4763
+ pubkeysForBatch.push({
4764
+ pubkey: address,
4765
+ caip
4766
+ });
4767
+ }
4768
+ }
4769
+ }
4770
+ console.log(tag, `Calling batch GetCharts with ${pubkeysForBatch.length} pubkeys`);
4771
+ const chartsResponse = await this.pioneer.GetCharts({
4772
+ pubkeys: pubkeysForBatch
4773
+ });
4774
+ const newBalances = chartsResponse?.data?.balances || [];
4775
+ console.log(tag, `Received ${newBalances.length} balances from batch endpoint`);
5201
4776
  const uniqueBalances = new Map([...this.balances, ...newBalances].map((balance) => [
5202
- balance.identifier,
4777
+ balance.identifier || `${balance.caip}:${balance.pubkey}`,
5203
4778
  {
5204
4779
  ...balance,
5205
4780
  type: balance.type || "balance"
5206
4781
  }
5207
4782
  ]));
5208
- console.log(tag6, "uniqueBalances: ", uniqueBalances);
4783
+ console.log(tag, "uniqueBalances: ", uniqueBalances.size);
5209
4784
  this.balances = Array.from(uniqueBalances.values());
5210
- console.log(tag6, "Updated this.balances: ", this.balances);
4785
+ console.log(tag, "Updated this.balances: ", this.balances.length);
5211
4786
  return this.balances;
5212
4787
  } catch (e) {
5213
- console.error(tag6, "Error in getCharts:", e);
4788
+ console.error(tag, "Error in getCharts:", e);
5214
4789
  throw e;
5215
4790
  }
5216
4791
  };
5217
4792
  this.setContext = async (context) => {
5218
- const tag6 = `${TAG9} | setContext | `;
4793
+ const tag = `${TAG9} | setContext | `;
5219
4794
  try {
5220
4795
  if (!context)
5221
4796
  throw Error("context required!");
@@ -5223,12 +4798,12 @@ class SDK {
5223
4798
  this.events.emit("SET_CONTEXT", context);
5224
4799
  return { success: true };
5225
4800
  } catch (e) {
5226
- console.error(tag6, "e: ", e);
4801
+ console.error(tag, "e: ", e);
5227
4802
  return { success: false };
5228
4803
  }
5229
4804
  };
5230
4805
  this.setContextType = async (contextType) => {
5231
- const tag6 = `${TAG9} | setContextType | `;
4806
+ const tag = `${TAG9} | setContextType | `;
5232
4807
  try {
5233
4808
  if (!contextType)
5234
4809
  throw Error("contextType required!");
@@ -5236,22 +4811,22 @@ class SDK {
5236
4811
  this.events.emit("SET_CONTEXT_TYPE", contextType);
5237
4812
  return { success: true };
5238
4813
  } catch (e) {
5239
- console.error(tag6, "e: ", e);
4814
+ console.error(tag, "e: ", e);
5240
4815
  return { success: false };
5241
4816
  }
5242
4817
  };
5243
4818
  this.refresh = async () => {
5244
- const tag6 = `${TAG9} | refresh | `;
4819
+ const tag = `${TAG9} | refresh | `;
5245
4820
  try {
5246
4821
  await this.sync();
5247
4822
  return this.balances;
5248
4823
  } catch (e) {
5249
- console.error(tag6, "e: ", e);
4824
+ console.error(tag, "e: ", e);
5250
4825
  throw e;
5251
4826
  }
5252
4827
  };
5253
4828
  this.setAssetContext = async function(asset) {
5254
- const tag6 = `${TAG9} | setAssetContext | `;
4829
+ const tag = `${TAG9} | setAssetContext | `;
5255
4830
  try {
5256
4831
  if (!asset) {
5257
4832
  this.assetContext = null;
@@ -5263,7 +4838,7 @@ class SDK {
5263
4838
  asset.networkId = caipToNetworkId7(asset.caip);
5264
4839
  if (!this.pubkeys || this.pubkeys.length === 0) {
5265
4840
  const errorMsg = `Cannot set asset context for ${asset.caip} - no pubkeys loaded. Please initialize wallet first.`;
5266
- console.error(tag6, errorMsg);
4841
+ console.error(tag, errorMsg);
5267
4842
  throw new Error(errorMsg);
5268
4843
  }
5269
4844
  const pubkeysForNetwork = this.pubkeys.filter((e) => {
@@ -5278,8 +4853,8 @@ class SDK {
5278
4853
  });
5279
4854
  if (pubkeysForNetwork.length === 0) {
5280
4855
  const errorMsg = `Cannot set asset context for ${asset.caip} - no address/xpub found for network ${asset.networkId}`;
5281
- console.error(tag6, errorMsg);
5282
- console.error(tag6, "Available networks in pubkeys:", [
4856
+ console.error(tag, errorMsg);
4857
+ console.error(tag, "Available networks in pubkeys:", [
5283
4858
  ...new Set(this.pubkeys.flatMap((p) => p.networks || []))
5284
4859
  ]);
5285
4860
  throw new Error(errorMsg);
@@ -5289,43 +4864,43 @@ class SDK {
5289
4864
  const xpubFound = pubkeysForNetwork.some((p) => p.type === "xpub" && p.pubkey);
5290
4865
  if (!xpubFound) {
5291
4866
  const errorMsg = `Cannot set asset context for UTXO chain ${asset.caip} - xpub required but not found`;
5292
- console.error(tag6, errorMsg);
4867
+ console.error(tag, errorMsg);
5293
4868
  throw new Error(errorMsg);
5294
4869
  }
5295
4870
  }
5296
4871
  const hasValidAddress = pubkeysForNetwork.some((p) => p.address || p.master || p.pubkey);
5297
4872
  if (!hasValidAddress) {
5298
4873
  const errorMsg = `Cannot set asset context for ${asset.caip} - no valid address found in pubkeys`;
5299
- console.error(tag6, errorMsg);
4874
+ console.error(tag, errorMsg);
5300
4875
  throw new Error(errorMsg);
5301
4876
  }
5302
- console.log(tag6, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
4877
+ console.log(tag, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5303
4878
  let freshPriceUsd = 0;
5304
4879
  try {
5305
4880
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5306
- console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
4881
+ console.warn(tag, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5307
4882
  } else {
5308
- console.log(tag6, "Fetching fresh market price for:", asset.caip);
4883
+ console.log(tag, "Fetching fresh market price for:", asset.caip);
5309
4884
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5310
- console.log(tag6, "Market data response:", marketData);
4885
+ console.log(tag, "Market data response:", marketData);
5311
4886
  if (marketData && marketData.data && marketData.data.length > 0) {
5312
4887
  freshPriceUsd = marketData.data[0];
5313
- console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
4888
+ console.log(tag, "✅ Fresh market price:", freshPriceUsd);
5314
4889
  } else {
5315
- console.warn(tag6, "No market data returned for:", asset.caip);
4890
+ console.warn(tag, "No market data returned for:", asset.caip);
5316
4891
  }
5317
4892
  }
5318
4893
  } catch (marketError) {
5319
- console.error(tag6, "Error fetching market price:", marketError);
4894
+ console.error(tag, "Error fetching market price:", marketError);
5320
4895
  }
5321
4896
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5322
- console.log(tag6, "assetInfo: ", assetInfo);
5323
- let assetInfoDiscovery = assetData2[asset.caip];
5324
- console.log(tag6, "assetInfoDiscovery: ", assetInfoDiscovery);
4897
+ console.log(tag, "assetInfo: ", assetInfo);
4898
+ let assetInfoDiscovery = assetData[asset.caip];
4899
+ console.log(tag, "assetInfoDiscovery: ", assetInfoDiscovery);
5325
4900
  if (assetInfoDiscovery)
5326
4901
  assetInfo = assetInfoDiscovery;
5327
4902
  if (!assetInfo) {
5328
- console.log(tag6, "Building placeholder asset!");
4903
+ console.log(tag, "Building placeholder asset!");
5329
4904
  assetInfo = {
5330
4905
  caip: asset.caip.toLowerCase(),
5331
4906
  networkId: asset.networkId,
@@ -5342,30 +4917,30 @@ class SDK {
5342
4917
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5343
4918
  if (balance > 0 && valueUsd > 0) {
5344
4919
  priceValue = valueUsd / balance;
5345
- console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
4920
+ console.log(tag, "calculated priceUsd from valueUsd/balance:", priceValue);
5346
4921
  }
5347
4922
  }
5348
4923
  if (priceValue && priceValue > 0) {
5349
- console.log(tag6, "detected priceUsd from balance:", priceValue);
4924
+ console.log(tag, "detected priceUsd from balance:", priceValue);
5350
4925
  assetInfo.priceUsd = priceValue;
5351
4926
  }
5352
4927
  }
5353
4928
  if (freshPriceUsd && freshPriceUsd > 0) {
5354
4929
  assetInfo.priceUsd = freshPriceUsd;
5355
- console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
4930
+ console.log(tag, "✅ Using fresh market price:", freshPriceUsd);
5356
4931
  let totalBalance = 0;
5357
4932
  let totalValueUsd = 0;
5358
- console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
4933
+ console.log(tag, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5359
4934
  for (const balanceEntry of matchingBalances) {
5360
4935
  const balance = parseFloat(balanceEntry.balance) || 0;
5361
4936
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5362
4937
  totalBalance += balance;
5363
4938
  totalValueUsd += valueUsd;
5364
- console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
4939
+ console.log(tag, ` Balance entry: ${balance} (${valueUsd} USD)`);
5365
4940
  }
5366
4941
  assetInfo.balance = totalBalance.toString();
5367
4942
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5368
- console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
4943
+ console.log(tag, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5369
4944
  }
5370
4945
  const assetBalances = this.balances.filter((b2) => b2.caip === asset.caip);
5371
4946
  const assetPubkeys = this.pubkeys.filter((p) => p.networks && Array.isArray(p.networks) && p.networks.includes(caipToNetworkId7(asset.caip)) || caipToNetworkId7(asset.caip).includes("eip155") && p.networks && Array.isArray(p.networks) && p.networks.some((n) => n.startsWith("eip155")));
@@ -5385,7 +4960,7 @@ class SDK {
5385
4960
  const balanceAmount = parseFloat(balance.balance || 0);
5386
4961
  balance.valueUsd = (balanceAmount * freshPriceUsd).toString();
5387
4962
  }
5388
- console.log(tag6, "Updated all balances with fresh price data");
4963
+ console.log(tag, "Updated all balances with fresh price data");
5389
4964
  }
5390
4965
  this.assetContext = finalAssetContext;
5391
4966
  if (asset.isToken || asset.type === "token" || assetInfo.isToken || assetInfo.type === "token") {
@@ -5437,20 +5012,20 @@ class SDK {
5437
5012
  const currentContextValid = this.pubkeyContext?.networks?.includes(networkId);
5438
5013
  if (!this.pubkeyContext || !currentContextValid) {
5439
5014
  this.pubkeyContext = assetPubkeys[0];
5440
- console.log(tag6, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5015
+ console.log(tag, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5441
5016
  } else {
5442
- console.log(tag6, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5017
+ console.log(tag, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5443
5018
  }
5444
5019
  }
5445
5020
  this.events.emit("SET_ASSET_CONTEXT", this.assetContext);
5446
5021
  return this.assetContext;
5447
5022
  } catch (e) {
5448
- console.error(tag6, "e: ", e);
5023
+ console.error(tag, "e: ", e);
5449
5024
  throw e;
5450
5025
  }
5451
5026
  };
5452
5027
  this.setPubkeyContext = async function(pubkey) {
5453
- let tag6 = `${TAG9} | setPubkeyContext | `;
5028
+ let tag = `${TAG9} | setPubkeyContext | `;
5454
5029
  try {
5455
5030
  if (!pubkey)
5456
5031
  throw Error("pubkey is required");
@@ -5458,31 +5033,31 @@ class SDK {
5458
5033
  throw Error("invalid pubkey: missing pubkey or address");
5459
5034
  const exists = this.pubkeys.some((pk) => pk.pubkey === pubkey.pubkey || pk.address === pubkey.address || pk.pubkey === pubkey.address);
5460
5035
  if (!exists) {
5461
- console.warn(tag6, "Pubkey not found in current pubkeys array");
5036
+ console.warn(tag, "Pubkey not found in current pubkeys array");
5462
5037
  }
5463
5038
  this.pubkeyContext = pubkey;
5464
- console.log(tag6, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5039
+ console.log(tag, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5465
5040
  return true;
5466
5041
  } catch (e) {
5467
- console.error(tag6, "e: ", e);
5042
+ console.error(tag, "e: ", e);
5468
5043
  throw e;
5469
5044
  }
5470
5045
  };
5471
5046
  this.setOutboundAssetContext = async function(asset) {
5472
- const tag6 = `${TAG9} | setOutputAssetContext | `;
5047
+ const tag = `${TAG9} | setOutputAssetContext | `;
5473
5048
  try {
5474
- console.log(tag6, "0. asset: ", asset);
5049
+ console.log(tag, "0. asset: ", asset);
5475
5050
  if (!asset) {
5476
5051
  this.outboundAssetContext = null;
5477
5052
  return;
5478
5053
  }
5479
- console.log(tag6, "1 asset: ", asset);
5054
+ console.log(tag, "1 asset: ", asset);
5480
5055
  if (!asset.caip)
5481
5056
  throw Error("Invalid Asset! missing caip!");
5482
5057
  if (!asset.networkId)
5483
5058
  asset.networkId = caipToNetworkId7(asset.caip);
5484
- console.log(tag6, "networkId: ", asset.networkId);
5485
- console.log(tag6, "this.pubkeys: ", this.pubkeys);
5059
+ console.log(tag, "networkId: ", asset.networkId);
5060
+ console.log(tag, "this.pubkeys: ", this.pubkeys);
5486
5061
  const pubkey = this.pubkeys.find((p) => {
5487
5062
  if (!p.networks || !Array.isArray(p.networks))
5488
5063
  return false;
@@ -5497,23 +5072,23 @@ class SDK {
5497
5072
  let freshPriceUsd = 0;
5498
5073
  try {
5499
5074
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5500
- console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5075
+ console.warn(tag, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5501
5076
  } else {
5502
- console.log(tag6, "Fetching fresh market price for:", asset.caip);
5077
+ console.log(tag, "Fetching fresh market price for:", asset.caip);
5503
5078
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5504
- console.log(tag6, "Market data response:", marketData);
5079
+ console.log(tag, "Market data response:", marketData);
5505
5080
  if (marketData && marketData.data && marketData.data.length > 0) {
5506
5081
  freshPriceUsd = marketData.data[0];
5507
- console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5082
+ console.log(tag, "✅ Fresh market price:", freshPriceUsd);
5508
5083
  } else {
5509
- console.warn(tag6, "No market data returned for:", asset.caip);
5084
+ console.warn(tag, "No market data returned for:", asset.caip);
5510
5085
  }
5511
5086
  }
5512
5087
  } catch (marketError) {
5513
- console.error(tag6, "Error fetching market price:", marketError);
5088
+ console.error(tag, "Error fetching market price:", marketError);
5514
5089
  }
5515
5090
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5516
- console.log(tag6, "assetInfo: ", assetInfo);
5091
+ console.log(tag, "assetInfo: ", assetInfo);
5517
5092
  if (!assetInfo) {
5518
5093
  assetInfo = {
5519
5094
  caip: asset.caip.toLowerCase(),
@@ -5531,45 +5106,45 @@ class SDK {
5531
5106
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5532
5107
  if (balance > 0 && valueUsd > 0) {
5533
5108
  priceValue = valueUsd / balance;
5534
- console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5109
+ console.log(tag, "calculated priceUsd from valueUsd/balance:", priceValue);
5535
5110
  }
5536
5111
  }
5537
5112
  if (priceValue && priceValue > 0) {
5538
- console.log(tag6, "detected priceUsd from balance:", priceValue);
5113
+ console.log(tag, "detected priceUsd from balance:", priceValue);
5539
5114
  assetInfo.priceUsd = priceValue;
5540
5115
  }
5541
5116
  }
5542
5117
  if (freshPriceUsd && freshPriceUsd > 0) {
5543
5118
  assetInfo.priceUsd = freshPriceUsd;
5544
- console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5119
+ console.log(tag, "✅ Using fresh market price:", freshPriceUsd);
5545
5120
  let totalBalance = 0;
5546
5121
  let totalValueUsd = 0;
5547
- console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5122
+ console.log(tag, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5548
5123
  for (const balanceEntry of matchingBalances) {
5549
5124
  const balance = parseFloat(balanceEntry.balance) || 0;
5550
5125
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5551
5126
  totalBalance += balance;
5552
5127
  totalValueUsd += valueUsd;
5553
- console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5128
+ console.log(tag, ` Balance entry: ${balance} (${valueUsd} USD)`);
5554
5129
  }
5555
5130
  assetInfo.balance = totalBalance.toString();
5556
5131
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5557
- console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5132
+ console.log(tag, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5558
5133
  }
5559
- console.log(tag6, "CHECKPOINT 1");
5134
+ console.log(tag, "CHECKPOINT 1");
5560
5135
  this.outboundAssetContext = { ...assetInfo, ...asset, ...pubkey };
5561
- console.log(tag6, "CHECKPOINT 3");
5562
- console.log(tag6, "outboundAssetContext: assetInfo: ", assetInfo);
5136
+ console.log(tag, "CHECKPOINT 3");
5137
+ console.log(tag, "outboundAssetContext: assetInfo: ", assetInfo);
5563
5138
  if (asset.caip) {
5564
5139
  this.outboundBlockchainContext = caipToNetworkId7(asset.caip);
5565
5140
  } else if (asset.networkId) {
5566
5141
  this.outboundBlockchainContext = asset.networkId;
5567
5142
  }
5568
- console.log(tag6, "CHECKPOINT 4");
5143
+ console.log(tag, "CHECKPOINT 4");
5569
5144
  this.events.emit("SET_OUTBOUND_ASSET_CONTEXT", this.outboundAssetContext);
5570
5145
  return this.outboundAssetContext;
5571
5146
  } catch (e) {
5572
- console.error(tag6, "e: ", e);
5147
+ console.error(tag, "e: ", e);
5573
5148
  throw e;
5574
5149
  }
5575
5150
  };