@pioneer-platform/pioneer-sdk 8.14.1 → 8.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -39,6 +39,7 @@ var __export = (target, all) => {
39
39
  set: (newValue) => all[name] = () => newValue
40
40
  });
41
41
  };
42
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
42
43
 
43
44
  // ../../../node_modules/coinselect/utils.js
44
45
  var require_utils = __commonJS((exports2, module2) => {
@@ -236,6 +237,546 @@ var require_split = __commonJS((exports2, module2) => {
236
237
  };
237
238
  });
238
239
 
240
+ // src/charts/utils.ts
241
+ function hydrateAssetData(caip) {
242
+ return import_pioneer_discovery.assetData[caip] || import_pioneer_discovery.assetData[caip.toLowerCase()];
243
+ }
244
+ function checkDuplicateBalance(balances, caip, pubkey, validator) {
245
+ return balances.some((b) => b.caip === caip && b.pubkey === pubkey && (!validator || b.validator === validator));
246
+ }
247
+ function createBalanceIdentifier(caip, pubkey) {
248
+ return `${caip}:${pubkey}`;
249
+ }
250
+ var import_pioneer_discovery;
251
+ var init_utils = __esm(() => {
252
+ import_pioneer_discovery = require("@pioneer-platform/pioneer-discovery");
253
+ });
254
+
255
+ // src/charts/custom-tokens.ts
256
+ async function fetchCustomTokens(params, balances) {
257
+ const { pioneer, pubkeys, blockchains, context } = params;
258
+ console.log(tag, "Fetching custom tokens...");
259
+ const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
260
+ const primaryAddress = evmPubkey?.address || evmPubkey?.master;
261
+ if (!primaryAddress) {
262
+ console.log(tag, "No EVM address found, skipping custom tokens");
263
+ return;
264
+ }
265
+ console.log(tag, "Using EVM address for custom tokens:", primaryAddress);
266
+ const supportedNetworks = blockchains.filter((net) => net.startsWith("eip155:"));
267
+ if (supportedNetworks.length === 0) {
268
+ console.log(tag, "No EVM networks for custom tokens");
269
+ return;
270
+ }
271
+ console.log(tag, `Checking custom tokens on ${supportedNetworks.length} networks`);
272
+ for (const networkId of supportedNetworks) {
273
+ try {
274
+ const response = await pioneer.GetCustomTokens({ networkId, userAddress: primaryAddress });
275
+ const customTokens = response?.data?.tokens || [];
276
+ console.log(tag, `Found ${customTokens.length} custom tokens on ${networkId}`);
277
+ for (const token of customTokens) {
278
+ const chartBalance = processCustomToken(token, primaryAddress, context, blockchains);
279
+ if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
280
+ balances.push(chartBalance);
281
+ console.log(tag, `Added custom token: ${chartBalance.symbol} = ${chartBalance.balance}`);
282
+ }
283
+ }
284
+ } catch (error) {
285
+ console.error(tag, `Error fetching custom tokens for ${networkId}:`, error.message);
286
+ }
287
+ }
288
+ console.log(tag, `Custom tokens complete. Total balances: ${balances.length}`);
289
+ }
290
+ function processCustomToken(token, primaryAddress, context, blockchains) {
291
+ if (!token.assetCaip || !token.networkId) {
292
+ return null;
293
+ }
294
+ let extractedNetworkId = token.networkId;
295
+ if (token.assetCaip.includes("/denom:")) {
296
+ const parts = token.assetCaip.split("/denom:");
297
+ if (parts.length > 0) {
298
+ extractedNetworkId = parts[0];
299
+ }
300
+ } else if (token.networkId && token.networkId.includes("/")) {
301
+ extractedNetworkId = token.networkId.split("/")[0];
302
+ }
303
+ const isEip155 = extractedNetworkId.startsWith("eip155:");
304
+ if (!isEip155 && !blockchains.includes(extractedNetworkId)) {
305
+ return null;
306
+ }
307
+ const tokenAssetInfo = hydrateAssetData(token.assetCaip);
308
+ const tokenPubkey = token.pubkey || primaryAddress;
309
+ const chartBalance = {
310
+ context,
311
+ chart: "pioneer",
312
+ contextType: context.split(":")[0],
313
+ name: tokenAssetInfo?.name || token.token?.name || "Unknown Custom Token",
314
+ caip: token.assetCaip,
315
+ icon: tokenAssetInfo?.icon || token.token?.icon || "",
316
+ pubkey: tokenPubkey,
317
+ ticker: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
318
+ ref: `${context}${token.assetCaip}`,
319
+ identifier: createBalanceIdentifier(token.assetCaip, tokenPubkey),
320
+ networkId: extractedNetworkId,
321
+ symbol: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
322
+ type: tokenAssetInfo?.type || "erc20",
323
+ token: true,
324
+ decimal: tokenAssetInfo?.decimal || token.token?.decimal,
325
+ balance: token.token?.balance?.toString() || "0",
326
+ priceUsd: token.token?.price || 0,
327
+ valueUsd: token.token?.balanceUSD || 0,
328
+ updated: new Date().getTime()
329
+ };
330
+ return chartBalance;
331
+ }
332
+ var tag = "| charts-custom-tokens |";
333
+ var init_custom_tokens = __esm(() => {
334
+ init_utils();
335
+ });
336
+
337
+ // src/charts/evm.ts
338
+ async function getEvmCharts(params) {
339
+ const { blockchains, pioneer, pubkeys, context } = params;
340
+ const balances = [];
341
+ const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
342
+ const primaryAddress = evmPubkey?.address || evmPubkey?.master;
343
+ console.log(tag2, "Total pubkeys available:", pubkeys.length);
344
+ console.log(tag2, "Blockchains to process:", blockchains);
345
+ const pubkeysForBatch = [];
346
+ for (const pubkey of pubkeys) {
347
+ const address = pubkey.address || pubkey.master || pubkey.pubkey;
348
+ if (!address)
349
+ continue;
350
+ const supportedNetworks = pubkey.networks || [];
351
+ for (const blockchain of blockchains) {
352
+ const supportsNetwork = supportedNetworks.some((net) => net === blockchain || net.endsWith(":*") && blockchain.startsWith(net.replace(":*", ":")));
353
+ if (supportsNetwork) {
354
+ let caip;
355
+ if (blockchain.startsWith("eip155:")) {
356
+ caip = `${blockchain}/slip44:60`;
357
+ } else {
358
+ caip = `${blockchain}/slip44:0`;
359
+ }
360
+ pubkeysForBatch.push({
361
+ pubkey: address,
362
+ caip
363
+ });
364
+ }
365
+ }
366
+ }
367
+ console.log(tag2, `Built ${pubkeysForBatch.length} pubkey-chain combinations for batch request`);
368
+ if (pubkeysForBatch.length === 0) {
369
+ console.log(tag2, "No pubkeys to query, skipping portfolio lookup");
370
+ return balances;
371
+ }
372
+ if (primaryAddress) {
373
+ await fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context);
374
+ }
375
+ await fetchCustomTokens({ blockchains, pioneer, pubkeys, context }, balances);
376
+ try {
377
+ console.log(tag2, `Calling GetPortfolio with ${pubkeysForBatch.length} pubkeys (batch + non-blocking)`);
378
+ let portfolio = await pioneer.GetPortfolio({
379
+ pubkeys: pubkeysForBatch
380
+ });
381
+ portfolio = portfolio.data?.data || portfolio.data;
382
+ if (!portfolio || !portfolio.balances) {
383
+ console.error(tag2, "No portfolio.balances found:", portfolio);
384
+ return balances;
385
+ }
386
+ console.log(tag2, `Portfolio returned ${portfolio.balances.length} balances`);
387
+ let processedCount = 0;
388
+ let skippedCount = 0;
389
+ for (const balance of portfolio.balances) {
390
+ const processedBalance = processPortfolioBalance(balance, primaryAddress, context, blockchains);
391
+ if (processedBalance) {
392
+ if (!checkDuplicateBalance(balances, processedBalance.caip, processedBalance.pubkey)) {
393
+ balances.push(processedBalance);
394
+ processedCount++;
395
+ }
396
+ } else {
397
+ skippedCount++;
398
+ }
399
+ }
400
+ console.log(tag2, `Processed ${processedCount} balances, skipped ${skippedCount}`);
401
+ if (portfolio.tokens && portfolio.tokens.length > 0) {
402
+ console.log(tag2, "Processing portfolio.tokens:", portfolio.tokens.length);
403
+ for (const token of portfolio.tokens) {
404
+ const processedToken = processPortfolioToken(token, primaryAddress, context, blockchains);
405
+ if (processedToken && !checkDuplicateBalance(balances, processedToken.caip, processedToken.pubkey)) {
406
+ balances.push(processedToken);
407
+ }
408
+ }
409
+ }
410
+ console.log(tag2, `Total balances (native + tokens): ${balances.length}`);
411
+ } catch (e) {
412
+ console.error(tag2, "Error fetching portfolio:", e);
413
+ }
414
+ return balances;
415
+ }
416
+ function processPortfolioBalance(balance, primaryAddress, context, blockchains) {
417
+ if (!balance.caip) {
418
+ console.error(tag2, "No caip found for:", balance);
419
+ return null;
420
+ }
421
+ const networkId = balance.caip.split("/")[0];
422
+ const isEip155 = networkId.startsWith("eip155:");
423
+ if (!isEip155 && !blockchains.includes(networkId)) {
424
+ return null;
425
+ }
426
+ const assetInfo = hydrateAssetData(balance.caip);
427
+ const balancePubkey = balance.pubkey || primaryAddress;
428
+ const balanceType = assetInfo?.type || balance.type || "native";
429
+ const isToken = balanceType !== "native" && balance.caip.includes("/erc20:");
430
+ let calculatedPrice = balance.priceUsd || balance.price || 0;
431
+ if ((!calculatedPrice || calculatedPrice === 0) && balance.valueUsd && balance.balance) {
432
+ const balanceNum = parseFloat(balance.balance.toString());
433
+ const valueNum = parseFloat(balance.valueUsd.toString());
434
+ if (balanceNum > 0 && valueNum > 0) {
435
+ calculatedPrice = valueNum / balanceNum;
436
+ console.log(tag2, `Calculated price from value/balance: ${calculatedPrice} for ${balance.caip}`);
437
+ }
438
+ }
439
+ const chartBalance = {
440
+ context,
441
+ chart: "pioneer",
442
+ contextType: "keepkey",
443
+ name: assetInfo?.name || balance.name || "Unknown",
444
+ caip: balance.caip,
445
+ icon: assetInfo?.icon || balance.icon || "",
446
+ pubkey: balancePubkey,
447
+ ticker: assetInfo?.symbol || balance.symbol || "UNK",
448
+ ref: `${context}${balance.caip}`,
449
+ identifier: createBalanceIdentifier(balance.caip, balancePubkey),
450
+ networkId,
451
+ chain: networkId,
452
+ symbol: assetInfo?.symbol || balance.symbol || "UNK",
453
+ type: balanceType,
454
+ token: isToken,
455
+ decimal: assetInfo?.decimal || balance.decimal,
456
+ balance: balance.balance.toString(),
457
+ price: calculatedPrice,
458
+ priceUsd: calculatedPrice,
459
+ valueUsd: balance.valueUsd.toString(),
460
+ updated: new Date().getTime()
461
+ };
462
+ if (balance.display) {
463
+ chartBalance.icon = ["multi", chartBalance.icon, balance.display.toString()].toString();
464
+ }
465
+ return chartBalance;
466
+ }
467
+ function processPortfolioToken(token, primaryAddress, context, blockchains) {
468
+ if (!token.assetCaip || !token.networkId) {
469
+ return null;
470
+ }
471
+ let extractedNetworkId = token.networkId;
472
+ if (token.assetCaip.includes("/denom:")) {
473
+ const parts = token.assetCaip.split("/denom:");
474
+ if (parts.length > 0) {
475
+ extractedNetworkId = parts[0];
476
+ }
477
+ } else if (token.networkId && token.networkId.includes("/")) {
478
+ extractedNetworkId = token.networkId.split("/")[0];
479
+ }
480
+ const isEip155 = extractedNetworkId.startsWith("eip155:");
481
+ if (!isEip155 && !blockchains.includes(extractedNetworkId)) {
482
+ return null;
483
+ }
484
+ const tokenAssetInfo = hydrateAssetData(token.assetCaip);
485
+ const tokenPubkey = token.pubkey || primaryAddress;
486
+ const chartBalance = {
487
+ context,
488
+ chart: "pioneer",
489
+ contextType: context.split(":")[0],
490
+ name: tokenAssetInfo?.name || token.token?.coingeckoId || token.token?.name || "Unknown",
491
+ caip: token.assetCaip,
492
+ icon: tokenAssetInfo?.icon || token.token?.icon || "",
493
+ pubkey: tokenPubkey,
494
+ ticker: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
495
+ ref: `${context}${token.assetCaip}`,
496
+ identifier: createBalanceIdentifier(token.assetCaip, tokenPubkey),
497
+ networkId: extractedNetworkId,
498
+ symbol: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
499
+ type: tokenAssetInfo?.type || "token",
500
+ token: true,
501
+ decimal: tokenAssetInfo?.decimal || token.token?.decimal,
502
+ balance: token.token?.balance?.toString() || "0",
503
+ priceUsd: token.token?.price || 0,
504
+ valueUsd: token.token?.balanceUSD || 0,
505
+ updated: new Date().getTime()
506
+ };
507
+ return chartBalance;
508
+ }
509
+ async function fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context) {
510
+ console.log(tag2, "Fetching stable coins for redundancy...");
511
+ try {
512
+ const fastFlag = typeof process !== "undefined" && process.env && process.env.PIONEER_FAST === "1";
513
+ const isTestContext = typeof context === "string" && /test|e2e/i.test(context);
514
+ if (fastFlag || isTestContext) {
515
+ console.log(tag2, "Fast mode detected (test/e2e). Skipping stable coin redundancy.");
516
+ return;
517
+ }
518
+ } catch (_) {
519
+ }
520
+ const supportedNetworks = ["eip155:1", "eip155:137", "eip155:8453", "eip155:56"];
521
+ const networksToCheck = blockchains.filter((net) => supportedNetworks.includes(net));
522
+ if (networksToCheck.length === 0) {
523
+ console.log(tag2, "No supported networks for stable coins");
524
+ return;
525
+ }
526
+ console.log(tag2, `Checking stable coins on ${networksToCheck.length} networks`);
527
+ const withTimeout2 = (p, ms) => {
528
+ return new Promise((resolve, reject) => {
529
+ const t = setTimeout(() => reject(new Error(`timeout ${ms}ms`)), ms);
530
+ p.then((v) => {
531
+ clearTimeout(t);
532
+ resolve(v);
533
+ }).catch((e) => {
534
+ clearTimeout(t);
535
+ reject(e);
536
+ });
537
+ });
538
+ };
539
+ const results = await Promise.allSettled(networksToCheck.map(async (networkId) => {
540
+ try {
541
+ const response = await withTimeout2(pioneer.GetStableCoins({ networkId, address: primaryAddress }), 2000);
542
+ const stableCoins = response?.data?.tokens || [];
543
+ console.log(tag2, `Found ${stableCoins.length} stable coins on ${networkId}`);
544
+ for (const token of stableCoins) {
545
+ const chartBalance = processPortfolioToken(token, primaryAddress, context, blockchains);
546
+ if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
547
+ balances.push(chartBalance);
548
+ console.log(tag2, `Added stable coin: ${chartBalance.symbol} = ${chartBalance.balance}`);
549
+ }
550
+ }
551
+ } catch (error) {
552
+ console.error(tag2, `Error fetching stable coins for ${networkId}:`, error?.message || error);
553
+ }
554
+ }));
555
+ const failures = results.filter((r) => r.status === "rejected").length;
556
+ if (failures > 0)
557
+ console.log(tag2, `Stable coin fetch had ${failures} failures (non-blocking)`);
558
+ console.log(tag2, `Stable coin redundancy complete. Total balances: ${balances.length}`);
559
+ }
560
+ var tag2 = "| charts-evm |";
561
+ var init_evm = __esm(() => {
562
+ init_utils();
563
+ init_custom_tokens();
564
+ });
565
+
566
+ // src/charts/maya.ts
567
+ async function getMayaCharts(params, existingBalances) {
568
+ const { blockchains, pioneer, pubkeys, context } = params;
569
+ const balances = [];
570
+ try {
571
+ const mayaPubkey = pubkeys.find((p) => p.networks && Array.isArray(p.networks) && p.networks.includes("cosmos:mayachain-mainnet-v1"));
572
+ if (!mayaPubkey || !mayaPubkey.address) {
573
+ console.log(tag3, "No MAYA pubkey found, skipping MAYA token fetch");
574
+ return balances;
575
+ }
576
+ if (!blockchains.includes("cosmos:mayachain-mainnet-v1")) {
577
+ console.log(tag3, "MAYA network not in blockchains list, skipping MAYA token fetch");
578
+ return balances;
579
+ }
580
+ const hasMayaToken = existingBalances.some((b) => b.caip === "cosmos:mayachain-mainnet-v1/denom:maya");
581
+ if (hasMayaToken) {
582
+ console.log(tag3, "MAYA token already exists in balances, skipping");
583
+ return balances;
584
+ }
585
+ console.log(tag3, "MAYA token not found in portfolio, fetching separately...");
586
+ console.log(tag3, "MAYA pubkey address:", mayaPubkey.address);
587
+ const mayaBalanceResponse = await pioneer.GetPortfolioBalances({
588
+ pubkeys: [
589
+ {
590
+ caip: "cosmos:mayachain-mainnet-v1/denom:maya",
591
+ pubkey: mayaPubkey.address
592
+ }
593
+ ]
594
+ });
595
+ console.log(tag3, "MAYA balance response:", JSON.stringify(mayaBalanceResponse?.data, null, 2));
596
+ if (!mayaBalanceResponse?.data || mayaBalanceResponse.data.length === 0) {
597
+ console.log(tag3, "No MAYA token balance returned from GetPortfolioBalances API");
598
+ return balances;
599
+ }
600
+ console.log(tag3, "Found MAYA token balances:", mayaBalanceResponse.data.length);
601
+ for (const mayaBalance of mayaBalanceResponse.data) {
602
+ if (mayaBalance.caip !== "cosmos:mayachain-mainnet-v1/denom:maya") {
603
+ console.log(tag3, "Unexpected balance in MAYA response:", mayaBalance);
604
+ continue;
605
+ }
606
+ const mayaAssetInfo = hydrateAssetData(mayaBalance.caip);
607
+ const isToken = mayaBalance.caip.includes("/denom:") && !mayaBalance.caip.endsWith("/denom:cacao");
608
+ const mayaTokenBalance = {
609
+ context,
610
+ chart: "pioneer",
611
+ contextType: context.split(":")[0],
612
+ name: mayaAssetInfo?.name || "Maya Token",
613
+ caip: mayaBalance.caip,
614
+ icon: mayaAssetInfo?.icon || "https://pioneers.dev/coins/maya.png",
615
+ pubkey: mayaPubkey.address,
616
+ ticker: mayaAssetInfo?.symbol || "MAYA",
617
+ ref: `${context}${mayaBalance.caip}`,
618
+ identifier: createBalanceIdentifier(mayaBalance.caip, mayaPubkey.address),
619
+ networkId: "cosmos:mayachain-mainnet-v1",
620
+ symbol: mayaAssetInfo?.symbol || "MAYA",
621
+ type: mayaAssetInfo?.type || "token",
622
+ token: isToken,
623
+ decimal: mayaAssetInfo?.decimal,
624
+ balance: mayaBalance.balance?.toString() || "0",
625
+ priceUsd: parseFloat(mayaBalance.priceUsd) || 0,
626
+ valueUsd: parseFloat(mayaBalance.valueUsd) || 0,
627
+ updated: new Date().getTime()
628
+ };
629
+ console.log(tag3, "Adding MAYA token to balances:", mayaTokenBalance);
630
+ balances.push(mayaTokenBalance);
631
+ }
632
+ } catch (mayaError) {
633
+ console.error(tag3, "Error fetching MAYA token balance:", mayaError);
634
+ }
635
+ return balances;
636
+ }
637
+ var tag3 = "| charts-maya |";
638
+ var init_maya = __esm(() => {
639
+ init_utils();
640
+ });
641
+
642
+ // src/charts/cosmos-staking.ts
643
+ async function getCosmosStakingCharts(params) {
644
+ const { blockchains, pioneer, pubkeys, context } = params;
645
+ const balances = [];
646
+ try {
647
+ try {
648
+ const fastFlag = typeof process !== "undefined" && process.env && process.env.PIONEER_FAST === "1";
649
+ const isTestContext = typeof context === "string" && /test|e2e/i.test(context);
650
+ if (fastFlag || isTestContext) {
651
+ console.log(tag4, "Fast mode detected (test/e2e). Skipping cosmos staking fetch.");
652
+ return balances;
653
+ }
654
+ } catch (_) {
655
+ }
656
+ console.log(tag4, "Adding Cosmos staking positions to charts...");
657
+ const cosmosPubkeys = pubkeys.filter((p) => p.networks && Array.isArray(p.networks) && p.networks.some((n) => n.includes("cosmos:cosmoshub") || n.includes("cosmos:osmosis")));
658
+ if (cosmosPubkeys.length === 0) {
659
+ console.log(tag4, "No cosmos pubkeys found for staking positions");
660
+ return balances;
661
+ }
662
+ console.log(tag4, "Found cosmos pubkeys for staking:", cosmosPubkeys.length);
663
+ await Promise.allSettled(cosmosPubkeys.map(async (cosmosPubkey) => {
664
+ if (!cosmosPubkey.address)
665
+ return;
666
+ const cosmosNetworks = cosmosPubkey.networks.filter((n) => n.includes("cosmos:cosmoshub") || n.includes("cosmos:osmosis"));
667
+ await Promise.allSettled(cosmosNetworks.filter((networkId) => blockchains.includes(networkId)).map(async (networkId) => {
668
+ await fetchStakingPositionsForNetwork(networkId, cosmosPubkey.address, context, pioneer, balances);
669
+ }));
670
+ }));
671
+ } catch (e) {
672
+ console.error(tag4, "Error adding cosmos staking positions:", e);
673
+ }
674
+ return balances;
675
+ }
676
+ async function fetchStakingPositionsForNetwork(networkId, address, context, pioneer, balances) {
677
+ try {
678
+ console.log(tag4, `Fetching staking positions for ${address} on ${networkId}...`);
679
+ let network;
680
+ if (networkId === "cosmos:cosmoshub-4") {
681
+ network = "cosmos";
682
+ } else if (networkId === "cosmos:osmosis-1") {
683
+ network = "osmosis";
684
+ } else {
685
+ console.error(tag4, `Unsupported networkId for staking: ${networkId}`);
686
+ return;
687
+ }
688
+ const stakingResponse = await pioneer.GetStakingPositions({
689
+ network,
690
+ address
691
+ });
692
+ if (!stakingResponse?.data || !Array.isArray(stakingResponse.data)) {
693
+ console.log(tag4, `No staking positions found for ${address} on ${networkId}`);
694
+ return;
695
+ }
696
+ console.log(tag4, `Found ${stakingResponse.data.length} staking positions for ${networkId}`);
697
+ for (const position of stakingResponse.data) {
698
+ const processedPosition = processStakingPosition(position, address, context, networkId);
699
+ if (processedPosition && !checkDuplicateBalance(balances, processedPosition.caip, processedPosition.pubkey, processedPosition.validator)) {
700
+ balances.push(processedPosition);
701
+ console.log(tag4, `Added ${position.type} position:`, {
702
+ balance: processedPosition.balance,
703
+ ticker: processedPosition.ticker,
704
+ valueUsd: processedPosition.valueUsd,
705
+ validator: processedPosition.validator
706
+ });
707
+ }
708
+ }
709
+ } catch (stakingError) {
710
+ console.error(tag4, `Error fetching staking positions for ${address} on ${networkId}:`, stakingError);
711
+ }
712
+ }
713
+ function processStakingPosition(position, address, context, networkId) {
714
+ if (!position.balance || position.balance <= 0 || !position.caip) {
715
+ return null;
716
+ }
717
+ const stakingAssetInfo = hydrateAssetData(position.caip);
718
+ const stakingBalance = {
719
+ context,
720
+ chart: "staking",
721
+ contextType: context.split(":")[0],
722
+ name: stakingAssetInfo?.name || position.name || `${position.type} Position`,
723
+ caip: position.caip,
724
+ icon: stakingAssetInfo?.icon || position.icon || "",
725
+ pubkey: address,
726
+ ticker: stakingAssetInfo?.symbol || position.ticker || position.symbol || "UNK",
727
+ ref: `${context}${position.caip}`,
728
+ identifier: createBalanceIdentifier(position.caip, address),
729
+ networkId,
730
+ symbol: stakingAssetInfo?.symbol || position.symbol || position.ticker || "UNK",
731
+ type: stakingAssetInfo?.type || position.type || "staking",
732
+ token: false,
733
+ decimal: stakingAssetInfo?.decimal,
734
+ balance: position.balance.toString(),
735
+ priceUsd: position.priceUsd || 0,
736
+ valueUsd: position.valueUsd || position.balance * (position.priceUsd || 0),
737
+ status: position.status || "active",
738
+ validator: position.validatorAddress || position.validator || "",
739
+ updated: new Date().getTime()
740
+ };
741
+ return stakingBalance;
742
+ }
743
+ var tag4 = "| charts-cosmos-staking |";
744
+ var init_cosmos_staking = __esm(() => {
745
+ init_utils();
746
+ });
747
+ // src/charts/index.ts
748
+ var exports_charts = {};
749
+ __export(exports_charts, {
750
+ getCharts: () => getCharts
751
+ });
752
+ var tag5 = "| getCharts |", getCharts = async (blockchains, pioneer, pubkeys, context) => {
753
+ try {
754
+ const balances = [];
755
+ console.log(tag5, "init");
756
+ const params = {
757
+ blockchains,
758
+ pioneer,
759
+ pubkeys,
760
+ context
761
+ };
762
+ const evmBalances = await getEvmCharts(params);
763
+ balances.push(...evmBalances);
764
+ const mayaBalances = await getMayaCharts(params, balances);
765
+ balances.push(...mayaBalances);
766
+ const stakingBalances = await getCosmosStakingCharts(params);
767
+ balances.push(...stakingBalances);
768
+ return balances;
769
+ } catch (error) {
770
+ console.error(tag5, "Error processing charts:", error);
771
+ throw error;
772
+ }
773
+ };
774
+ var init_charts = __esm(() => {
775
+ init_evm();
776
+ init_maya();
777
+ init_cosmos_staking();
778
+ });
779
+
239
780
  // src/index.ts
240
781
  var exports_src = {};
241
782
  __export(exports_src, {
@@ -390,7 +931,7 @@ class Pioneer {
390
931
 
391
932
  // src/index.ts
392
933
  var import_pioneer_coins4 = require("@pioneer-platform/pioneer-coins");
393
- var import_pioneer_discovery = require("@pioneer-platform/pioneer-discovery");
934
+ var import_pioneer_discovery2 = require("@pioneer-platform/pioneer-discovery");
394
935
  var import_pioneer_events = require("@pioneer-platform/pioneer-events");
395
936
  var import_events = __toESM(require("events"));
396
937
 
@@ -1441,9 +1982,16 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
1441
1982
  accountInfo = accountInfo.data;
1442
1983
  const sequence = accountInfo.Sequence.toString();
1443
1984
  const ledgerIndexCurrent = parseInt(accountInfo.ledger_index_current);
1444
- let desttag = memo;
1445
- if (!desttag || /^\s*$/.test(desttag) || isNaN(desttag)) {
1446
- desttag = "0";
1985
+ let desttag = undefined;
1986
+ if (memo && memo.trim() !== "") {
1987
+ if (!/^\d+$/.test(memo.trim())) {
1988
+ throw new Error(`XRP destination tag must be numeric. Got: "${memo}"`);
1989
+ }
1990
+ const tagNum = parseInt(memo.trim(), 10);
1991
+ if (isNaN(tagNum) || tagNum < 0 || tagNum > 4294967295) {
1992
+ throw new Error(`XRP destination tag must be 0-4294967295. Got: ${memo}`);
1993
+ }
1994
+ desttag = tagNum.toString();
1447
1995
  }
1448
1996
  if (isMax) {
1449
1997
  amount = Number(accountInfo.Balance) - 1e6 - 1;
@@ -1452,6 +2000,22 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
1452
2000
  amount = amount * 1e6;
1453
2001
  amount = amount.toString();
1454
2002
  }
2003
+ const msg = {
2004
+ type: "ripple-sdk/MsgSend",
2005
+ value: {
2006
+ amount: [
2007
+ {
2008
+ amount,
2009
+ denom: "drop"
2010
+ }
2011
+ ],
2012
+ from_address: fromAddress,
2013
+ to_address: to
2014
+ }
2015
+ };
2016
+ if (desttag !== undefined) {
2017
+ msg.DestinationTag = desttag;
2018
+ }
1455
2019
  let tx = {
1456
2020
  type: "auth/StdTx",
1457
2021
  value: {
@@ -1465,36 +2029,24 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
1465
2029
  gas: "28000"
1466
2030
  },
1467
2031
  memo: memo || "",
1468
- msg: [
1469
- {
1470
- type: "ripple-sdk/MsgSend",
1471
- DestinationTag: desttag,
1472
- value: {
1473
- amount: [
1474
- {
1475
- amount,
1476
- denom: "drop"
1477
- }
1478
- ],
1479
- from_address: fromAddress,
1480
- to_address: to
1481
- }
1482
- }
1483
- ],
2032
+ msg: [msg],
1484
2033
  signatures: null
1485
2034
  }
1486
2035
  };
2036
+ const payment = {
2037
+ amount,
2038
+ destination: to
2039
+ };
2040
+ if (desttag !== undefined) {
2041
+ payment.destinationTag = desttag;
2042
+ }
1487
2043
  let unsignedTx = {
1488
2044
  addressNList: [2147483692, 2147483792, 2147483648, 0, 0],
1489
2045
  tx,
1490
2046
  flags: undefined,
1491
2047
  lastLedgerSequence: (ledgerIndexCurrent + 1000).toString(),
1492
2048
  sequence: sequence || "0",
1493
- payment: {
1494
- amount,
1495
- destination: to,
1496
- destinationTag: desttag
1497
- }
2049
+ payment
1498
2050
  };
1499
2051
  return unsignedTx;
1500
2052
  } catch (error) {
@@ -2769,6 +3321,10 @@ async function getFees(pioneer, networkId) {
2769
3321
  console.log(tag, "Using hardcoded fees for Cosmos network:", networkId);
2770
3322
  return getCosmosFees(networkId);
2771
3323
  }
3324
+ if (networkId === "ripple:4109c6f2045fc7eff4cde8f9905d19c2") {
3325
+ console.log(tag, "Using hardcoded fees for Ripple: 0.00001 XRP");
3326
+ return getRippleFees(networkId);
3327
+ }
2772
3328
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
2773
3329
  console.log(tag, "Using hardcoded fees for Dogecoin: 10 sat/byte");
2774
3330
  return {
@@ -3095,6 +3651,39 @@ function getCosmosFees(networkId) {
3095
3651
  raw: { hardcoded: true, base: feeConfig.base, unit: feeConfig.unit, denom: feeConfig.denom }
3096
3652
  };
3097
3653
  }
3654
+ function getRippleFees(networkId) {
3655
+ const networkName = getNetworkName(networkId);
3656
+ const standardFee = "0.00001";
3657
+ return {
3658
+ slow: {
3659
+ label: "Standard",
3660
+ value: standardFee,
3661
+ unit: "XRP",
3662
+ description: `Fixed fee for ${networkName}. XRP uses a deterministic fee model.`,
3663
+ estimatedTime: "~4 seconds",
3664
+ priority: "low"
3665
+ },
3666
+ average: {
3667
+ label: "Standard",
3668
+ value: standardFee,
3669
+ unit: "XRP",
3670
+ description: `Fixed fee for ${networkName}. XRP uses a deterministic fee model.`,
3671
+ estimatedTime: "~4 seconds",
3672
+ priority: "medium"
3673
+ },
3674
+ fastest: {
3675
+ label: "Standard",
3676
+ value: standardFee,
3677
+ unit: "XRP",
3678
+ description: `Fixed fee for ${networkName}. XRP uses a deterministic fee model.`,
3679
+ estimatedTime: "~4 seconds",
3680
+ priority: "high"
3681
+ },
3682
+ networkId,
3683
+ networkType: "RIPPLE",
3684
+ raw: { hardcoded: true, fee: standardFee, unit: "XRP" }
3685
+ };
3686
+ }
3098
3687
  function getFallbackFees(networkId) {
3099
3688
  const networkType = getNetworkType(networkId);
3100
3689
  const networkName = getNetworkName(networkId);
@@ -3493,7 +4082,7 @@ class SDK {
3493
4082
  this.appIcon = config.appIcon || "https://pioneers.dev/coins/keepkey.png";
3494
4083
  this.spec = spec || config.spec || "https://api.keepkey.info/spec/swagger";
3495
4084
  this.wss = config.wss || "wss://api.keepkey.info";
3496
- this.assets = import_pioneer_discovery.assetData;
4085
+ this.assets = import_pioneer_discovery2.assetData;
3497
4086
  this.assetsMap = new Map;
3498
4087
  this.username = config.username;
3499
4088
  this.queryKey = config.queryKey;
@@ -3544,9 +4133,9 @@ class SDK {
3544
4133
  fallbackToRemote: true
3545
4134
  }) : null;
3546
4135
  this.pairWallet = async (options) => {
3547
- const tag = TAG9 + " | pairWallet | ";
4136
+ const tag6 = TAG9 + " | pairWallet | ";
3548
4137
  if (this.viewOnlyMode || this.skipDevicePairing) {
3549
- console.log(tag, "\uD83D\uDC41️ [VIEW-ONLY] Skipping device pairing");
4138
+ console.log(tag6, "\uD83D\uDC41️ [VIEW-ONLY] Skipping device pairing");
3550
4139
  return {
3551
4140
  success: false,
3552
4141
  reason: "view-only-mode",
@@ -3587,7 +4176,7 @@ class SDK {
3587
4176
  return true;
3588
4177
  };
3589
4178
  this.setPubkeys = (newPubkeys) => {
3590
- const tag = `${TAG9} | setPubkeys | `;
4179
+ const tag6 = `${TAG9} | setPubkeys | `;
3591
4180
  this.pubkeys = [];
3592
4181
  this.pubkeySet.clear();
3593
4182
  let added = 0;
@@ -3613,7 +4202,7 @@ class SDK {
3613
4202
  return !!this.keepkeyEndpoint && this.keepkeyEndpoint.isAvailable;
3614
4203
  };
3615
4204
  this.getUnifiedPortfolio = async function() {
3616
- const tag = `${TAG9} | getUnifiedPortfolio | `;
4205
+ const tag6 = `${TAG9} | getUnifiedPortfolio | `;
3617
4206
  try {
3618
4207
  const startTime = performance.now();
3619
4208
  try {
@@ -3624,17 +4213,17 @@ class SDK {
3624
4213
  signal: AbortSignal.timeout(2000)
3625
4214
  });
3626
4215
  if (!portfolioResponse.ok) {
3627
- console.warn(tag, "Portfolio endpoint returned", portfolioResponse.status);
4216
+ console.warn(tag6, "Portfolio endpoint returned", portfolioResponse.status);
3628
4217
  return null;
3629
4218
  }
3630
4219
  const portfolioData = await portfolioResponse.json();
3631
4220
  const loadTime = performance.now() - startTime;
3632
4221
  if (!portfolioData.success) {
3633
- console.warn(tag, "Portfolio API returned success=false");
4222
+ console.warn(tag6, "Portfolio API returned success=false");
3634
4223
  return null;
3635
4224
  }
3636
4225
  if (portfolioData.totalValueUsd === 0 || !portfolioData.totalValueUsd) {
3637
- console.warn(tag, "Portfolio value is $0.00 - may need device connection or sync");
4226
+ console.warn(tag6, "Portfolio value is $0.00 - may need device connection or sync");
3638
4227
  return null;
3639
4228
  }
3640
4229
  let allBalances = [];
@@ -3721,14 +4310,14 @@ class SDK {
3721
4310
  };
3722
4311
  } catch (fetchError) {
3723
4312
  if (fetchError.name === "AbortError") {
3724
- console.log(tag, "Unified portfolio request timed out (this is normal if vault not running)");
4313
+ console.log(tag6, "Unified portfolio request timed out (this is normal if vault not running)");
3725
4314
  } else {
3726
- console.log(tag, "Failed to fetch unified portfolio:", fetchError.message);
4315
+ console.log(tag6, "Failed to fetch unified portfolio:", fetchError.message);
3727
4316
  }
3728
4317
  return null;
3729
4318
  }
3730
4319
  } catch (e) {
3731
- console.error(tag, "Error:", e);
4320
+ console.error(tag6, "Error:", e);
3732
4321
  return null;
3733
4322
  }
3734
4323
  };
@@ -3739,7 +4328,7 @@ class SDK {
3739
4328
  return this.syncState.isSynced;
3740
4329
  };
3741
4330
  this.init = async function(walletsVerbose, setup) {
3742
- const tag = `${TAG9} | init | `;
4331
+ const tag6 = `${TAG9} | init | `;
3743
4332
  try {
3744
4333
  if (!this.username)
3745
4334
  throw Error("username required!");
@@ -3804,11 +4393,11 @@ class SDK {
3804
4393
  this.events.emit("message", request);
3805
4394
  });
3806
4395
  clientEvents.events.on("balance:update", (data) => {
3807
- const tag2 = TAG9 + " | balance:update | ";
4396
+ const tag7 = TAG9 + " | balance:update | ";
3808
4397
  try {
3809
4398
  const payload = typeof data === "string" ? JSON.parse(data) : data;
3810
4399
  const balance = payload.balance;
3811
- console.log(tag2, "Received balance update:", balance.caip);
4400
+ console.log(tag7, "Received balance update:", balance.caip);
3812
4401
  const exists = this.balances.find((b) => b.caip === balance.caip && b.pubkey === balance.pubkey);
3813
4402
  if (!exists) {
3814
4403
  this.balances.push(balance);
@@ -3818,27 +4407,27 @@ class SDK {
3818
4407
  }
3819
4408
  this.events.emit("BALANCE_UPDATE", balance);
3820
4409
  } catch (e) {
3821
- console.error(tag2, "Error processing balance update:", e);
4410
+ console.error(tag7, "Error processing balance update:", e);
3822
4411
  }
3823
4412
  });
3824
4413
  clientEvents.events.on("sync:progress", (data) => {
3825
- const tag2 = TAG9 + " | sync:progress | ";
4414
+ const tag7 = TAG9 + " | sync:progress | ";
3826
4415
  try {
3827
4416
  const payload = typeof data === "string" ? JSON.parse(data) : data;
3828
- console.log(tag2, `Sync progress: ${payload.percentage}%`);
4417
+ console.log(tag7, `Sync progress: ${payload.percentage}%`);
3829
4418
  this.syncState.syncProgress = payload.percentage;
3830
4419
  this.syncState.syncedChains = payload.completed;
3831
4420
  this.syncState.totalChains = payload.total;
3832
4421
  this.events.emit("SYNC_PROGRESS", this.syncState);
3833
4422
  } catch (e) {
3834
- console.error(tag2, "Error processing sync progress:", e);
4423
+ console.error(tag7, "Error processing sync progress:", e);
3835
4424
  }
3836
4425
  });
3837
4426
  clientEvents.events.on("sync:complete", (data) => {
3838
- const tag2 = TAG9 + " | sync:complete | ";
4427
+ const tag7 = TAG9 + " | sync:complete | ";
3839
4428
  try {
3840
4429
  const payload = typeof data === "string" ? JSON.parse(data) : data;
3841
- console.log(tag2, `Sync complete: ${payload.balances} balances in ${payload.duration}ms`);
4430
+ console.log(tag7, `Sync complete: ${payload.balances} balances in ${payload.duration}ms`);
3842
4431
  this.syncState.isSynced = true;
3843
4432
  this.syncState.isInitialSync = false;
3844
4433
  this.syncState.syncProgress = 100;
@@ -3847,7 +4436,7 @@ class SDK {
3847
4436
  this.events.emit("SYNC_COMPLETE", this.syncState);
3848
4437
  this.events.emit("SYNC_STATE_CHANGED", this.syncState);
3849
4438
  } catch (e) {
3850
- console.error(tag2, "Error processing sync complete:", e);
4439
+ console.error(tag7, "Error processing sync complete:", e);
3851
4440
  }
3852
4441
  });
3853
4442
  this.events.emit("SET_STATUS", "init");
@@ -3879,18 +4468,27 @@ class SDK {
3879
4468
  }
3880
4469
  return this.pioneer;
3881
4470
  } catch (e) {
3882
- console.error(tag, "e: ", e);
4471
+ console.error(tag6, "e: ", e);
3883
4472
  throw e;
3884
4473
  }
3885
4474
  };
3886
4475
  this.buildDashboardFromBalances = function() {
3887
4476
  return buildDashboardFromBalances(this.balances, this.blockchains, this.assetsMap);
3888
4477
  };
4478
+ this.inferTypeFromCaip = function(caip) {
4479
+ if (caip.includes("/slip44:"))
4480
+ return "native";
4481
+ if (caip.includes("/erc20:") || caip.includes("/bep20:") || caip.includes("/spl:"))
4482
+ return "token";
4483
+ if (caip.includes("/denom:"))
4484
+ return "native";
4485
+ return "unknown";
4486
+ };
3889
4487
  this.syncMarket = async function() {
3890
4488
  return syncMarket(this.balances, this.pioneer);
3891
4489
  };
3892
4490
  this.sync = async function() {
3893
- const tag = `${TAG9} | sync | `;
4491
+ const tag6 = `${TAG9} | sync | `;
3894
4492
  try {
3895
4493
  const matchesNetwork = (item, networkId) => {
3896
4494
  if (!item.networks || !Array.isArray(item.networks))
@@ -3934,9 +4532,9 @@ class SDK {
3934
4532
  }
3935
4533
  }
3936
4534
  await this.getBalances();
3937
- console.log(tag, "Loading charts (tokens + portfolio)...");
4535
+ console.log(tag6, "Loading charts (tokens + portfolio)...");
3938
4536
  await this.getCharts();
3939
- console.log(tag, `Charts loaded. Total balances: ${this.balances.length}`);
4537
+ console.log(tag6, `Charts loaded. Total balances: ${this.balances.length}`);
3940
4538
  await this.syncMarket();
3941
4539
  const dashboardData = {
3942
4540
  networks: [],
@@ -4025,7 +4623,7 @@ class SDK {
4025
4623
  this.events.emit("SYNC_COMPLETE", this.syncState);
4026
4624
  return true;
4027
4625
  } catch (e) {
4028
- console.error(tag, "Error in sync:", e);
4626
+ console.error(tag6, "Error in sync:", e);
4029
4627
  throw e;
4030
4628
  }
4031
4629
  };
@@ -4039,7 +4637,7 @@ class SDK {
4039
4637
  }
4040
4638
  };
4041
4639
  this.buildTx = async function(sendPayload) {
4042
- let tag = TAG9 + " | buildTx | ";
4640
+ let tag6 = TAG9 + " | buildTx | ";
4043
4641
  try {
4044
4642
  const transactionDependencies = {
4045
4643
  context: this.context,
@@ -4053,7 +4651,7 @@ class SDK {
4053
4651
  };
4054
4652
  let txManager = new TransactionManager(transactionDependencies, this.events);
4055
4653
  let unsignedTx = await txManager.transfer(sendPayload);
4056
- console.log(tag, "unsignedTx: ", unsignedTx);
4654
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4057
4655
  return unsignedTx;
4058
4656
  } catch (e) {
4059
4657
  console.error(e);
@@ -4061,14 +4659,14 @@ class SDK {
4061
4659
  }
4062
4660
  };
4063
4661
  this.buildDelegateTx = async function(caip, params) {
4064
- let tag = TAG9 + " | buildDelegateTx | ";
4662
+ let tag6 = TAG9 + " | buildDelegateTx | ";
4065
4663
  try {
4066
4664
  const delegateParams = {
4067
4665
  ...params,
4068
4666
  type: "delegate"
4069
4667
  };
4070
4668
  let unsignedTx = await createUnsignedStakingTx(caip, delegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4071
- console.log(tag, "unsignedTx: ", unsignedTx);
4669
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4072
4670
  return unsignedTx;
4073
4671
  } catch (e) {
4074
4672
  console.error(e);
@@ -4076,14 +4674,14 @@ class SDK {
4076
4674
  }
4077
4675
  };
4078
4676
  this.buildUndelegateTx = async function(caip, params) {
4079
- let tag = TAG9 + " | buildUndelegateTx | ";
4677
+ let tag6 = TAG9 + " | buildUndelegateTx | ";
4080
4678
  try {
4081
4679
  const undelegateParams = {
4082
4680
  ...params,
4083
4681
  type: "undelegate"
4084
4682
  };
4085
4683
  let unsignedTx = await createUnsignedStakingTx(caip, undelegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4086
- console.log(tag, "unsignedTx: ", unsignedTx);
4684
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4087
4685
  return unsignedTx;
4088
4686
  } catch (e) {
4089
4687
  console.error(e);
@@ -4091,14 +4689,14 @@ class SDK {
4091
4689
  }
4092
4690
  };
4093
4691
  this.buildClaimRewardsTx = async function(caip, params) {
4094
- let tag = TAG9 + " | buildClaimRewardsTx | ";
4692
+ let tag6 = TAG9 + " | buildClaimRewardsTx | ";
4095
4693
  try {
4096
4694
  const claimParams = {
4097
4695
  ...params,
4098
4696
  type: "claim_rewards"
4099
4697
  };
4100
4698
  let unsignedTx = await createUnsignedStakingTx(caip, claimParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4101
- console.log(tag, "unsignedTx: ", unsignedTx);
4699
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4102
4700
  return unsignedTx;
4103
4701
  } catch (e) {
4104
4702
  console.error(e);
@@ -4106,7 +4704,7 @@ class SDK {
4106
4704
  }
4107
4705
  };
4108
4706
  this.buildClaimAllRewardsTx = async function(caip, params) {
4109
- let tag = TAG9 + " | buildClaimAllRewardsTx | ";
4707
+ let tag6 = TAG9 + " | buildClaimAllRewardsTx | ";
4110
4708
  try {
4111
4709
  const claimAllParams = {
4112
4710
  ...params,
@@ -4120,7 +4718,7 @@ class SDK {
4120
4718
  }
4121
4719
  };
4122
4720
  this.signTx = async function(caip, unsignedTx) {
4123
- let tag = TAG9 + " | signTx | ";
4721
+ let tag6 = TAG9 + " | signTx | ";
4124
4722
  try {
4125
4723
  const transactionDependencies = {
4126
4724
  context: this.context,
@@ -4141,7 +4739,7 @@ class SDK {
4141
4739
  }
4142
4740
  };
4143
4741
  this.broadcastTx = async function(caip, signedTx) {
4144
- let tag = TAG9 + " | broadcastTx | ";
4742
+ let tag6 = TAG9 + " | broadcastTx | ";
4145
4743
  try {
4146
4744
  const transactionDependencies = {
4147
4745
  context: this.context,
@@ -4165,7 +4763,7 @@ class SDK {
4165
4763
  }
4166
4764
  };
4167
4765
  this.swap = async function(swapPayload) {
4168
- let tag = `${TAG9} | swap | `;
4766
+ let tag6 = `${TAG9} | swap | `;
4169
4767
  try {
4170
4768
  if (!swapPayload)
4171
4769
  throw Error("swapPayload required!");
@@ -4214,15 +4812,15 @@ class SDK {
4214
4812
  throw new Error(`Cannot use max amount: no balance found for ${swapPayload.caipIn}`);
4215
4813
  }
4216
4814
  let totalBalance = 0;
4217
- console.log(tag, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4815
+ console.log(tag6, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4218
4816
  for (const balanceEntry of inputBalances) {
4219
4817
  const balance = parseFloat(balanceEntry.balance) || 0;
4220
4818
  totalBalance += balance;
4221
- console.log(tag, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4819
+ console.log(tag6, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4222
4820
  }
4223
4821
  this.assetContext.balance = totalBalance.toString();
4224
4822
  this.assetContext.valueUsd = (totalBalance * parseFloat(this.assetContext.priceUsd || "0")).toFixed(2);
4225
- console.log(tag, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4823
+ console.log(tag6, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4226
4824
  const feeReserves = {
4227
4825
  "bip122:000000000019d6689c085ae165831e93/slip44:0": 0.00005,
4228
4826
  "eip155:1/slip44:60": 0.001,
@@ -4233,7 +4831,7 @@ class SDK {
4233
4831
  };
4234
4832
  const reserve = feeReserves[swapPayload.caipIn] || 0.0001;
4235
4833
  inputAmount = Math.max(0, totalBalance - reserve);
4236
- console.log(tag, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4834
+ console.log(tag6, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4237
4835
  } else {
4238
4836
  inputAmount = typeof swapPayload.amount === "string" ? parseFloat(swapPayload.amount) : swapPayload.amount;
4239
4837
  if (isNaN(inputAmount) || inputAmount <= 0) {
@@ -4253,7 +4851,7 @@ class SDK {
4253
4851
  result = await this.pioneer.Quote(quote);
4254
4852
  result = result.data;
4255
4853
  } catch (e) {
4256
- console.error(tag, "Failed to get quote: ", e);
4854
+ console.error(tag6, "Failed to get quote: ", e);
4257
4855
  throw Error("Quote API failed for path: " + quote.sellAsset + " -> " + quote.buyAsset + ". Error: " + e);
4258
4856
  }
4259
4857
  if (!result || result.length === 0)
@@ -4280,16 +4878,16 @@ class SDK {
4280
4878
  if (tx.type === "deposit") {
4281
4879
  unsignedTx = await createUnsignedTendermintTx(caip, tx.type, tx.txParams.amount, tx.txParams.memo, this.pubkeys, this.pioneer, this.pubkeyContext, false, undefined);
4282
4880
  } else if (tx.type === "EVM" || tx.type === "evm") {
4283
- console.log(tag, "Building EVM swap transaction with createUnsignedEvmTx");
4881
+ console.log(tag6, "Building EVM swap transaction with createUnsignedEvmTx");
4284
4882
  unsignedTx = await createUnsignedEvmTx(caip, tx.txParams.recipientAddress, parseFloat(tx.txParams.amount), tx.txParams.memo, this.pubkeys, this.pioneer, this.pubkeyContext, false);
4285
- console.log(tag, "✅ Built complete EVM transaction:", {
4883
+ console.log(tag6, "✅ Built complete EVM transaction:", {
4286
4884
  to: unsignedTx.to,
4287
4885
  from: this.pubkeyContext?.address,
4288
4886
  value: unsignedTx.value,
4289
4887
  chainId: unsignedTx.chainId,
4290
4888
  hasData: !!unsignedTx.data
4291
4889
  });
4292
- console.log(tag, "\uD83D\uDEE1️ Running Tenderly simulation for EVM swap...");
4890
+ console.log(tag6, "\uD83D\uDEE1️ Running Tenderly simulation for EVM swap...");
4293
4891
  try {
4294
4892
  const insightResult = await this.pioneer.Insight({
4295
4893
  tx: unsignedTx,
@@ -4297,15 +4895,15 @@ class SDK {
4297
4895
  isThorchainSwap: tx.txParams.isThorchainSwap || false
4298
4896
  });
4299
4897
  const insight = insightResult.body;
4300
- console.log(tag, "Simulation result:", insight?.simulation);
4898
+ console.log(tag6, "Simulation result:", insight?.simulation);
4301
4899
  if (!insight || !insight.simulation) {
4302
- console.warn(tag, "⚠️ WARNING: Tenderly simulation unavailable - proceeding without validation");
4900
+ console.warn(tag6, "⚠️ WARNING: Tenderly simulation unavailable - proceeding without validation");
4303
4901
  } else if (!insight.simulation.success) {
4304
- console.warn(tag, `⚠️ WARNING: Swap simulation FAILED - ${insight.simulation.error || "Transaction may revert"}`);
4305
- console.warn(tag, "⚠️ Proceeding anyway - USE CAUTION");
4902
+ console.warn(tag6, `⚠️ WARNING: Swap simulation FAILED - ${insight.simulation.error || "Transaction may revert"}`);
4903
+ console.warn(tag6, "⚠️ Proceeding anyway - USE CAUTION");
4306
4904
  } else {
4307
4905
  if (tx.txParams.isThorchainSwap) {
4308
- console.log(tag, "\uD83D\uDD0D Verifying THORChain swap parameters...");
4906
+ console.log(tag6, "\uD83D\uDD0D Verifying THORChain swap parameters...");
4309
4907
  const method = insight.simulation.method;
4310
4908
  if (!method || !method.toLowerCase().includes("deposit")) {
4311
4909
  throw new Error(`❌ CRITICAL: Invalid THORChain swap method: ${method} - expected depositWithExpiry`);
@@ -4316,20 +4914,20 @@ class SDK {
4316
4914
  if (routerAddress.toLowerCase() === vaultAddress.toLowerCase()) {
4317
4915
  throw new Error(`❌ CRITICAL: Sending directly to vault ${vaultAddress} instead of router!`);
4318
4916
  }
4319
- console.log(tag, `✅ Router: ${routerAddress}`);
4320
- console.log(tag, `✅ Vault: ${vaultAddress}`);
4917
+ console.log(tag6, `✅ Router: ${routerAddress}`);
4918
+ console.log(tag6, `✅ Vault: ${vaultAddress}`);
4321
4919
  }
4322
4920
  if (insight.simulation.addresses && insight.simulation.addresses.length > 0) {
4323
- console.log(tag, `✅ Addresses involved: ${insight.simulation.addresses.length}`);
4921
+ console.log(tag6, `✅ Addresses involved: ${insight.simulation.addresses.length}`);
4324
4922
  } else {
4325
- console.log(tag, "⚠️ WARNING: No addresses detected in simulation");
4923
+ console.log(tag6, "⚠️ WARNING: No addresses detected in simulation");
4326
4924
  }
4327
4925
  }
4328
- console.log(tag, `✅ Simulation PASSED - Gas used: ${insight.simulation.gasUsed}`);
4329
- console.log(tag, `✅ Method: ${insight.simulation.method}`);
4926
+ console.log(tag6, `✅ Simulation PASSED - Gas used: ${insight.simulation.gasUsed}`);
4927
+ console.log(tag6, `✅ Method: ${insight.simulation.method}`);
4330
4928
  }
4331
4929
  } catch (e) {
4332
- console.error(tag, "❌ Simulation validation failed:", e.message);
4930
+ console.error(tag6, "❌ Simulation validation failed:", e.message);
4333
4931
  throw new Error(`Swap blocked by simulation failure: ${e.message}`);
4334
4932
  }
4335
4933
  } else {
@@ -4349,12 +4947,12 @@ class SDK {
4349
4947
  return unsignedTx;
4350
4948
  }
4351
4949
  } catch (e) {
4352
- console.error(tag, "Error: ", e);
4950
+ console.error(tag6, "Error: ", e);
4353
4951
  throw e;
4354
4952
  }
4355
4953
  };
4356
4954
  this.transfer = async function(sendPayload) {
4357
- let tag = `${TAG9} | transfer | `;
4955
+ let tag6 = `${TAG9} | transfer | `;
4358
4956
  try {
4359
4957
  if (!sendPayload)
4360
4958
  throw Error("sendPayload required!");
@@ -4388,15 +4986,15 @@ class SDK {
4388
4986
  return { txid, events: this.events };
4389
4987
  } catch (error) {
4390
4988
  if (error instanceof Error) {
4391
- console.error(tag, "An error occurred during the transfer process:", error.message);
4989
+ console.error(tag6, "An error occurred during the transfer process:", error.message);
4392
4990
  } else {
4393
- console.error(tag, "An unknown error occurred during the transfer process");
4991
+ console.error(tag6, "An unknown error occurred during the transfer process");
4394
4992
  }
4395
4993
  throw error;
4396
4994
  }
4397
4995
  };
4398
4996
  this.followTransaction = async function(caip, txid) {
4399
- let tag = " | followTransaction | ";
4997
+ let tag6 = " | followTransaction | ";
4400
4998
  try {
4401
4999
  const finalConfirmationBlocksByCaip = {
4402
5000
  dogecoin: 3,
@@ -4426,7 +5024,7 @@ class SDK {
4426
5024
  }
4427
5025
  }
4428
5026
  } catch (error) {
4429
- console.error(tag, "Error:", error);
5027
+ console.error(tag6, "Error:", error);
4430
5028
  }
4431
5029
  if (!isConfirmed) {
4432
5030
  await new Promise((resolve) => setTimeout(resolve, 8000));
@@ -4444,18 +5042,18 @@ class SDK {
4444
5042
  requiredConfirmations
4445
5043
  };
4446
5044
  } catch (error) {
4447
- console.error(tag, "Error:", error);
5045
+ console.error(tag6, "Error:", error);
4448
5046
  throw new Error("Failed to follow transaction");
4449
5047
  }
4450
5048
  };
4451
5049
  this.setBlockchains = async function(blockchains) {
4452
- const tag = `${TAG9} | setBlockchains | `;
5050
+ const tag6 = `${TAG9} | setBlockchains | `;
4453
5051
  try {
4454
5052
  if (!blockchains)
4455
5053
  throw Error("blockchains required!");
4456
5054
  const uniqueBlockchains = [...new Set(blockchains)];
4457
5055
  if (blockchains.length !== uniqueBlockchains.length) {
4458
- console.warn(tag, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
5056
+ console.warn(tag6, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
4459
5057
  }
4460
5058
  this.blockchains = uniqueBlockchains;
4461
5059
  this.events.emit("SET_BLOCKCHAINS", this.blockchains);
@@ -4465,12 +5063,12 @@ class SDK {
4465
5063
  }
4466
5064
  };
4467
5065
  this.addAsset = async function(caip, data) {
4468
- let tag = TAG9 + " | addAsset | ";
5066
+ let tag6 = TAG9 + " | addAsset | ";
4469
5067
  try {
4470
5068
  let success = false;
4471
5069
  if (!caip)
4472
5070
  throw new Error("caip required!");
4473
- let dataLocal = import_pioneer_discovery.assetData[caip];
5071
+ let dataLocal = import_pioneer_discovery2.assetData[caip];
4474
5072
  if (!dataLocal) {
4475
5073
  if (!data.networkId)
4476
5074
  throw new Error("networkId required! can not build asset");
@@ -4503,22 +5101,22 @@ class SDK {
4503
5101
  }
4504
5102
  };
4505
5103
  this.clearWalletState = async function() {
4506
- const tag = `${TAG9} | clearWalletState | `;
5104
+ const tag6 = `${TAG9} | clearWalletState | `;
4507
5105
  try {
4508
5106
  this.context = null;
4509
5107
  this.paths = [];
4510
5108
  this.blockchains = [];
4511
5109
  this.pubkeys = [];
4512
5110
  this.pubkeySet.clear();
4513
- console.log(tag, "Cleared wallet state including pubkeys and tracking set");
5111
+ console.log(tag6, "Cleared wallet state including pubkeys and tracking set");
4514
5112
  return true;
4515
5113
  } catch (e) {
4516
- console.error(tag, "e: ", e);
5114
+ console.error(tag6, "e: ", e);
4517
5115
  throw e;
4518
5116
  }
4519
5117
  };
4520
5118
  this.addPath = async function(path) {
4521
- const tag = `${TAG9} | addPath | `;
5119
+ const tag6 = `${TAG9} | addPath | `;
4522
5120
  try {
4523
5121
  this.paths.push(path);
4524
5122
  const pubkey = await getPubkey(path.networks[0], path, this.keepKeySdk, this.context);
@@ -4527,14 +5125,14 @@ class SDK {
4527
5125
  this.buildDashboardFromBalances();
4528
5126
  return { success: true, pubkey };
4529
5127
  } catch (e) {
4530
- console.error(tag, "Failed:", e);
5128
+ console.error(tag6, "Failed:", e);
4531
5129
  throw e;
4532
5130
  }
4533
5131
  };
4534
5132
  this.addPaths = async function(paths) {
4535
- const tag = `${TAG9} | addPaths | `;
5133
+ const tag6 = `${TAG9} | addPaths | `;
4536
5134
  try {
4537
- console.log(tag, `Adding ${paths.length} paths in batch mode...`);
5135
+ console.log(tag6, `Adding ${paths.length} paths in batch mode...`);
4538
5136
  this.paths.push(...paths);
4539
5137
  const newPubkeys = [];
4540
5138
  for (const path of paths) {
@@ -4543,10 +5141,10 @@ class SDK {
4543
5141
  this.addPubkey(pubkey);
4544
5142
  newPubkeys.push(pubkey);
4545
5143
  } catch (error) {
4546
- console.warn(tag, `Failed to get pubkey for path ${path.note}:`, error.message);
5144
+ console.warn(tag6, `Failed to get pubkey for path ${path.note}:`, error.message);
4547
5145
  }
4548
5146
  }
4549
- console.log(tag, `Successfully added ${newPubkeys.length} pubkeys`);
5147
+ console.log(tag6, `Successfully added ${newPubkeys.length} pubkeys`);
4550
5148
  const networkSet = new Set;
4551
5149
  for (const path of paths) {
4552
5150
  if (path.networks && Array.isArray(path.networks)) {
@@ -4554,13 +5152,13 @@ class SDK {
4554
5152
  }
4555
5153
  }
4556
5154
  const uniqueNetworks = [...networkSet];
4557
- console.log(tag, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
5155
+ console.log(tag6, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
4558
5156
  await this.getBalancesForNetworks(uniqueNetworks);
4559
5157
  this.buildDashboardFromBalances();
4560
- console.log(tag, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
5158
+ console.log(tag6, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
4561
5159
  return { success: true, pubkeys: newPubkeys };
4562
5160
  } catch (e) {
4563
- console.error(tag, "Failed:", e);
5161
+ console.error(tag6, "Failed:", e);
4564
5162
  throw e;
4565
5163
  }
4566
5164
  };
@@ -4568,12 +5166,12 @@ class SDK {
4568
5166
  return this.getGasAssets();
4569
5167
  };
4570
5168
  this.getGasAssets = async function() {
4571
- const tag = `${TAG9} | getGasAssets | `;
5169
+ const tag6 = `${TAG9} | getGasAssets | `;
4572
5170
  try {
4573
5171
  for (let i = 0;i < this.blockchains.length; i++) {
4574
5172
  let networkId = this.blockchains[i];
4575
5173
  let caip = import_pioneer_caip8.networkIdToCaip(networkId);
4576
- let asset = await import_pioneer_discovery.assetData[caip.toLowerCase()];
5174
+ let asset = await import_pioneer_discovery2.assetData[caip.toLowerCase()];
4577
5175
  if (asset) {
4578
5176
  asset.caip = caip.toLowerCase();
4579
5177
  asset.networkId = networkId;
@@ -4602,7 +5200,7 @@ class SDK {
4602
5200
  denom: "maya"
4603
5201
  };
4604
5202
  this.assetsMap.set(mayaTokenCaip, mayaToken);
4605
- console.log(tag, "Added MAYA token to assetsMap");
5203
+ console.log(tag6, "Added MAYA token to assetsMap");
4606
5204
  }
4607
5205
  return this.assetsMap;
4608
5206
  } catch (e) {
@@ -4611,7 +5209,7 @@ class SDK {
4611
5209
  }
4612
5210
  };
4613
5211
  this.getPubkeys = async function() {
4614
- const tag = `${TAG9} | getPubkeys | `;
5212
+ const tag6 = `${TAG9} | getPubkeys | `;
4615
5213
  try {
4616
5214
  if (this.paths.length === 0)
4617
5215
  throw new Error("No paths found!");
@@ -4625,43 +5223,46 @@ class SDK {
4625
5223
  }
4626
5224
  const pubkeysWithoutNetworks = this.pubkeys.filter((pk) => !pk.networks || !Array.isArray(pk.networks) || pk.networks.length === 0);
4627
5225
  if (pubkeysWithoutNetworks.length > 0) {
4628
- console.error(tag, "ERROR: Some pubkeys missing networks field!");
4629
- console.error(tag, "Affected pubkeys:", pubkeysWithoutNetworks.length);
5226
+ console.error(tag6, "ERROR: Some pubkeys missing networks field!");
5227
+ console.error(tag6, "Affected pubkeys:", pubkeysWithoutNetworks.length);
4630
5228
  pubkeysWithoutNetworks.forEach((pk) => {
4631
- console.error(tag, ` - ${pk.note || pk.pubkey}: networks=${pk.networks}`);
5229
+ console.error(tag6, ` - ${pk.note || pk.pubkey}: networks=${pk.networks}`);
4632
5230
  });
4633
5231
  for (const pubkey of pubkeysWithoutNetworks) {
4634
5232
  const matchingPath = this.paths.find((p) => JSON.stringify(p.addressNList) === JSON.stringify(pubkey.addressNList));
4635
5233
  if (matchingPath && matchingPath.networks) {
4636
- console.warn(tag, ` ⚠️ Auto-fixing: Adding networks from path ${matchingPath.note}`);
5234
+ console.warn(tag6, ` ⚠️ Auto-fixing: Adding networks from path ${matchingPath.note}`);
4637
5235
  pubkey.networks = matchingPath.networks;
4638
5236
  }
4639
5237
  }
4640
5238
  const stillMissing = this.pubkeys.filter((pk) => !pk.networks || !Array.isArray(pk.networks) || pk.networks.length === 0);
4641
5239
  if (stillMissing.length > 0) {
4642
- console.error(tag, `❌ CRITICAL: ${stillMissing.length} pubkeys still missing networks after auto-fix!`);
5240
+ console.error(tag6, `❌ CRITICAL: ${stillMissing.length} pubkeys still missing networks after auto-fix!`);
4643
5241
  stillMissing.forEach((pk) => {
4644
- console.error(tag, ` - ${pk.note || pk.pubkey}`);
5242
+ console.error(tag6, ` - ${pk.note || pk.pubkey}`);
4645
5243
  });
4646
5244
  } else {
4647
- console.log(tag, `✅ Auto-fix successful: All pubkeys now have networks field`);
5245
+ console.log(tag6, `✅ Auto-fix successful: All pubkeys now have networks field`);
4648
5246
  }
4649
5247
  }
4650
5248
  this.events.emit("SET_PUBKEYS", this.pubkeys);
4651
5249
  return pubkeys;
4652
5250
  } catch (error) {
4653
5251
  console.error("Error in getPubkeys:", error);
4654
- console.error(tag, "Error in getPubkeys:", error);
5252
+ console.error(tag6, "Error in getPubkeys:", error);
4655
5253
  throw error;
4656
5254
  }
4657
5255
  };
4658
- this.getBalancesForNetworks = async function(networkIds) {
4659
- const tag = `${TAG9} | getBalancesForNetworks | `;
5256
+ this.getBalancesForNetworks = async function(networkIds, forceRefresh) {
5257
+ const tag6 = `${TAG9} | getBalancesForNetworks | `;
4660
5258
  try {
4661
5259
  if (!this.pioneer) {
4662
- console.error(tag, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
5260
+ console.error(tag6, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
4663
5261
  throw new Error("Pioneer client not initialized. Call init() first.");
4664
5262
  }
5263
+ if (forceRefresh) {
5264
+ console.log(tag6, "\uD83D\uDD04 Force refresh requested - bypassing balance cache");
5265
+ }
4665
5266
  console.log("\uD83D\uDD0D [DIAGNOSTIC] Input networks:", networkIds);
4666
5267
  console.log("\uD83D\uDD0D [DIAGNOSTIC] Total pubkeys:", this.pubkeys.length);
4667
5268
  const pubkeysWithNetworks = this.pubkeys.filter((p) => p.networks && Array.isArray(p.networks));
@@ -4687,20 +5288,20 @@ class SDK {
4687
5288
  return network === adjustedNetworkId;
4688
5289
  }));
4689
5290
  if (pubkeys.length === 0) {
4690
- console.warn(tag, `⚠️ No pubkeys found for ${networkId} with networks field`);
4691
- console.warn(tag, "Attempting fallback: finding pubkeys by path matching");
5291
+ console.warn(tag6, `⚠️ No pubkeys found for ${networkId} with networks field`);
5292
+ console.warn(tag6, "Attempting fallback: finding pubkeys by path matching");
4692
5293
  const pathsForNetwork = this.paths.filter((p) => p.networks?.includes(networkId) || networkId.startsWith("eip155:") && p.networks?.includes("eip155:*"));
4693
5294
  for (const path of pathsForNetwork) {
4694
5295
  const matchingPubkey = this.pubkeys.find((pk) => JSON.stringify(pk.addressNList) === JSON.stringify(path.addressNList));
4695
5296
  if (matchingPubkey) {
4696
- console.warn(tag, ` ✓ Found pubkey via path matching: ${matchingPubkey.note || matchingPubkey.pubkey.slice(0, 10)}`);
5297
+ console.warn(tag6, ` ✓ Found pubkey via path matching: ${matchingPubkey.note || matchingPubkey.pubkey.slice(0, 10)}`);
4697
5298
  pubkeys.push(matchingPubkey);
4698
5299
  }
4699
5300
  }
4700
5301
  if (pubkeys.length > 0) {
4701
- console.warn(tag, ` ✅ Fallback successful: Found ${pubkeys.length} pubkeys for ${networkId}`);
5302
+ console.warn(tag6, ` ✅ Fallback successful: Found ${pubkeys.length} pubkeys for ${networkId}`);
4702
5303
  } else {
4703
- console.error(tag, ` ❌ Fallback failed: No pubkeys found for ${networkId}`);
5304
+ console.error(tag6, ` ❌ Fallback failed: No pubkeys found for ${networkId}`);
4704
5305
  }
4705
5306
  }
4706
5307
  const caipNative = await import_pioneer_caip8.networkIdToCaip(networkId);
@@ -4722,7 +5323,7 @@ class SDK {
4722
5323
  const apiCallStart = performance.now();
4723
5324
  console.time("GetPortfolioBalances Response Time");
4724
5325
  try {
4725
- let marketInfo = await this.pioneer.GetPortfolioBalances({ pubkeys: assetQuery });
5326
+ let marketInfo = await this.pioneer.GetPortfolioBalances({ pubkeys: assetQuery }, forceRefresh ? { forceRefresh: true } : undefined);
4726
5327
  const apiCallTime = performance.now() - apiCallStart;
4727
5328
  console.timeEnd("GetPortfolioBalances Response Time");
4728
5329
  console.log(`⏱️ [PERF] API call completed in ${apiCallTime.toFixed(0)}ms`);
@@ -4732,10 +5333,23 @@ class SDK {
4732
5333
  console.log(`⏱️ [PERF] Starting balance enrichment...`);
4733
5334
  for (let balance of balances) {
4734
5335
  const assetInfo = this.assetsMap.get(balance.caip.toLowerCase()) || this.assetsMap.get(balance.caip);
4735
- if (!assetInfo)
5336
+ if (!assetInfo) {
5337
+ console.warn(`⚠️ [ENRICHMENT] Asset metadata missing for ${balance.caip}, using fallback enrichment`);
5338
+ const inferredType = this.inferTypeFromCaip(balance.caip);
5339
+ Object.assign(balance, {
5340
+ type: balance.type || inferredType,
5341
+ isNative: balance.isNative ?? inferredType === "native",
5342
+ networkId: import_pioneer_caip8.caipToNetworkId(balance.caip),
5343
+ icon: "https://pioneers.dev/coins/unknown.png",
5344
+ identifier: `${balance.caip}:${balance.pubkey}`,
5345
+ updated: Date.now()
5346
+ });
4736
5347
  continue;
5348
+ }
4737
5349
  const color = ASSET_COLORS[balance.caip] || assetInfo.color;
4738
5350
  Object.assign(balance, assetInfo, {
5351
+ type: balance.type || assetInfo.type,
5352
+ isNative: balance.isNative ?? assetInfo.isNative,
4739
5353
  networkId: import_pioneer_caip8.caipToNetworkId(balance.caip),
4740
5354
  icon: assetInfo.icon || "https://pioneers.dev/coins/etherum.png",
4741
5355
  identifier: `${balance.caip}:${balance.pubkey}`,
@@ -4757,43 +5371,43 @@ class SDK {
4757
5371
  console.log(`⏱️ [PERF] Total getBalancesForNetworks: ${(performance.now() - apiCallStart).toFixed(0)}ms`);
4758
5372
  return this.balances;
4759
5373
  } catch (apiError) {
4760
- console.error(tag, "GetPortfolioBalances API call failed:", apiError);
5374
+ console.error(tag6, "GetPortfolioBalances API call failed:", apiError);
4761
5375
  throw new Error(`GetPortfolioBalances API call failed: ${apiError?.message || "Unknown error"}`);
4762
5376
  }
4763
5377
  } catch (e) {
4764
- console.error(tag, "Error: ", e);
5378
+ console.error(tag6, "Error: ", e);
4765
5379
  throw e;
4766
5380
  }
4767
5381
  };
4768
- this.getBalances = async function() {
4769
- const tag = `${TAG9} | getBalances | `;
5382
+ this.getBalances = async function(forceRefresh) {
5383
+ const tag6 = `${TAG9} | getBalances | `;
4770
5384
  try {
4771
- return await this.getBalancesForNetworks(this.blockchains);
5385
+ return await this.getBalancesForNetworks(this.blockchains, forceRefresh);
4772
5386
  } catch (e) {
4773
- console.error(tag, "Error in getBalances: ", e);
5387
+ console.error(tag6, "Error in getBalances: ", e);
4774
5388
  throw e;
4775
5389
  }
4776
5390
  };
4777
5391
  this.getBalance = async function(networkId) {
4778
- const tag = `${TAG9} | getBalance | `;
5392
+ const tag6 = `${TAG9} | getBalance | `;
4779
5393
  try {
4780
5394
  const results = await this.getBalancesForNetworks([networkId]);
4781
5395
  const filtered = results.filter(async (b) => b.networkId === await import_pioneer_caip8.networkIdToCaip(networkId));
4782
5396
  return filtered;
4783
5397
  } catch (e) {
4784
- console.error(tag, "Error: ", e);
5398
+ console.error(tag6, "Error: ", e);
4785
5399
  throw e;
4786
5400
  }
4787
5401
  };
4788
5402
  this.getFees = async function(networkId) {
4789
- const tag = `${TAG9} | getFees | `;
5403
+ const tag6 = `${TAG9} | getFees | `;
4790
5404
  try {
4791
5405
  if (!this.pioneer) {
4792
5406
  throw new Error("Pioneer client not initialized. Call init() first.");
4793
5407
  }
4794
5408
  return await getFees(this.pioneer, networkId);
4795
5409
  } catch (e) {
4796
- console.error(tag, "Error getting fees: ", e);
5410
+ console.error(tag6, "Error getting fees: ", e);
4797
5411
  throw e;
4798
5412
  }
4799
5413
  };
@@ -4801,42 +5415,12 @@ class SDK {
4801
5415
  return estimateTransactionFee(feeRate, unit, networkType, txSize);
4802
5416
  };
4803
5417
  this.getCharts = async function() {
4804
- const tag = `${TAG9} | getCharts | `;
5418
+ const tag6 = `${TAG9} | getCharts | `;
4805
5419
  try {
4806
- console.log(tag, "Fetching charts from batch endpoint");
4807
- const pubkeysForBatch = [];
4808
- for (const pubkey of this.pubkeys) {
4809
- const address = pubkey.address || pubkey.master || pubkey.pubkey;
4810
- if (!address)
4811
- continue;
4812
- const supportedNetworks = pubkey.networks || [];
4813
- for (const blockchain of this.blockchains) {
4814
- const supportsNetwork = supportedNetworks.some((net) => net === blockchain || net.endsWith(":*") && blockchain.startsWith(net.replace(":*", ":")));
4815
- if (supportsNetwork) {
4816
- let caip;
4817
- if (blockchain.startsWith("eip155:")) {
4818
- caip = `${blockchain}/slip44:60`;
4819
- } else {
4820
- caip = `${blockchain}/slip44:0`;
4821
- }
4822
- pubkeysForBatch.push({
4823
- pubkey: address,
4824
- caip
4825
- });
4826
- }
4827
- }
4828
- }
4829
- console.log(tag, `Calling batch GetCharts with ${pubkeysForBatch.length} pubkeys`);
4830
- let newBalances = [];
4831
- try {
4832
- const chartsResponse = await this.pioneer.GetCharts({
4833
- pubkeys: pubkeysForBatch
4834
- });
4835
- newBalances = chartsResponse?.data?.balances || [];
4836
- console.log(tag, `Received ${newBalances.length} balances from batch endpoint`);
4837
- } catch (chartsError) {
4838
- console.warn(tag, `GetCharts API not available (${chartsError.message}), continuing without charts data`);
4839
- }
5420
+ console.log(tag6, "Fetching charts (portfolio + tokens + staking)...");
5421
+ const { getCharts: getChartsModular } = await Promise.resolve().then(() => (init_charts(), exports_charts));
5422
+ const newBalances = await getChartsModular(this.blockchains, this.pioneer, this.pubkeys, this.context);
5423
+ console.log(tag6, `Modular charts returned ${newBalances.length} balances (native + tokens + staking)`);
4840
5424
  const uniqueBalances = new Map([...this.balances, ...newBalances].map((balance) => [
4841
5425
  balance.identifier || `${balance.caip}:${balance.pubkey}`,
4842
5426
  {
@@ -4844,17 +5428,19 @@ class SDK {
4844
5428
  type: balance.type || "balance"
4845
5429
  }
4846
5430
  ]));
4847
- console.log(tag, "uniqueBalances: ", uniqueBalances.size);
5431
+ console.log(tag6, "Deduplicated to:", uniqueBalances.size, "unique balances");
4848
5432
  this.balances = Array.from(uniqueBalances.values());
4849
- console.log(tag, "Updated this.balances: ", this.balances.length);
5433
+ const tokens = this.balances.filter((b) => b.token === true);
5434
+ const native = this.balances.filter((b) => b.token !== true);
5435
+ console.log(tag6, `Balance breakdown: ${native.length} native + ${tokens.length} tokens = ${this.balances.length} total`);
4850
5436
  return this.balances;
4851
5437
  } catch (e) {
4852
- console.error(tag, "Error in getCharts:", e);
5438
+ console.error(tag6, "Error in getCharts:", e);
4853
5439
  throw e;
4854
5440
  }
4855
5441
  };
4856
5442
  this.setContext = async (context) => {
4857
- const tag = `${TAG9} | setContext | `;
5443
+ const tag6 = `${TAG9} | setContext | `;
4858
5444
  try {
4859
5445
  if (!context)
4860
5446
  throw Error("context required!");
@@ -4862,12 +5448,12 @@ class SDK {
4862
5448
  this.events.emit("SET_CONTEXT", context);
4863
5449
  return { success: true };
4864
5450
  } catch (e) {
4865
- console.error(tag, "e: ", e);
5451
+ console.error(tag6, "e: ", e);
4866
5452
  return { success: false };
4867
5453
  }
4868
5454
  };
4869
5455
  this.setContextType = async (contextType) => {
4870
- const tag = `${TAG9} | setContextType | `;
5456
+ const tag6 = `${TAG9} | setContextType | `;
4871
5457
  try {
4872
5458
  if (!contextType)
4873
5459
  throw Error("contextType required!");
@@ -4875,22 +5461,27 @@ class SDK {
4875
5461
  this.events.emit("SET_CONTEXT_TYPE", contextType);
4876
5462
  return { success: true };
4877
5463
  } catch (e) {
4878
- console.error(tag, "e: ", e);
5464
+ console.error(tag6, "e: ", e);
4879
5465
  return { success: false };
4880
5466
  }
4881
5467
  };
4882
- this.refresh = async () => {
4883
- const tag = `${TAG9} | refresh | `;
5468
+ this.refresh = async (forceRefresh) => {
5469
+ const tag6 = `${TAG9} | refresh | `;
4884
5470
  try {
4885
- await this.sync();
5471
+ if (forceRefresh) {
5472
+ console.log(tag6, "\uD83D\uDD04 Force refresh - fetching fresh balances from blockchain");
5473
+ await this.getBalances(true);
5474
+ } else {
5475
+ await this.sync();
5476
+ }
4886
5477
  return this.balances;
4887
5478
  } catch (e) {
4888
- console.error(tag, "e: ", e);
5479
+ console.error(tag6, "e: ", e);
4889
5480
  throw e;
4890
5481
  }
4891
5482
  };
4892
5483
  this.setAssetContext = async function(asset) {
4893
- const tag = `${TAG9} | setAssetContext | `;
5484
+ const tag6 = `${TAG9} | setAssetContext | `;
4894
5485
  try {
4895
5486
  if (!asset) {
4896
5487
  this.assetContext = null;
@@ -4902,7 +5493,7 @@ class SDK {
4902
5493
  asset.networkId = import_pioneer_caip8.caipToNetworkId(asset.caip);
4903
5494
  if (!this.pubkeys || this.pubkeys.length === 0) {
4904
5495
  const errorMsg = `Cannot set asset context for ${asset.caip} - no pubkeys loaded. Please initialize wallet first.`;
4905
- console.error(tag, errorMsg);
5496
+ console.error(tag6, errorMsg);
4906
5497
  throw new Error(errorMsg);
4907
5498
  }
4908
5499
  const pubkeysForNetwork = this.pubkeys.filter((e) => {
@@ -4917,8 +5508,8 @@ class SDK {
4917
5508
  });
4918
5509
  if (pubkeysForNetwork.length === 0) {
4919
5510
  const errorMsg = `Cannot set asset context for ${asset.caip} - no address/xpub found for network ${asset.networkId}`;
4920
- console.error(tag, errorMsg);
4921
- console.error(tag, "Available networks in pubkeys:", [
5511
+ console.error(tag6, errorMsg);
5512
+ console.error(tag6, "Available networks in pubkeys:", [
4922
5513
  ...new Set(this.pubkeys.flatMap((p) => p.networks || []))
4923
5514
  ]);
4924
5515
  throw new Error(errorMsg);
@@ -4928,43 +5519,43 @@ class SDK {
4928
5519
  const xpubFound = pubkeysForNetwork.some((p) => p.type === "xpub" && p.pubkey);
4929
5520
  if (!xpubFound) {
4930
5521
  const errorMsg = `Cannot set asset context for UTXO chain ${asset.caip} - xpub required but not found`;
4931
- console.error(tag, errorMsg);
5522
+ console.error(tag6, errorMsg);
4932
5523
  throw new Error(errorMsg);
4933
5524
  }
4934
5525
  }
4935
5526
  const hasValidAddress = pubkeysForNetwork.some((p) => p.address || p.master || p.pubkey);
4936
5527
  if (!hasValidAddress) {
4937
5528
  const errorMsg = `Cannot set asset context for ${asset.caip} - no valid address found in pubkeys`;
4938
- console.error(tag, errorMsg);
5529
+ console.error(tag6, errorMsg);
4939
5530
  throw new Error(errorMsg);
4940
5531
  }
4941
- console.log(tag, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5532
+ console.log(tag6, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
4942
5533
  let freshPriceUsd = 0;
4943
5534
  try {
4944
5535
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
4945
- console.warn(tag, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5536
+ console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
4946
5537
  } else {
4947
- console.log(tag, "Fetching fresh market price for:", asset.caip);
5538
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
4948
5539
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
4949
- console.log(tag, "Market data response:", marketData);
5540
+ console.log(tag6, "Market data response:", marketData);
4950
5541
  if (marketData && marketData.data && marketData.data.length > 0) {
4951
5542
  freshPriceUsd = marketData.data[0];
4952
- console.log(tag, "✅ Fresh market price:", freshPriceUsd);
5543
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
4953
5544
  } else {
4954
- console.warn(tag, "No market data returned for:", asset.caip);
5545
+ console.warn(tag6, "No market data returned for:", asset.caip);
4955
5546
  }
4956
5547
  }
4957
5548
  } catch (marketError) {
4958
- console.error(tag, "Error fetching market price:", marketError);
5549
+ console.error(tag6, "Error fetching market price:", marketError);
4959
5550
  }
4960
5551
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
4961
- console.log(tag, "assetInfo: ", assetInfo);
4962
- let assetInfoDiscovery = import_pioneer_discovery.assetData[asset.caip];
4963
- console.log(tag, "assetInfoDiscovery: ", assetInfoDiscovery);
5552
+ console.log(tag6, "assetInfo: ", assetInfo);
5553
+ let assetInfoDiscovery = import_pioneer_discovery2.assetData[asset.caip];
5554
+ console.log(tag6, "assetInfoDiscovery: ", assetInfoDiscovery);
4964
5555
  if (assetInfoDiscovery)
4965
5556
  assetInfo = assetInfoDiscovery;
4966
5557
  if (!assetInfo) {
4967
- console.log(tag, "Building placeholder asset!");
5558
+ console.log(tag6, "Building placeholder asset!");
4968
5559
  assetInfo = {
4969
5560
  caip: asset.caip.toLowerCase(),
4970
5561
  networkId: asset.networkId,
@@ -4981,30 +5572,30 @@ class SDK {
4981
5572
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
4982
5573
  if (balance > 0 && valueUsd > 0) {
4983
5574
  priceValue = valueUsd / balance;
4984
- console.log(tag, "calculated priceUsd from valueUsd/balance:", priceValue);
5575
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
4985
5576
  }
4986
5577
  }
4987
5578
  if (priceValue && priceValue > 0) {
4988
- console.log(tag, "detected priceUsd from balance:", priceValue);
5579
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
4989
5580
  assetInfo.priceUsd = priceValue;
4990
5581
  }
4991
5582
  }
4992
5583
  if (freshPriceUsd && freshPriceUsd > 0) {
4993
5584
  assetInfo.priceUsd = freshPriceUsd;
4994
- console.log(tag, "✅ Using fresh market price:", freshPriceUsd);
5585
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
4995
5586
  let totalBalance = 0;
4996
5587
  let totalValueUsd = 0;
4997
- console.log(tag, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5588
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
4998
5589
  for (const balanceEntry of matchingBalances) {
4999
5590
  const balance = parseFloat(balanceEntry.balance) || 0;
5000
5591
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5001
5592
  totalBalance += balance;
5002
5593
  totalValueUsd += valueUsd;
5003
- console.log(tag, ` Balance entry: ${balance} (${valueUsd} USD)`);
5594
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5004
5595
  }
5005
5596
  assetInfo.balance = totalBalance.toString();
5006
5597
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5007
- console.log(tag, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5598
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5008
5599
  }
5009
5600
  const assetBalances = this.balances.filter((b) => b.caip === asset.caip);
5010
5601
  const assetPubkeys = this.pubkeys.filter((p) => p.networks && Array.isArray(p.networks) && p.networks.includes(import_pioneer_caip8.caipToNetworkId(asset.caip)) || import_pioneer_caip8.caipToNetworkId(asset.caip).includes("eip155") && p.networks && Array.isArray(p.networks) && p.networks.some((n) => n.startsWith("eip155")));
@@ -5024,7 +5615,7 @@ class SDK {
5024
5615
  const balanceAmount = parseFloat(balance.balance || 0);
5025
5616
  balance.valueUsd = (balanceAmount * freshPriceUsd).toString();
5026
5617
  }
5027
- console.log(tag, "Updated all balances with fresh price data");
5618
+ console.log(tag6, "Updated all balances with fresh price data");
5028
5619
  }
5029
5620
  this.assetContext = finalAssetContext;
5030
5621
  if (asset.isToken || asset.type === "token" || assetInfo.isToken || assetInfo.type === "token") {
@@ -5076,20 +5667,20 @@ class SDK {
5076
5667
  const currentContextValid = this.pubkeyContext?.networks?.includes(networkId);
5077
5668
  if (!this.pubkeyContext || !currentContextValid) {
5078
5669
  this.pubkeyContext = assetPubkeys[0];
5079
- console.log(tag, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5670
+ console.log(tag6, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5080
5671
  } else {
5081
- console.log(tag, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5672
+ console.log(tag6, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5082
5673
  }
5083
5674
  }
5084
5675
  this.events.emit("SET_ASSET_CONTEXT", this.assetContext);
5085
5676
  return this.assetContext;
5086
5677
  } catch (e) {
5087
- console.error(tag, "e: ", e);
5678
+ console.error(tag6, "e: ", e);
5088
5679
  throw e;
5089
5680
  }
5090
5681
  };
5091
5682
  this.setPubkeyContext = async function(pubkey) {
5092
- let tag = `${TAG9} | setPubkeyContext | `;
5683
+ let tag6 = `${TAG9} | setPubkeyContext | `;
5093
5684
  try {
5094
5685
  if (!pubkey)
5095
5686
  throw Error("pubkey is required");
@@ -5097,31 +5688,31 @@ class SDK {
5097
5688
  throw Error("invalid pubkey: missing pubkey or address");
5098
5689
  const exists = this.pubkeys.some((pk) => pk.pubkey === pubkey.pubkey || pk.address === pubkey.address || pk.pubkey === pubkey.address);
5099
5690
  if (!exists) {
5100
- console.warn(tag, "Pubkey not found in current pubkeys array");
5691
+ console.warn(tag6, "Pubkey not found in current pubkeys array");
5101
5692
  }
5102
5693
  this.pubkeyContext = pubkey;
5103
- console.log(tag, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5694
+ console.log(tag6, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5104
5695
  return true;
5105
5696
  } catch (e) {
5106
- console.error(tag, "e: ", e);
5697
+ console.error(tag6, "e: ", e);
5107
5698
  throw e;
5108
5699
  }
5109
5700
  };
5110
5701
  this.setOutboundAssetContext = async function(asset) {
5111
- const tag = `${TAG9} | setOutputAssetContext | `;
5702
+ const tag6 = `${TAG9} | setOutputAssetContext | `;
5112
5703
  try {
5113
- console.log(tag, "0. asset: ", asset);
5704
+ console.log(tag6, "0. asset: ", asset);
5114
5705
  if (!asset) {
5115
5706
  this.outboundAssetContext = null;
5116
5707
  return;
5117
5708
  }
5118
- console.log(tag, "1 asset: ", asset);
5709
+ console.log(tag6, "1 asset: ", asset);
5119
5710
  if (!asset.caip)
5120
5711
  throw Error("Invalid Asset! missing caip!");
5121
5712
  if (!asset.networkId)
5122
5713
  asset.networkId = import_pioneer_caip8.caipToNetworkId(asset.caip);
5123
- console.log(tag, "networkId: ", asset.networkId);
5124
- console.log(tag, "this.pubkeys: ", this.pubkeys);
5714
+ console.log(tag6, "networkId: ", asset.networkId);
5715
+ console.log(tag6, "this.pubkeys: ", this.pubkeys);
5125
5716
  const pubkey = this.pubkeys.find((p) => {
5126
5717
  if (!p.networks || !Array.isArray(p.networks))
5127
5718
  return false;
@@ -5136,23 +5727,23 @@ class SDK {
5136
5727
  let freshPriceUsd = 0;
5137
5728
  try {
5138
5729
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5139
- console.warn(tag, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5730
+ console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5140
5731
  } else {
5141
- console.log(tag, "Fetching fresh market price for:", asset.caip);
5732
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
5142
5733
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5143
- console.log(tag, "Market data response:", marketData);
5734
+ console.log(tag6, "Market data response:", marketData);
5144
5735
  if (marketData && marketData.data && marketData.data.length > 0) {
5145
5736
  freshPriceUsd = marketData.data[0];
5146
- console.log(tag, "✅ Fresh market price:", freshPriceUsd);
5737
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5147
5738
  } else {
5148
- console.warn(tag, "No market data returned for:", asset.caip);
5739
+ console.warn(tag6, "No market data returned for:", asset.caip);
5149
5740
  }
5150
5741
  }
5151
5742
  } catch (marketError) {
5152
- console.error(tag, "Error fetching market price:", marketError);
5743
+ console.error(tag6, "Error fetching market price:", marketError);
5153
5744
  }
5154
5745
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5155
- console.log(tag, "assetInfo: ", assetInfo);
5746
+ console.log(tag6, "assetInfo: ", assetInfo);
5156
5747
  if (!assetInfo) {
5157
5748
  assetInfo = {
5158
5749
  caip: asset.caip.toLowerCase(),
@@ -5170,70 +5761,70 @@ class SDK {
5170
5761
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5171
5762
  if (balance > 0 && valueUsd > 0) {
5172
5763
  priceValue = valueUsd / balance;
5173
- console.log(tag, "calculated priceUsd from valueUsd/balance:", priceValue);
5764
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5174
5765
  }
5175
5766
  }
5176
5767
  if (priceValue && priceValue > 0) {
5177
- console.log(tag, "detected priceUsd from balance:", priceValue);
5768
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
5178
5769
  assetInfo.priceUsd = priceValue;
5179
5770
  }
5180
5771
  }
5181
5772
  if (freshPriceUsd && freshPriceUsd > 0) {
5182
5773
  assetInfo.priceUsd = freshPriceUsd;
5183
- console.log(tag, "✅ Using fresh market price:", freshPriceUsd);
5774
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5184
5775
  let totalBalance = 0;
5185
5776
  let totalValueUsd = 0;
5186
- console.log(tag, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5777
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5187
5778
  for (const balanceEntry of matchingBalances) {
5188
5779
  const balance = parseFloat(balanceEntry.balance) || 0;
5189
5780
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5190
5781
  totalBalance += balance;
5191
5782
  totalValueUsd += valueUsd;
5192
- console.log(tag, ` Balance entry: ${balance} (${valueUsd} USD)`);
5783
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5193
5784
  }
5194
5785
  assetInfo.balance = totalBalance.toString();
5195
5786
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5196
- console.log(tag, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5787
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5197
5788
  }
5198
- console.log(tag, "CHECKPOINT 1");
5789
+ console.log(tag6, "CHECKPOINT 1");
5199
5790
  this.outboundAssetContext = { ...assetInfo, ...asset, ...pubkey };
5200
- console.log(tag, "CHECKPOINT 3");
5201
- console.log(tag, "outboundAssetContext: assetInfo: ", assetInfo);
5791
+ console.log(tag6, "CHECKPOINT 3");
5792
+ console.log(tag6, "outboundAssetContext: assetInfo: ", assetInfo);
5202
5793
  if (asset.caip) {
5203
5794
  this.outboundBlockchainContext = import_pioneer_caip8.caipToNetworkId(asset.caip);
5204
5795
  } else if (asset.networkId) {
5205
5796
  this.outboundBlockchainContext = asset.networkId;
5206
5797
  }
5207
- console.log(tag, "CHECKPOINT 4");
5798
+ console.log(tag6, "CHECKPOINT 4");
5208
5799
  this.events.emit("SET_OUTBOUND_ASSET_CONTEXT", this.outboundAssetContext);
5209
5800
  return this.outboundAssetContext;
5210
5801
  } catch (e) {
5211
- console.error(tag, "e: ", e);
5802
+ console.error(tag6, "e: ", e);
5212
5803
  throw e;
5213
5804
  }
5214
5805
  };
5215
5806
  }
5216
5807
  CheckERC20Allowance = async (params) => {
5217
- const tag = TAG9 + " | CheckERC20Allowance | ";
5808
+ const tag6 = TAG9 + " | CheckERC20Allowance | ";
5218
5809
  try {
5219
- console.log(tag, "Checking ERC20 allowance:", params);
5810
+ console.log(tag6, "Checking ERC20 allowance:", params);
5220
5811
  const result = await this.pioneer.GetTokenAllowance(params);
5221
- console.log(tag, "Allowance result:", result);
5812
+ console.log(tag6, "Allowance result:", result);
5222
5813
  return result.data;
5223
5814
  } catch (e) {
5224
- console.error(tag, "Error checking ERC20 allowance:", e);
5815
+ console.error(tag6, "Error checking ERC20 allowance:", e);
5225
5816
  throw e;
5226
5817
  }
5227
5818
  };
5228
5819
  BuildERC20ApprovalTx = async (params) => {
5229
- const tag = TAG9 + " | BuildERC20ApprovalTx | ";
5820
+ const tag6 = TAG9 + " | BuildERC20ApprovalTx | ";
5230
5821
  try {
5231
- console.log(tag, "Building ERC20 approval transaction:", params);
5822
+ console.log(tag6, "Building ERC20 approval transaction:", params);
5232
5823
  const result = await this.pioneer.BuildApprovalTransaction(params);
5233
- console.log(tag, "Approval tx built:", result);
5824
+ console.log(tag6, "Approval tx built:", result);
5234
5825
  return result.data;
5235
5826
  } catch (e) {
5236
- console.error(tag, "Error building approval transaction:", e);
5827
+ console.error(tag6, "Error building approval transaction:", e);
5237
5828
  throw e;
5238
5829
  }
5239
5830
  };