@ecency/wallets 1.5.29 → 1.5.30

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.
@@ -1,6 +1,6 @@
1
- import { CONFIG, getAccountFullQueryOptions, getQueryClient, getDynamicPropsQueryOptions, useBroadcastMutation, getSpkMarkets, getSpkWallet, getHiveEngineTokensMarket, getHiveEngineTokensBalances, getHiveEngineTokensMetadata, getHiveEngineTokenTransactions, getHiveEngineTokenMetrics, getHiveEngineUnclaimedRewards, EcencyAnalytics, getPortfolioQueryOptions, useAccountUpdate, getCurrencyRate } from '@ecency/sdk';
2
- export { getHiveEngineMetrics, getHiveEngineOpenOrders, getHiveEngineOrderBook, getHiveEngineTradeHistory } from '@ecency/sdk';
3
- import { useQuery, queryOptions, infiniteQueryOptions, useQueryClient, useMutation } from '@tanstack/react-query';
1
+ import { CONFIG, getAccountFullQueryOptions, getPortfolioQueryOptions, getQueryClient, AssetOperation, useAccountUpdate, getHiveEngineTokensBalancesQueryOptions, getHiveEngineTokensMetadataQueryOptions } from '@ecency/sdk';
2
+ export { AssetOperation, HIVE_ACCOUNT_OPERATION_GROUPS, HIVE_OPERATION_LIST, HIVE_OPERATION_NAME_BY_ID, HIVE_OPERATION_ORDERS, HiveEngineToken, NaiMap, PointTransactionType, Symbol, formattedNumber, getAccountWalletAssetInfoQueryOptions, getAllHiveEngineTokensQueryOptions, getHbdAssetGeneralInfoQueryOptions, getHbdAssetTransactionsQueryOptions, getHiveAssetGeneralInfoQueryOptions, getHiveAssetMetricQueryOptions, getHiveAssetTransactionsQueryOptions, getHiveAssetWithdrawalRoutesQueryOptions, getHiveEngineBalancesWithUsdQueryOptions, getHiveEngineTokenGeneralInfoQueryOptions, getHiveEngineTokenTransactionsQueryOptions, getHiveEngineTokensBalancesQueryOptions, getHiveEngineTokensMarketQueryOptions, getHiveEngineTokensMetadataQueryOptions, getHiveEngineTokensMetricsQueryOptions, getHiveEngineUnclaimedRewardsQueryOptions, getHivePowerAssetGeneralInfoQueryOptions, getHivePowerAssetTransactionsQueryOptions, getHivePowerDelegatesInfiniteQueryOptions, getHivePowerDelegatingsQueryOptions, getLarynxAssetGeneralInfoQueryOptions, getLarynxPowerAssetGeneralInfoQueryOptions, getPointsAssetGeneralInfoQueryOptions, getPointsAssetTransactionsQueryOptions, getPointsQueryOptions, getSpkAssetGeneralInfoQueryOptions, getSpkMarketsQueryOptions, getSpkWalletQueryOptions, isEmptyDate, parseAsset, resolveHiveOperationFilters, rewardSpk, useClaimPoints, useWalletOperation, vestsToHp } from '@ecency/sdk';
3
+ import { useQuery, queryOptions, useQueryClient, useMutation } from '@tanstack/react-query';
4
4
  import bip39, { mnemonicToSeedSync } from 'bip39';
5
5
  import { LRUCache } from 'lru-cache';
6
6
  import { BtcWallet, buildPsbt as buildPsbt$1 } from '@okxweb3/coin-bitcoin';
@@ -10,21 +10,16 @@ import { TonWallet } from '@okxweb3/coin-ton';
10
10
  import { SolWallet } from '@okxweb3/coin-solana';
11
11
  import { AptosWallet } from '@okxweb3/coin-aptos';
12
12
  import { bip32 } from '@okxweb3/crypto-lib';
13
- import { utils, PrivateKey } from '@hiveio/dhive';
13
+ import { PrivateKey } from '@hiveio/dhive';
14
14
  import { cryptoUtils } from '@hiveio/dhive/lib/crypto';
15
15
  import { Memo } from '@hiveio/dhive/lib/memo';
16
- import dayjs from 'dayjs';
17
- import hs from 'hivesigner';
18
- import numeral from 'numeral';
19
16
  import * as R from 'remeda';
20
17
 
21
18
  var __defProp = Object.defineProperty;
22
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
23
19
  var __export = (target, all) => {
24
20
  for (var name in all)
25
21
  __defProp(target, name, { get: all[name], enumerable: true });
26
22
  };
27
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
28
23
 
29
24
  // src/internal/scrypt-guard.ts
30
25
  var globalLike = globalThis;
@@ -584,2326 +579,6 @@ function useHiveKeysQuery(username) {
584
579
  }
585
580
  });
586
581
  }
587
-
588
- // src/modules/assets/utils/parse-asset.ts
589
- var Symbol2 = /* @__PURE__ */ ((Symbol3) => {
590
- Symbol3["HIVE"] = "HIVE";
591
- Symbol3["HBD"] = "HBD";
592
- Symbol3["VESTS"] = "VESTS";
593
- Symbol3["SPK"] = "SPK";
594
- return Symbol3;
595
- })(Symbol2 || {});
596
- var NaiMap = /* @__PURE__ */ ((NaiMap2) => {
597
- NaiMap2["@@000000021"] = "HIVE";
598
- NaiMap2["@@000000013"] = "HBD";
599
- NaiMap2["@@000000037"] = "VESTS";
600
- return NaiMap2;
601
- })(NaiMap || {});
602
- function parseAsset(sval) {
603
- if (typeof sval === "string") {
604
- const sp = sval.split(" ");
605
- return {
606
- amount: parseFloat(sp[0]),
607
- // @ts-ignore
608
- symbol: Symbol2[sp[1]]
609
- };
610
- } else {
611
- return {
612
- amount: parseFloat(sval.amount.toString()) / Math.pow(10, sval.precision),
613
- // @ts-ignore
614
- symbol: NaiMap[sval.nai]
615
- };
616
- }
617
- }
618
-
619
- // src/modules/assets/utils/is-empty-date.ts
620
- function isEmptyDate(s) {
621
- if (s === void 0) {
622
- return true;
623
- }
624
- return parseInt(s.split("-")[0], 10) < 1980;
625
- }
626
-
627
- // src/modules/assets/utils/vests-to-hp.ts
628
- function vestsToHp(vests, hivePerMVests) {
629
- return vests / 1e6 * hivePerMVests;
630
- }
631
-
632
- // src/modules/assets/utils/reward-spk.ts
633
- function rewardSpk(data, sstats) {
634
- let a = 0, b = 0, c = 0, t = 0, diff = data.head_block - data.spk_block;
635
- if (!data.spk_block) {
636
- return 0;
637
- } else if (diff < 28800) {
638
- return 0;
639
- } else {
640
- t = diff / 28800;
641
- a = data.gov ? simpleInterest(data.gov, t, sstats.spk_rate_lgov) : 0;
642
- b = data.pow ? simpleInterest(data.pow, t, sstats.spk_rate_lpow) : 0;
643
- c = simpleInterest(
644
- (data.granted.t > 0 ? data.granted.t : 0) + (data.granting.t && data.granting.t > 0 ? data.granting.t : 0),
645
- t,
646
- sstats.spk_rate_ldel
647
- );
648
- const i = a + b + c;
649
- if (i) {
650
- return i;
651
- } else {
652
- return 0;
653
- }
654
- }
655
- function simpleInterest(p, t2, r) {
656
- const amount = p * (1 + r / 365);
657
- const interest = amount - p;
658
- return interest * t2;
659
- }
660
- }
661
-
662
- // src/internal/hive-auth.ts
663
- var broadcastHandler = null;
664
- function registerHiveAuthBroadcastHandler(handler) {
665
- broadcastHandler = handler;
666
- }
667
- function getHiveAuthBroadcastHandler() {
668
- return broadcastHandler;
669
- }
670
-
671
- // src/modules/assets/utils/hive-auth.ts
672
- function registerWalletHiveAuthBroadcast(handler) {
673
- registerHiveAuthBroadcastHandler(handler);
674
- }
675
- function broadcastWithWalletHiveAuth(username, operations, keyType) {
676
- const handler = getHiveAuthBroadcastHandler();
677
- if (!handler) {
678
- throw new Error("HiveAuth broadcast handler is not registered");
679
- }
680
- return handler(username, operations, keyType);
681
- }
682
- function hasWalletHiveAuthBroadcast() {
683
- return typeof getHiveAuthBroadcastHandler() === "function";
684
- }
685
-
686
- // src/modules/assets/hive/queries/get-hive-asset-general-info-query-options.ts
687
- function getHiveAssetGeneralInfoQueryOptions(username) {
688
- return queryOptions({
689
- queryKey: ["assets", "hive", "general-info", username],
690
- staleTime: 6e4,
691
- refetchInterval: 9e4,
692
- queryFn: async () => {
693
- await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());
694
- await getQueryClient().prefetchQuery(
695
- getAccountFullQueryOptions(username)
696
- );
697
- const dynamicProps = getQueryClient().getQueryData(
698
- getDynamicPropsQueryOptions().queryKey
699
- );
700
- const accountData = getQueryClient().getQueryData(
701
- getAccountFullQueryOptions(username).queryKey
702
- );
703
- const marketTicker = await CONFIG.hiveClient.call("condenser_api", "get_ticker", []).catch(() => void 0);
704
- const marketPrice = Number.parseFloat(marketTicker?.latest ?? "");
705
- if (!accountData) {
706
- return {
707
- name: "HIVE",
708
- title: "Hive",
709
- price: Number.isFinite(marketPrice) ? marketPrice : dynamicProps ? dynamicProps.base / dynamicProps.quote : 0,
710
- accountBalance: 0
711
- };
712
- }
713
- const liquidBalance = parseAsset(accountData.balance).amount;
714
- const savingsBalance = parseAsset(accountData.savings_balance).amount;
715
- return {
716
- name: "HIVE",
717
- title: "Hive",
718
- price: Number.isFinite(marketPrice) ? marketPrice : dynamicProps ? dynamicProps.base / dynamicProps.quote : 0,
719
- accountBalance: liquidBalance + savingsBalance,
720
- parts: [
721
- {
722
- name: "current",
723
- balance: liquidBalance
724
- },
725
- {
726
- name: "savings",
727
- balance: savingsBalance
728
- }
729
- ]
730
- };
731
- }
732
- });
733
- }
734
- function getAPR(dynamicProps) {
735
- const initialInflationRate = 9.5;
736
- const initialBlock = 7e6;
737
- const decreaseRate = 25e4;
738
- const decreasePercentPerIncrement = 0.01;
739
- const headBlock = dynamicProps.headBlock;
740
- const deltaBlocks = headBlock - initialBlock;
741
- const decreaseIncrements = deltaBlocks / decreaseRate;
742
- let currentInflationRate = initialInflationRate - decreaseIncrements * decreasePercentPerIncrement;
743
- if (currentInflationRate < 0.95) {
744
- currentInflationRate = 0.95;
745
- }
746
- const vestingRewardPercent = dynamicProps.vestingRewardPercent / 1e4;
747
- const virtualSupply = dynamicProps.virtualSupply;
748
- const totalVestingFunds = dynamicProps.totalVestingFund;
749
- return (virtualSupply * currentInflationRate * vestingRewardPercent / totalVestingFunds).toFixed(3);
750
- }
751
- function getHivePowerAssetGeneralInfoQueryOptions(username) {
752
- return queryOptions({
753
- queryKey: ["assets", "hive-power", "general-info", username],
754
- staleTime: 6e4,
755
- refetchInterval: 9e4,
756
- queryFn: async () => {
757
- await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());
758
- await getQueryClient().prefetchQuery(
759
- getAccountFullQueryOptions(username)
760
- );
761
- const dynamicProps = getQueryClient().getQueryData(
762
- getDynamicPropsQueryOptions().queryKey
763
- );
764
- const accountData = getQueryClient().getQueryData(
765
- getAccountFullQueryOptions(username).queryKey
766
- );
767
- if (!dynamicProps || !accountData) {
768
- return {
769
- name: "HP",
770
- title: "Hive Power",
771
- price: 0,
772
- accountBalance: 0
773
- };
774
- }
775
- const marketTicker = await CONFIG.hiveClient.call("condenser_api", "get_ticker", []).catch(() => void 0);
776
- const marketPrice = Number.parseFloat(marketTicker?.latest ?? "");
777
- const price = Number.isFinite(marketPrice) ? marketPrice : dynamicProps.base / dynamicProps.quote;
778
- const vestingShares = parseAsset(accountData.vesting_shares).amount;
779
- const delegatedVests = parseAsset(accountData.delegated_vesting_shares).amount;
780
- const receivedVests = parseAsset(accountData.received_vesting_shares).amount;
781
- const withdrawRateVests = parseAsset(accountData.vesting_withdraw_rate).amount;
782
- const remainingToWithdrawVests = Math.max(
783
- (Number(accountData.to_withdraw) - Number(accountData.withdrawn)) / 1e6,
784
- 0
785
- );
786
- const nextWithdrawalVests = !isEmptyDate(accountData.next_vesting_withdrawal) ? Math.min(withdrawRateVests, remainingToWithdrawVests) : 0;
787
- const hpBalance = +vestsToHp(
788
- vestingShares,
789
- dynamicProps.hivePerMVests
790
- ).toFixed(3);
791
- const outgoingDelegationsHp = +vestsToHp(
792
- delegatedVests,
793
- dynamicProps.hivePerMVests
794
- ).toFixed(3);
795
- const incomingDelegationsHp = +vestsToHp(
796
- receivedVests,
797
- dynamicProps.hivePerMVests
798
- ).toFixed(3);
799
- const pendingPowerDownHp = +vestsToHp(
800
- remainingToWithdrawVests,
801
- dynamicProps.hivePerMVests
802
- ).toFixed(3);
803
- const nextPowerDownHp = +vestsToHp(
804
- nextWithdrawalVests,
805
- dynamicProps.hivePerMVests
806
- ).toFixed(3);
807
- const totalBalance = Math.max(hpBalance - pendingPowerDownHp, 0);
808
- const availableHp = Math.max(
809
- // Owned HP minus the portions already delegated away.
810
- hpBalance - outgoingDelegationsHp,
811
- 0
812
- );
813
- return {
814
- name: "HP",
815
- title: "Hive Power",
816
- price,
817
- accountBalance: +totalBalance.toFixed(3),
818
- apr: getAPR(dynamicProps),
819
- parts: [
820
- {
821
- name: "hp_balance",
822
- balance: hpBalance
823
- },
824
- {
825
- name: "available",
826
- balance: +availableHp.toFixed(3)
827
- },
828
- {
829
- name: "outgoing_delegations",
830
- balance: outgoingDelegationsHp
831
- },
832
- {
833
- name: "incoming_delegations",
834
- balance: incomingDelegationsHp
835
- },
836
- ...pendingPowerDownHp > 0 ? [
837
- {
838
- name: "pending_power_down",
839
- balance: +pendingPowerDownHp.toFixed(3)
840
- }
841
- ] : [],
842
- ...nextPowerDownHp > 0 && nextPowerDownHp !== pendingPowerDownHp ? [
843
- {
844
- name: "next_power_down",
845
- balance: +nextPowerDownHp.toFixed(3)
846
- }
847
- ] : []
848
- ]
849
- };
850
- }
851
- });
852
- }
853
- function getHbdAssetGeneralInfoQueryOptions(username) {
854
- return queryOptions({
855
- queryKey: ["assets", "hbd", "general-info", username],
856
- staleTime: 6e4,
857
- refetchInterval: 9e4,
858
- queryFn: async () => {
859
- await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());
860
- await getQueryClient().prefetchQuery(
861
- getAccountFullQueryOptions(username)
862
- );
863
- const accountData = getQueryClient().getQueryData(
864
- getAccountFullQueryOptions(username).queryKey
865
- );
866
- const dynamicProps = getQueryClient().getQueryData(
867
- getDynamicPropsQueryOptions().queryKey
868
- );
869
- let price = 1;
870
- try {
871
- await CONFIG.queryClient.prefetchQuery(
872
- getTokenPriceQueryOptions("HBD")
873
- );
874
- const marketPrice = CONFIG.queryClient.getQueryData(
875
- getTokenPriceQueryOptions("HBD").queryKey
876
- ) ?? 0;
877
- if (typeof marketPrice === "number" && Number.isFinite(marketPrice)) {
878
- price = marketPrice;
879
- }
880
- } catch {
881
- }
882
- if (!accountData) {
883
- return {
884
- name: "HBD",
885
- title: "Hive Dollar",
886
- price,
887
- accountBalance: 0
888
- };
889
- }
890
- return {
891
- name: "HBD",
892
- title: "Hive Dollar",
893
- price,
894
- accountBalance: parseAsset(accountData.hbd_balance).amount + parseAsset(accountData?.savings_hbd_balance).amount,
895
- apr: ((dynamicProps?.hbdInterestRate ?? 0) / 100).toFixed(3),
896
- parts: [
897
- {
898
- name: "current",
899
- balance: parseAsset(accountData.hbd_balance).amount
900
- },
901
- {
902
- name: "savings",
903
- balance: parseAsset(accountData.savings_hbd_balance).amount
904
- }
905
- ]
906
- };
907
- }
908
- });
909
- }
910
- var ops = utils.operationOrders;
911
- var HIVE_ACCOUNT_OPERATION_GROUPS = {
912
- transfers: [
913
- ops.transfer,
914
- ops.transfer_to_savings,
915
- ops.transfer_from_savings,
916
- ops.cancel_transfer_from_savings,
917
- ops.recurrent_transfer,
918
- ops.fill_recurrent_transfer,
919
- ops.escrow_transfer,
920
- ops.fill_recurrent_transfer
921
- ],
922
- "market-orders": [
923
- ops.fill_convert_request,
924
- ops.fill_order,
925
- ops.fill_collateralized_convert_request,
926
- ops.limit_order_create2,
927
- ops.limit_order_create,
928
- ops.limit_order_cancel
929
- ],
930
- interests: [ops.interest],
931
- "stake-operations": [
932
- ops.return_vesting_delegation,
933
- ops.withdraw_vesting,
934
- ops.transfer_to_vesting,
935
- ops.set_withdraw_vesting_route,
936
- ops.update_proposal_votes,
937
- ops.fill_vesting_withdraw,
938
- ops.account_witness_proxy,
939
- ops.delegate_vesting_shares
940
- ],
941
- rewards: [
942
- ops.author_reward,
943
- ops.curation_reward,
944
- ops.producer_reward,
945
- ops.claim_reward_balance,
946
- ops.comment_benefactor_reward,
947
- ops.liquidity_reward,
948
- ops.proposal_pay
949
- ],
950
- "": []
951
- };
952
- var HIVE_OPERATION_LIST = Object.keys(
953
- utils.operationOrders
954
- );
955
- var operationOrders = utils.operationOrders;
956
- var HIVE_OPERATION_ORDERS = operationOrders;
957
- var HIVE_OPERATION_NAME_BY_ID = Object.entries(operationOrders).reduce((acc, [name, id]) => {
958
- acc[id] = name;
959
- return acc;
960
- }, {});
961
-
962
- // src/modules/assets/hive/queries/get-hive-asset-transactions-query-options.ts
963
- var operationOrders2 = utils.operationOrders;
964
- function isHiveOperationName(value) {
965
- return Object.prototype.hasOwnProperty.call(operationOrders2, value);
966
- }
967
- function resolveHiveOperationFilters(filters) {
968
- const rawValues = Array.isArray(filters) ? filters : [filters];
969
- const hasAll = rawValues.includes("");
970
- const uniqueValues = Array.from(
971
- new Set(
972
- rawValues.filter(
973
- (value) => value !== void 0 && value !== null && value !== ""
974
- )
975
- )
976
- );
977
- const filterKey = hasAll || uniqueValues.length === 0 ? "all" : uniqueValues.map((value) => value.toString()).sort().join("|");
978
- const operationIds = /* @__PURE__ */ new Set();
979
- if (!hasAll) {
980
- uniqueValues.forEach((value) => {
981
- if (value in HIVE_ACCOUNT_OPERATION_GROUPS) {
982
- HIVE_ACCOUNT_OPERATION_GROUPS[value].forEach(
983
- (id) => operationIds.add(id)
984
- );
985
- return;
986
- }
987
- if (isHiveOperationName(value)) {
988
- operationIds.add(operationOrders2[value]);
989
- }
990
- });
991
- }
992
- const filterArgs = makeBitMaskFilter(Array.from(operationIds));
993
- return {
994
- filterKey,
995
- filterArgs
996
- };
997
- }
998
- function makeBitMaskFilter(allowedOperations) {
999
- let low = 0n;
1000
- let high = 0n;
1001
- allowedOperations.forEach((operation) => {
1002
- if (operation < 64) {
1003
- low |= 1n << BigInt(operation);
1004
- } else {
1005
- high |= 1n << BigInt(operation - 64);
1006
- }
1007
- });
1008
- return [low !== 0n ? low.toString() : null, high !== 0n ? high.toString() : null];
1009
- }
1010
- function getHiveAssetTransactionsQueryOptions(username, limit = 20, filters = []) {
1011
- const { filterArgs, filterKey } = resolveHiveOperationFilters(filters);
1012
- return infiniteQueryOptions({
1013
- queryKey: ["assets", "hive", "transactions", username, limit, filterKey],
1014
- initialData: { pages: [], pageParams: [] },
1015
- initialPageParam: -1,
1016
- getNextPageParam: (lastPage, __) => lastPage ? +(lastPage[lastPage.length - 1]?.num ?? 0) - 1 : -1,
1017
- queryFn: async ({ pageParam }) => {
1018
- const response = await CONFIG.hiveClient.call(
1019
- "condenser_api",
1020
- "get_account_history",
1021
- [username, pageParam, limit, ...filterArgs]
1022
- );
1023
- return response.map(
1024
- (x) => ({
1025
- num: x[0],
1026
- type: x[1].op[0],
1027
- timestamp: x[1].timestamp,
1028
- trx_id: x[1].trx_id,
1029
- ...x[1].op[1]
1030
- })
1031
- );
1032
- },
1033
- select: ({ pages, pageParams }) => ({
1034
- pageParams,
1035
- pages: pages.map(
1036
- (page) => page.filter((item) => {
1037
- switch (item.type) {
1038
- case "author_reward":
1039
- case "comment_benefactor_reward":
1040
- const hivePayout = parseAsset(item.hive_payout);
1041
- return hivePayout.amount > 0;
1042
- case "transfer":
1043
- case "transfer_to_savings":
1044
- case "transfer_to_vesting":
1045
- case "recurrent_transfer":
1046
- return parseAsset(item.amount).symbol === "HIVE";
1047
- case "transfer_from_savings":
1048
- return parseAsset(item.amount).symbol === "HIVE";
1049
- case "fill_recurrent_transfer":
1050
- const asset = parseAsset(item.amount);
1051
- return ["HIVE"].includes(asset.symbol);
1052
- case "claim_reward_balance":
1053
- const rewardHive = parseAsset(
1054
- item.reward_hive
1055
- );
1056
- return rewardHive.amount > 0;
1057
- case "curation_reward":
1058
- case "cancel_transfer_from_savings":
1059
- case "fill_order":
1060
- case "limit_order_create":
1061
- case "limit_order_cancel":
1062
- case "fill_convert_request":
1063
- case "fill_collateralized_convert_request":
1064
- return true;
1065
- case "limit_order_create2":
1066
- return true;
1067
- default:
1068
- return false;
1069
- }
1070
- })
1071
- )
1072
- })
1073
- });
1074
- }
1075
- function getHivePowerAssetTransactionsQueryOptions(username, limit = 20, filters = []) {
1076
- const { filterKey } = resolveHiveOperationFilters(filters);
1077
- const userSelectedOperations = new Set(
1078
- Array.isArray(filters) ? filters : [filters]
1079
- );
1080
- const hasAllFilter = userSelectedOperations.has("") || userSelectedOperations.size === 0;
1081
- return infiniteQueryOptions({
1082
- ...getHiveAssetTransactionsQueryOptions(username, limit, filters),
1083
- queryKey: [
1084
- "assets",
1085
- "hive-power",
1086
- "transactions",
1087
- username,
1088
- limit,
1089
- filterKey
1090
- ],
1091
- select: ({ pages, pageParams }) => ({
1092
- pageParams,
1093
- pages: pages.map(
1094
- (page) => page.filter((item) => {
1095
- switch (item.type) {
1096
- case "author_reward":
1097
- case "comment_benefactor_reward":
1098
- const vestingPayout = parseAsset(
1099
- item.vesting_payout
1100
- );
1101
- return vestingPayout.amount > 0;
1102
- case "claim_reward_balance":
1103
- const rewardVests = parseAsset(
1104
- item.reward_vests
1105
- );
1106
- return rewardVests.amount > 0;
1107
- case "transfer_to_vesting":
1108
- return true;
1109
- case "transfer":
1110
- case "transfer_to_savings":
1111
- case "recurrent_transfer":
1112
- return ["VESTS", "HP"].includes(
1113
- parseAsset(item.amount).symbol
1114
- );
1115
- case "fill_recurrent_transfer":
1116
- const asset = parseAsset(item.amount);
1117
- return ["VESTS", "HP"].includes(asset.symbol);
1118
- case "curation_reward":
1119
- case "withdraw_vesting":
1120
- case "delegate_vesting_shares":
1121
- case "fill_vesting_withdraw":
1122
- case "return_vesting_delegation":
1123
- case "producer_reward":
1124
- case "set_withdraw_vesting_route":
1125
- return true;
1126
- default:
1127
- return hasAllFilter || userSelectedOperations.has(item.type);
1128
- }
1129
- })
1130
- )
1131
- })
1132
- });
1133
- }
1134
- function getHbdAssetTransactionsQueryOptions(username, limit = 20, filters = []) {
1135
- const { filterKey } = resolveHiveOperationFilters(filters);
1136
- return infiniteQueryOptions({
1137
- ...getHiveAssetTransactionsQueryOptions(username, limit, filters),
1138
- queryKey: ["assets", "hbd", "transactions", username, limit, filterKey],
1139
- select: ({ pages, pageParams }) => ({
1140
- pageParams,
1141
- pages: pages.map(
1142
- (page) => page.filter((item) => {
1143
- switch (item.type) {
1144
- case "author_reward":
1145
- case "comment_benefactor_reward":
1146
- const hbdPayout = parseAsset(item.hbd_payout);
1147
- return hbdPayout.amount > 0;
1148
- case "claim_reward_balance":
1149
- const rewardHbd = parseAsset(
1150
- item.reward_hbd
1151
- );
1152
- return rewardHbd.amount > 0;
1153
- case "transfer":
1154
- case "transfer_to_savings":
1155
- case "transfer_to_vesting":
1156
- case "recurrent_transfer":
1157
- return parseAsset(item.amount).symbol === "HBD";
1158
- case "transfer_from_savings":
1159
- return parseAsset(item.amount).symbol === "HBD";
1160
- case "fill_recurrent_transfer":
1161
- const asset = parseAsset(item.amount);
1162
- return ["HBD"].includes(asset.symbol);
1163
- case "cancel_transfer_from_savings":
1164
- case "fill_order":
1165
- case "limit_order_create":
1166
- case "limit_order_cancel":
1167
- case "fill_convert_request":
1168
- case "fill_collateralized_convert_request":
1169
- case "proposal_pay":
1170
- case "interest":
1171
- return true;
1172
- case "limit_order_create2":
1173
- return true;
1174
- default:
1175
- return false;
1176
- }
1177
- })
1178
- )
1179
- })
1180
- });
1181
- }
1182
- function getHiveAssetMetricQueryOptions(bucketSeconds = 86400) {
1183
- return infiniteQueryOptions({
1184
- queryKey: ["assets", "hive", "metrics", bucketSeconds],
1185
- queryFn: async ({ pageParam: [startDate, endDate] }) => {
1186
- const apiData = await CONFIG.hiveClient.call(
1187
- "condenser_api",
1188
- "get_market_history",
1189
- [
1190
- bucketSeconds,
1191
- dayjs(startDate).format("YYYY-MM-DDTHH:mm:ss"),
1192
- dayjs(endDate).format("YYYY-MM-DDTHH:mm:ss")
1193
- ]
1194
- );
1195
- return apiData.map(({ hive, non_hive, open }) => ({
1196
- close: non_hive.close / hive.close,
1197
- open: non_hive.open / hive.open,
1198
- low: non_hive.low / hive.low,
1199
- high: non_hive.high / hive.high,
1200
- volume: hive.volume,
1201
- time: new Date(open)
1202
- }));
1203
- },
1204
- initialPageParam: [
1205
- // Fetch at least 8 hours or given interval
1206
- dayjs().subtract(Math.max(100 * bucketSeconds, 28800), "second").toDate(),
1207
- /* @__PURE__ */ new Date()
1208
- ],
1209
- getNextPageParam: (_, __, [prevStartDate]) => [
1210
- dayjs(prevStartDate.getTime()).subtract(Math.max(100 * bucketSeconds, 28800), "second").toDate(),
1211
- dayjs(prevStartDate.getTime()).subtract(bucketSeconds, "second").toDate()
1212
- ]
1213
- });
1214
- }
1215
- function getHiveAssetWithdrawalRoutesQueryOptions(username) {
1216
- return queryOptions({
1217
- queryKey: ["assets", "hive", "withdrawal-routes", username],
1218
- queryFn: () => CONFIG.hiveClient.database.call("get_withdraw_routes", [
1219
- username,
1220
- "outgoing"
1221
- ])
1222
- });
1223
- }
1224
- function getHivePowerDelegatesInfiniteQueryOptions(username, limit = 50) {
1225
- return queryOptions({
1226
- queryKey: ["assets", "hive-power", "delegates", username],
1227
- enabled: !!username,
1228
- queryFn: () => CONFIG.hiveClient.database.call("get_vesting_delegations", [
1229
- username,
1230
- "",
1231
- limit
1232
- ])
1233
- });
1234
- }
1235
- function getHivePowerDelegatingsQueryOptions(username) {
1236
- return queryOptions({
1237
- queryKey: ["assets", "hive-power", "delegatings", username],
1238
- queryFn: async () => {
1239
- const response = await fetch(
1240
- CONFIG.privateApiHost + `/private-api/received-vesting/${username}`,
1241
- {
1242
- headers: {
1243
- "Content-Type": "application/json"
1244
- }
1245
- }
1246
- );
1247
- return (await response.json()).list;
1248
- },
1249
- select: (data) => data.sort(
1250
- (a, b) => parseAsset(b.vesting_shares).amount - parseAsset(a.vesting_shares).amount
1251
- )
1252
- });
1253
- }
1254
-
1255
- // src/modules/assets/utils/keychain-fallback.ts
1256
- async function broadcastWithKeychainFallback(account, operations, authority = "Active") {
1257
- if (typeof window === "undefined" || !window.hive_keychain) {
1258
- throw new Error("[SDK][Wallets] \u2013 Keychain extension not found");
1259
- }
1260
- return new Promise((resolve, reject) => {
1261
- window.hive_keychain.requestBroadcast(
1262
- account,
1263
- operations,
1264
- authority,
1265
- (response) => {
1266
- if (!response.success) {
1267
- reject(new Error(response.message || "Keychain operation cancelled"));
1268
- return;
1269
- }
1270
- resolve(response.result);
1271
- }
1272
- );
1273
- });
1274
- }
1275
-
1276
- // src/modules/assets/hive/mutations/transfer.ts
1277
- async function transferHive(payload, auth) {
1278
- const parsedAsset = parseAsset(payload.amount);
1279
- const token = parsedAsset.symbol;
1280
- const precision = token === "VESTS" /* VESTS */ ? 6 : 3;
1281
- const formattedAmount = parsedAsset.amount.toFixed(precision);
1282
- const amountWithSymbol = `${formattedAmount} ${token}`;
1283
- const operation = [
1284
- "transfer",
1285
- {
1286
- from: payload.from,
1287
- to: payload.to,
1288
- amount: amountWithSymbol,
1289
- memo: payload.memo
1290
- }
1291
- ];
1292
- if (payload.type === "key" && "key" in payload) {
1293
- const { key, type, ...params } = payload;
1294
- return CONFIG.hiveClient.broadcast.transfer(
1295
- {
1296
- from: params.from,
1297
- to: params.to,
1298
- amount: amountWithSymbol,
1299
- memo: params.memo
1300
- },
1301
- key
1302
- );
1303
- } else if (payload.type === "keychain") {
1304
- if (auth?.broadcast) {
1305
- return auth.broadcast([operation], "active");
1306
- }
1307
- return broadcastWithKeychainFallback(payload.from, [operation], "Active");
1308
- } else if (payload.type === "hiveauth") {
1309
- if (auth?.broadcast) {
1310
- return auth.broadcast([operation], "active");
1311
- }
1312
- return broadcastWithWalletHiveAuth(payload.from, [operation], "active");
1313
- } else {
1314
- return hs.sendOperation(
1315
- operation,
1316
- { callback: `https://ecency.com/@${payload.from}/wallet` },
1317
- () => {
1318
- }
1319
- );
1320
- }
1321
- }
1322
- async function transferToSavingsHive(payload, auth) {
1323
- const operationPayload = {
1324
- from: payload.from,
1325
- to: payload.to,
1326
- amount: payload.amount,
1327
- memo: payload.memo
1328
- };
1329
- const operation = ["transfer_to_savings", operationPayload];
1330
- if (payload.type === "key" && "key" in payload) {
1331
- const { key, type, ...params } = payload;
1332
- return CONFIG.hiveClient.broadcast.sendOperations(
1333
- [["transfer_to_savings", params]],
1334
- key
1335
- );
1336
- } else if (payload.type === "keychain") {
1337
- if (auth?.broadcast) {
1338
- return auth.broadcast([operation], "active");
1339
- }
1340
- return broadcastWithKeychainFallback(payload.from, [operation], "Active");
1341
- } else if (payload.type === "hiveauth") {
1342
- if (auth?.broadcast) {
1343
- return auth.broadcast([operation], "active");
1344
- }
1345
- return broadcastWithWalletHiveAuth(payload.from, [operation], "active");
1346
- } else {
1347
- return hs.sendOperation(operation, { callback: `https://ecency.com/@${payload.from}/wallet` }, () => {
1348
- });
1349
- }
1350
- }
1351
- async function transferFromSavingsHive(payload, auth) {
1352
- const requestId = payload.request_id ?? Date.now() >>> 0;
1353
- const operationPayload = {
1354
- from: payload.from,
1355
- to: payload.to,
1356
- amount: payload.amount,
1357
- memo: payload.memo,
1358
- request_id: requestId
1359
- };
1360
- const operation = ["transfer_from_savings", operationPayload];
1361
- if (payload.type === "key" && "key" in payload) {
1362
- const { key } = payload;
1363
- return CONFIG.hiveClient.broadcast.sendOperations(
1364
- [operation],
1365
- key
1366
- );
1367
- }
1368
- if (payload.type === "keychain") {
1369
- if (auth?.broadcast) {
1370
- return auth.broadcast([operation], "active");
1371
- }
1372
- return broadcastWithKeychainFallback(payload.from, [operation], "Active");
1373
- }
1374
- if (payload.type === "hiveauth") {
1375
- if (auth?.broadcast) {
1376
- return auth.broadcast([operation], "active");
1377
- }
1378
- return broadcastWithWalletHiveAuth(payload.from, [operation], "active");
1379
- }
1380
- return hs.sendOperation(operation, { callback: `https://ecency.com/@${payload.from}/wallet` }, () => {
1381
- });
1382
- }
1383
- async function powerUpHive(payload, auth) {
1384
- const operationPayload = {
1385
- from: payload.from,
1386
- to: payload.to,
1387
- amount: payload.amount,
1388
- memo: payload.memo
1389
- };
1390
- const operation = ["transfer_to_vesting", operationPayload];
1391
- if (payload.type === "key" && "key" in payload) {
1392
- const { key, type, ...params } = payload;
1393
- return CONFIG.hiveClient.broadcast.sendOperations(
1394
- [["transfer_to_vesting", params]],
1395
- key
1396
- );
1397
- } else if (payload.type === "keychain") {
1398
- if (auth?.broadcast) {
1399
- return auth.broadcast([operation], "active");
1400
- }
1401
- return broadcastWithKeychainFallback(payload.from, [operation], "Active");
1402
- } else if (payload.type === "hiveauth") {
1403
- if (auth?.broadcast) {
1404
- return auth.broadcast([operation], "active");
1405
- }
1406
- return broadcastWithWalletHiveAuth(payload.from, [operation], "active");
1407
- } else {
1408
- return hs.sendOperation(operation, { callback: `https://ecency.com/@${payload.from}/wallet` }, () => {
1409
- });
1410
- }
1411
- }
1412
- async function delegateHive(payload, auth) {
1413
- const operationPayload = {
1414
- delegator: payload.from,
1415
- delegatee: payload.to,
1416
- vesting_shares: payload.amount
1417
- };
1418
- const operation = ["delegate_vesting_shares", operationPayload];
1419
- if (payload.type === "key" && "key" in payload) {
1420
- const { key } = payload;
1421
- return CONFIG.hiveClient.broadcast.sendOperations(
1422
- [operation],
1423
- key
1424
- );
1425
- } else if (payload.type === "keychain") {
1426
- if (auth?.broadcast) {
1427
- return auth.broadcast([operation], "active");
1428
- }
1429
- return broadcastWithKeychainFallback(payload.from, [operation], "Active");
1430
- } else if (payload.type === "hiveauth") {
1431
- if (auth?.broadcast) {
1432
- return auth.broadcast([operation], "active");
1433
- }
1434
- return broadcastWithWalletHiveAuth(payload.from, [operation], "active");
1435
- } else {
1436
- return hs.sendOperation(operation, { callback: `https://ecency.com/@${payload.from}/wallet` }, () => {
1437
- });
1438
- }
1439
- }
1440
- async function powerDownHive(payload, auth) {
1441
- const operationPayload = {
1442
- account: payload.from,
1443
- vesting_shares: payload.amount
1444
- };
1445
- const operation = ["withdraw_vesting", operationPayload];
1446
- if (payload.type === "key" && "key" in payload) {
1447
- const { key } = payload;
1448
- return CONFIG.hiveClient.broadcast.sendOperations(
1449
- [operation],
1450
- key
1451
- );
1452
- } else if (payload.type === "keychain") {
1453
- if (auth?.broadcast) {
1454
- return auth.broadcast([operation], "active");
1455
- }
1456
- return broadcastWithKeychainFallback(payload.from, [operation], "Active");
1457
- } else if (payload.type === "hiveauth") {
1458
- if (auth?.broadcast) {
1459
- return auth.broadcast([operation], "active");
1460
- }
1461
- return broadcastWithWalletHiveAuth(payload.from, [operation], "active");
1462
- } else {
1463
- return hs.sendOperation(operation, { callback: `https://ecency.com/@${payload.from}/wallet` }, () => {
1464
- });
1465
- }
1466
- }
1467
- async function withdrawVestingRouteHive(payload, auth) {
1468
- const baseParams = {
1469
- from_account: payload.from_account,
1470
- to_account: payload.to_account,
1471
- percent: payload.percent,
1472
- auto_vest: payload.auto_vest
1473
- };
1474
- const operation = ["set_withdraw_vesting_route", baseParams];
1475
- if (payload.type === "key" && "key" in payload) {
1476
- const { key, type: type2, ...params2 } = payload;
1477
- return CONFIG.hiveClient.broadcast.sendOperations(
1478
- [["set_withdraw_vesting_route", params2]],
1479
- key
1480
- );
1481
- }
1482
- if (payload.type === "keychain") {
1483
- if (auth?.broadcast) {
1484
- return auth.broadcast([operation], "active");
1485
- }
1486
- return broadcastWithKeychainFallback(payload.from_account, [operation], "Active");
1487
- }
1488
- if (payload.type === "hiveauth") {
1489
- if (auth?.broadcast) {
1490
- return auth.broadcast([operation], "active");
1491
- }
1492
- return broadcastWithWalletHiveAuth(payload.from_account, [operation], "active");
1493
- }
1494
- const { type, ...params } = payload;
1495
- return hs.sendOperation(operation, { callback: `https://ecency.com/@${params.from_account}/wallet` }, () => {
1496
- });
1497
- }
1498
- function useClaimRewards(username, auth, onSuccess) {
1499
- const { data } = useQuery(getAccountFullQueryOptions(username));
1500
- const queryClient = useQueryClient();
1501
- return useBroadcastMutation(
1502
- ["assets", "hive", "claim-rewards", data?.name],
1503
- username,
1504
- () => {
1505
- if (!data) {
1506
- throw new Error("Failed to fetch account while claiming balance");
1507
- }
1508
- const {
1509
- reward_hive_balance: hiveBalance,
1510
- reward_hbd_balance: hbdBalance,
1511
- reward_vesting_balance: vestingBalance
1512
- } = data;
1513
- return [
1514
- [
1515
- "claim_reward_balance",
1516
- {
1517
- account: username,
1518
- reward_hive: hiveBalance,
1519
- reward_hbd: hbdBalance,
1520
- reward_vests: vestingBalance
1521
- }
1522
- ]
1523
- ];
1524
- },
1525
- async () => {
1526
- onSuccess();
1527
- await delay(1e3);
1528
- queryClient.invalidateQueries({
1529
- queryKey: getAccountFullQueryOptions(username).queryKey
1530
- });
1531
- queryClient.invalidateQueries({
1532
- queryKey: ["ecency-wallets", "portfolio", "v2", username]
1533
- });
1534
- queryClient.invalidateQueries({
1535
- queryKey: getHiveAssetGeneralInfoQueryOptions(username).queryKey
1536
- });
1537
- queryClient.invalidateQueries({
1538
- queryKey: getHbdAssetGeneralInfoQueryOptions(username).queryKey
1539
- });
1540
- queryClient.invalidateQueries({
1541
- queryKey: getHivePowerAssetGeneralInfoQueryOptions(username).queryKey
1542
- });
1543
- ["HIVE", "HBD", "HP"].forEach((asset) => {
1544
- queryClient.invalidateQueries({
1545
- queryKey: ["ecency-wallets", "asset-info", username, asset]
1546
- });
1547
- });
1548
- setTimeout(() => {
1549
- queryClient.invalidateQueries({
1550
- queryKey: getAccountFullQueryOptions(username).queryKey
1551
- });
1552
- queryClient.invalidateQueries({
1553
- queryKey: ["ecency-wallets", "portfolio", "v2", username]
1554
- });
1555
- queryClient.invalidateQueries({
1556
- queryKey: getHiveAssetGeneralInfoQueryOptions(username).queryKey
1557
- });
1558
- queryClient.invalidateQueries({
1559
- queryKey: getHbdAssetGeneralInfoQueryOptions(username).queryKey
1560
- });
1561
- queryClient.invalidateQueries({
1562
- queryKey: getHivePowerAssetGeneralInfoQueryOptions(username).queryKey
1563
- });
1564
- ["HIVE", "HBD", "HP"].forEach((asset) => {
1565
- queryClient.invalidateQueries({
1566
- queryKey: ["ecency-wallets", "asset-info", username, asset]
1567
- });
1568
- });
1569
- }, 5e3);
1570
- },
1571
- auth
1572
- );
1573
- }
1574
- async function claimInterestHive(payload, auth) {
1575
- const requestId = payload.request_id ?? Date.now() >>> 0;
1576
- const baseOperation = {
1577
- from: payload.from,
1578
- to: payload.to,
1579
- amount: payload.amount,
1580
- memo: payload.memo,
1581
- request_id: requestId
1582
- };
1583
- const cancelOperation = {
1584
- from: payload.from,
1585
- request_id: requestId
1586
- };
1587
- const operations = [
1588
- ["transfer_from_savings", baseOperation],
1589
- ["cancel_transfer_from_savings", cancelOperation]
1590
- ];
1591
- if (payload.type === "key" && "key" in payload) {
1592
- const { key } = payload;
1593
- return CONFIG.hiveClient.broadcast.sendOperations(operations, key);
1594
- }
1595
- if (payload.type === "keychain") {
1596
- if (auth?.broadcast) {
1597
- return auth.broadcast(operations, "active");
1598
- }
1599
- return broadcastWithKeychainFallback(payload.from, operations, "Active");
1600
- }
1601
- if (payload.type === "hiveauth") {
1602
- if (auth?.broadcast) {
1603
- return auth.broadcast(operations, "active");
1604
- }
1605
- return broadcastWithWalletHiveAuth(payload.from, operations, "active");
1606
- }
1607
- return hs.sendOperations(operations, { callback: `https://ecency.com/@${payload.from}/wallet` }, () => {
1608
- });
1609
- }
1610
- async function convertHbd(payload, auth) {
1611
- const requestid = Math.floor(Date.now() / 1e3);
1612
- const operationPayload = {
1613
- owner: payload.from,
1614
- requestid,
1615
- amount: payload.amount
1616
- };
1617
- const operation = ["convert", operationPayload];
1618
- if (payload.type === "key" && "key" in payload) {
1619
- const { key, type, ...params } = payload;
1620
- return CONFIG.hiveClient.broadcast.sendOperations(
1621
- [["convert", { ...params, owner: params.from, requestid }]],
1622
- key
1623
- );
1624
- } else if (payload.type === "keychain") {
1625
- if (auth?.broadcast) {
1626
- return auth.broadcast([operation], "active");
1627
- }
1628
- return broadcastWithKeychainFallback(payload.from, [operation], "Active");
1629
- } else if (payload.type === "hiveauth") {
1630
- if (auth?.broadcast) {
1631
- return auth.broadcast([operation], "active");
1632
- }
1633
- return broadcastWithWalletHiveAuth(payload.from, [operation], "active");
1634
- } else {
1635
- return hs.sendOperation(operation, { callback: `https://ecency.com/@${payload.from}/wallet` }, () => {
1636
- });
1637
- }
1638
- }
1639
-
1640
- // src/modules/assets/types/asset-operation.ts
1641
- var AssetOperation = /* @__PURE__ */ ((AssetOperation2) => {
1642
- AssetOperation2["Transfer"] = "transfer";
1643
- AssetOperation2["TransferToSavings"] = "transfer-saving";
1644
- AssetOperation2["WithdrawFromSavings"] = "withdraw-saving";
1645
- AssetOperation2["Delegate"] = "delegate";
1646
- AssetOperation2["PowerUp"] = "power-up";
1647
- AssetOperation2["PowerDown"] = "power-down";
1648
- AssetOperation2["WithdrawRoutes"] = "withdraw-routes";
1649
- AssetOperation2["ClaimInterest"] = "claim-interest";
1650
- AssetOperation2["Swap"] = "swap";
1651
- AssetOperation2["Convert"] = "convert";
1652
- AssetOperation2["Gift"] = "gift";
1653
- AssetOperation2["Promote"] = "promote";
1654
- AssetOperation2["Claim"] = "claim";
1655
- AssetOperation2["Buy"] = "buy";
1656
- AssetOperation2["LockLiquidity"] = "lock";
1657
- AssetOperation2["Stake"] = "stake";
1658
- AssetOperation2["Unstake"] = "unstake";
1659
- AssetOperation2["Undelegate"] = "undelegate";
1660
- return AssetOperation2;
1661
- })(AssetOperation || {});
1662
- async function transferSpk(payload, auth) {
1663
- const json = JSON.stringify({
1664
- to: payload.to,
1665
- amount: parseAsset(payload.amount).amount * 1e3,
1666
- ...typeof payload.memo === "string" ? { memo: payload.memo } : {}
1667
- });
1668
- const op = {
1669
- id: "spkcc_spk_send",
1670
- json,
1671
- required_auths: [payload.from],
1672
- required_posting_auths: []
1673
- };
1674
- const operation = [
1675
- "custom_json",
1676
- {
1677
- id: op.id,
1678
- required_auths: [payload.from],
1679
- required_posting_auths: [],
1680
- json
1681
- }
1682
- ];
1683
- if (payload.type === "key" && "key" in payload) {
1684
- const { key } = payload;
1685
- return CONFIG.hiveClient.broadcast.json(op, key);
1686
- } else if (payload.type === "keychain") {
1687
- if (auth?.broadcast) {
1688
- return auth.broadcast([operation], "active");
1689
- }
1690
- return broadcastWithKeychainFallback(payload.from, [operation], "Active");
1691
- } else if (payload.type === "hiveauth") {
1692
- if (auth?.broadcast) {
1693
- return auth.broadcast([operation], "active");
1694
- }
1695
- return broadcastWithWalletHiveAuth(payload.from, [operation], "active");
1696
- } else {
1697
- const { amount } = parseAsset(payload.amount);
1698
- return hs.sign(
1699
- "custom_json",
1700
- {
1701
- authority: "active",
1702
- required_auths: `["${payload.from}"]`,
1703
- required_posting_auths: "[]",
1704
- id: "spkcc_spk_send",
1705
- json: JSON.stringify({
1706
- to: payload.to,
1707
- amount: +amount * 1e3,
1708
- ...typeof payload.memo === "string" ? { memo: payload.memo } : {}
1709
- })
1710
- },
1711
- `https://ecency.com/@${payload.from}/wallet`
1712
- );
1713
- }
1714
- }
1715
- var lockLarynx = async (payload, auth) => {
1716
- const json = JSON.stringify({ amount: +payload.amount * 1e3 });
1717
- const op = {
1718
- id: payload.mode === "lock" ? "spkcc_gov_up" : "spkcc_gov_down",
1719
- json,
1720
- required_auths: [payload.from],
1721
- required_posting_auths: []
1722
- };
1723
- const operation = [
1724
- "custom_json",
1725
- {
1726
- id: op.id,
1727
- required_auths: [payload.from],
1728
- required_posting_auths: [],
1729
- json
1730
- }
1731
- ];
1732
- if (payload.type === "key" && "key" in payload) {
1733
- const { key } = payload;
1734
- return CONFIG.hiveClient.broadcast.json(op, key);
1735
- } else if (payload.type === "keychain") {
1736
- if (auth?.broadcast) {
1737
- return auth.broadcast([operation], "active");
1738
- }
1739
- return broadcastWithKeychainFallback(payload.from, [operation], "Active");
1740
- } else if (payload.type === "hiveauth") {
1741
- if (auth?.broadcast) {
1742
- return auth.broadcast([operation], "active");
1743
- }
1744
- return broadcastWithWalletHiveAuth(payload.from, [operation], "active");
1745
- } else {
1746
- const { amount } = parseAsset(payload.amount);
1747
- return hs.sign(
1748
- "custom_json",
1749
- {
1750
- authority: "active",
1751
- required_auths: `["${payload.from}"]`,
1752
- required_posting_auths: "[]",
1753
- id: op.id,
1754
- json: JSON.stringify({ amount: +amount * 1e3 })
1755
- },
1756
- `https://ecency.com/@${payload.from}/wallet`
1757
- );
1758
- }
1759
- };
1760
- async function powerUpLarynx(payload, auth) {
1761
- const json = JSON.stringify({ amount: +payload.amount * 1e3 });
1762
- const op = {
1763
- id: `spkcc_power_${payload.mode}`,
1764
- json,
1765
- required_auths: [payload.from],
1766
- required_posting_auths: []
1767
- };
1768
- const operation = [
1769
- "custom_json",
1770
- {
1771
- id: `spkcc_power_${payload.mode}`,
1772
- required_auths: [payload.from],
1773
- required_posting_auths: [],
1774
- json
1775
- }
1776
- ];
1777
- if (payload.type === "key" && "key" in payload) {
1778
- const { key } = payload;
1779
- return CONFIG.hiveClient.broadcast.json(op, key);
1780
- } else if (payload.type === "keychain") {
1781
- if (auth?.broadcast) {
1782
- return auth.broadcast([operation], "active");
1783
- }
1784
- return broadcastWithKeychainFallback(payload.from, [operation], "Active");
1785
- } else if (payload.type === "hiveauth") {
1786
- if (auth?.broadcast) {
1787
- return auth.broadcast([operation], "active");
1788
- }
1789
- return broadcastWithWalletHiveAuth(payload.from, [operation], "active");
1790
- } else {
1791
- const { amount } = parseAsset(payload.amount);
1792
- return hs.sign(
1793
- "custom_json",
1794
- {
1795
- authority: "active",
1796
- required_auths: `["${payload.from}"]`,
1797
- required_posting_auths: "[]",
1798
- id: `spkcc_power_${payload.mode}`,
1799
- json: JSON.stringify({ amount: +amount * 1e3 })
1800
- },
1801
- `https://ecency.com/@${payload.from}/wallet`
1802
- );
1803
- }
1804
- }
1805
- async function transferLarynx(payload, auth) {
1806
- const json = JSON.stringify({
1807
- to: payload.to,
1808
- amount: parseAsset(payload.amount).amount * 1e3,
1809
- ...typeof payload.memo === "string" ? { memo: payload.memo } : {}
1810
- });
1811
- const op = {
1812
- id: "spkcc_send",
1813
- json,
1814
- required_auths: [payload.from],
1815
- required_posting_auths: []
1816
- };
1817
- const operation = [
1818
- "custom_json",
1819
- {
1820
- id: "spkcc_send",
1821
- required_auths: [payload.from],
1822
- required_posting_auths: [],
1823
- json
1824
- }
1825
- ];
1826
- if (payload.type === "key" && "key" in payload) {
1827
- const { key } = payload;
1828
- return CONFIG.hiveClient.broadcast.json(op, key);
1829
- } else if (payload.type === "keychain") {
1830
- if (auth?.broadcast) {
1831
- return auth.broadcast([operation], "active");
1832
- }
1833
- return broadcastWithKeychainFallback(payload.from, [operation], "Active");
1834
- } else if (payload.type === "hiveauth") {
1835
- if (auth?.broadcast) {
1836
- return auth.broadcast([operation], "active");
1837
- }
1838
- return broadcastWithWalletHiveAuth(payload.from, [operation], "active");
1839
- } else {
1840
- const { amount } = parseAsset(payload.amount);
1841
- return hs.sign(
1842
- "custom_json",
1843
- {
1844
- authority: "active",
1845
- required_auths: `["${payload.from}"]`,
1846
- required_posting_auths: "[]",
1847
- id: "spkcc_send",
1848
- json: JSON.stringify({
1849
- to: payload.to,
1850
- amount: +amount * 1e3,
1851
- ...typeof payload.memo === "string" ? { memo: payload.memo } : {}
1852
- })
1853
- },
1854
- `https://ecency.com/@${payload.from}/wallet`
1855
- );
1856
- }
1857
- }
1858
- function getSpkMarketsQueryOptions() {
1859
- return queryOptions({
1860
- queryKey: ["assets", "spk", "markets"],
1861
- staleTime: 6e4,
1862
- refetchInterval: 9e4,
1863
- queryFn: async () => {
1864
- const data = await getSpkMarkets();
1865
- return {
1866
- list: Object.entries(data.markets.node).map(([name, node]) => ({
1867
- name,
1868
- status: node.lastGood >= data.head_block - 1200 ? "\u{1F7E9}" : node.lastGood > data.head_block - 28800 ? "\u{1F7E8}" : "\u{1F7E5}"
1869
- })),
1870
- raw: data
1871
- };
1872
- }
1873
- });
1874
- }
1875
- function getSpkWalletQueryOptions(username) {
1876
- return queryOptions({
1877
- queryKey: ["assets", "spk", "wallet", username],
1878
- queryFn: async () => {
1879
- if (!username) {
1880
- throw new Error("[SDK][Wallets][SPK] \u2013 username wasn't provided");
1881
- }
1882
- return getSpkWallet(username);
1883
- },
1884
- enabled: !!username,
1885
- staleTime: 6e4,
1886
- refetchInterval: 9e4
1887
- });
1888
- }
1889
-
1890
- // src/modules/assets/spk/queries/get-larynx-asset-general-info-query-options.ts
1891
- function format(value) {
1892
- return value.toFixed(3);
1893
- }
1894
- function getLarynxAssetGeneralInfoQueryOptions(username) {
1895
- return queryOptions({
1896
- queryKey: ["assets", "larynx", "general-info", username],
1897
- staleTime: 6e4,
1898
- refetchInterval: 9e4,
1899
- queryFn: async () => {
1900
- await getQueryClient().prefetchQuery(getSpkWalletQueryOptions(username));
1901
- await getQueryClient().prefetchQuery(getSpkMarketsQueryOptions());
1902
- await getQueryClient().prefetchQuery(
1903
- getHiveAssetGeneralInfoQueryOptions(username)
1904
- );
1905
- const wallet = getQueryClient().getQueryData(
1906
- getSpkWalletQueryOptions(username).queryKey
1907
- );
1908
- const market = getQueryClient().getQueryData(
1909
- getSpkMarketsQueryOptions().queryKey
1910
- );
1911
- const hiveAsset = getQueryClient().getQueryData(
1912
- getHiveAssetGeneralInfoQueryOptions(username).queryKey
1913
- );
1914
- if (!wallet || !market) {
1915
- return {
1916
- name: "LARYNX",
1917
- title: "SPK Network / LARYNX",
1918
- price: 1,
1919
- accountBalance: 0
1920
- };
1921
- }
1922
- const price = +format(
1923
- wallet.balance / 1e3 * +wallet.tick * (hiveAsset?.price ?? 0)
1924
- );
1925
- const accountBalance = +format(wallet.balance / 1e3);
1926
- return {
1927
- name: "LARYNX",
1928
- layer: "SPK",
1929
- title: "LARYNX",
1930
- price: price / accountBalance,
1931
- accountBalance
1932
- };
1933
- }
1934
- });
1935
- }
1936
- function format2(value) {
1937
- return value.toFixed(3);
1938
- }
1939
- function getSpkAssetGeneralInfoQueryOptions(username) {
1940
- return queryOptions({
1941
- queryKey: ["assets", "spk", "general-info", username],
1942
- staleTime: 6e4,
1943
- refetchInterval: 9e4,
1944
- queryFn: async () => {
1945
- await getQueryClient().prefetchQuery(getSpkWalletQueryOptions(username));
1946
- await getQueryClient().prefetchQuery(getSpkMarketsQueryOptions());
1947
- await getQueryClient().prefetchQuery(
1948
- getHiveAssetGeneralInfoQueryOptions(username)
1949
- );
1950
- const wallet = getQueryClient().getQueryData(
1951
- getSpkWalletQueryOptions(username).queryKey
1952
- );
1953
- const market = getQueryClient().getQueryData(
1954
- getSpkMarketsQueryOptions().queryKey
1955
- );
1956
- const hiveAsset = getQueryClient().getQueryData(
1957
- getHiveAssetGeneralInfoQueryOptions(username).queryKey
1958
- );
1959
- if (!wallet || !market) {
1960
- return {
1961
- name: "SPK",
1962
- layer: "SPK",
1963
- title: "SPK Network",
1964
- price: 1,
1965
- accountBalance: 0
1966
- };
1967
- }
1968
- const price = +format2(
1969
- (wallet.gov + wallet.spk) / 1e3 * +wallet.tick * (hiveAsset?.price ?? 0)
1970
- );
1971
- const accountBalance = +format2(
1972
- (wallet.spk + rewardSpk(
1973
- wallet,
1974
- market.raw.stats || {
1975
- spk_rate_lgov: "0.001",
1976
- spk_rate_lpow: format2(
1977
- parseFloat(market.raw.stats.spk_rate_lpow) * 100
1978
- ),
1979
- spk_rate_ldel: format2(
1980
- parseFloat(market.raw.stats.spk_rate_ldel) * 100
1981
- )
1982
- }
1983
- )) / 1e3
1984
- );
1985
- return {
1986
- name: "SPK",
1987
- layer: "SPK",
1988
- title: "SPK Network",
1989
- price: price / accountBalance,
1990
- accountBalance
1991
- };
1992
- }
1993
- });
1994
- }
1995
- function format3(value) {
1996
- return value.toFixed(3);
1997
- }
1998
- function getLarynxPowerAssetGeneralInfoQueryOptions(username) {
1999
- return queryOptions({
2000
- queryKey: ["assets", "larynx-power", "general-info", username],
2001
- staleTime: 6e4,
2002
- refetchInterval: 9e4,
2003
- queryFn: async () => {
2004
- await getQueryClient().prefetchQuery(getSpkWalletQueryOptions(username));
2005
- await getQueryClient().prefetchQuery(getSpkMarketsQueryOptions());
2006
- await getQueryClient().prefetchQuery(
2007
- getHiveAssetGeneralInfoQueryOptions(username)
2008
- );
2009
- const wallet = getQueryClient().getQueryData(
2010
- getSpkWalletQueryOptions(username).queryKey
2011
- );
2012
- const market = getQueryClient().getQueryData(
2013
- getSpkMarketsQueryOptions().queryKey
2014
- );
2015
- const hiveAsset = getQueryClient().getQueryData(
2016
- getHiveAssetGeneralInfoQueryOptions(username).queryKey
2017
- );
2018
- if (!wallet || !market) {
2019
- return {
2020
- name: "LP",
2021
- title: "SPK Network / LARYNX Power",
2022
- price: 1,
2023
- accountBalance: 0
2024
- };
2025
- }
2026
- const price = +format3(
2027
- wallet.poweredUp / 1e3 * +wallet.tick * (hiveAsset?.price ?? 0)
2028
- );
2029
- const accountBalance = +format3(wallet.poweredUp / 1e3);
2030
- return {
2031
- name: "LP",
2032
- title: "LARYNX Power",
2033
- layer: "SPK",
2034
- price: price / accountBalance,
2035
- accountBalance,
2036
- parts: [
2037
- {
2038
- name: "delegating",
2039
- balance: wallet.granting?.t ? +format3(wallet.granting.t / 1e3) : 0
2040
- },
2041
- {
2042
- name: "recieved",
2043
- balance: wallet.granted?.t ? +format3(wallet.granted.t / 1e3) : 0
2044
- }
2045
- ]
2046
- };
2047
- }
2048
- });
2049
- }
2050
- function getAllHiveEngineTokensQueryOptions(account, symbol) {
2051
- return queryOptions({
2052
- queryKey: ["assets", "hive-engine", "all-tokens", account, symbol],
2053
- queryFn: async () => {
2054
- return getHiveEngineTokensMarket(account, symbol);
2055
- }
2056
- });
2057
- }
2058
- function formattedNumber(value, options2 = void 0) {
2059
- let opts = {
2060
- fractionDigits: 3,
2061
- prefix: "",
2062
- suffix: ""
2063
- };
2064
- if (options2) {
2065
- opts = { ...opts, ...options2 };
2066
- }
2067
- const { fractionDigits, prefix, suffix } = opts;
2068
- let format4 = "0,0";
2069
- if (fractionDigits) {
2070
- format4 += "." + "0".repeat(fractionDigits);
2071
- }
2072
- let out = "";
2073
- if (prefix) out += prefix + " ";
2074
- const av = Math.abs(parseFloat(value.toString())) < 1e-4 ? 0 : value;
2075
- out += numeral(av).format(format4);
2076
- if (suffix) out += " " + suffix;
2077
- return out;
2078
- }
2079
-
2080
- // src/modules/assets/hive-engine/utils/hive-engine-token.ts
2081
- var HiveEngineToken = class {
2082
- constructor(props) {
2083
- __publicField(this, "symbol");
2084
- __publicField(this, "name");
2085
- __publicField(this, "icon");
2086
- __publicField(this, "precision");
2087
- __publicField(this, "stakingEnabled");
2088
- __publicField(this, "delegationEnabled");
2089
- __publicField(this, "balance");
2090
- __publicField(this, "stake");
2091
- __publicField(this, "stakedBalance");
2092
- __publicField(this, "delegationsIn");
2093
- __publicField(this, "delegationsOut");
2094
- __publicField(this, "usdValue");
2095
- __publicField(this, "hasDelegations", () => {
2096
- if (!this.delegationEnabled) {
2097
- return false;
2098
- }
2099
- return this.delegationsIn > 0 && this.delegationsOut > 0;
2100
- });
2101
- __publicField(this, "delegations", () => {
2102
- if (!this.hasDelegations()) {
2103
- return "";
2104
- }
2105
- return `(${formattedNumber(this.stake, {
2106
- fractionDigits: this.precision
2107
- })} + ${formattedNumber(this.delegationsIn, {
2108
- fractionDigits: this.precision
2109
- })} - ${formattedNumber(this.delegationsOut, {
2110
- fractionDigits: this.precision
2111
- })})`;
2112
- });
2113
- __publicField(this, "staked", () => {
2114
- if (!this.stakingEnabled) {
2115
- return "-";
2116
- }
2117
- if (this.stakedBalance < 1e-4) {
2118
- return this.stakedBalance.toString();
2119
- }
2120
- return formattedNumber(this.stakedBalance, {
2121
- fractionDigits: this.precision
2122
- });
2123
- });
2124
- __publicField(this, "balanced", () => {
2125
- if (this.balance < 1e-4) {
2126
- return this.balance.toString();
2127
- }
2128
- return formattedNumber(this.balance, { fractionDigits: this.precision });
2129
- });
2130
- this.symbol = props.symbol;
2131
- this.name = props.name || "";
2132
- this.icon = props.icon || "";
2133
- this.precision = props.precision || 0;
2134
- this.stakingEnabled = props.stakingEnabled || false;
2135
- this.delegationEnabled = props.delegationEnabled || false;
2136
- this.balance = parseFloat(props.balance) || 0;
2137
- this.stake = parseFloat(props.stake) || 0;
2138
- this.delegationsIn = parseFloat(props.delegationsIn) || 0;
2139
- this.delegationsOut = parseFloat(props.delegationsOut) || 0;
2140
- this.stakedBalance = this.stake + this.delegationsIn - this.delegationsOut;
2141
- this.usdValue = props.usdValue;
2142
- }
2143
- };
2144
-
2145
- // src/modules/assets/hive-engine/queries/get-hive-engine-balances-with-usd-query-options.ts
2146
- function getHiveEngineBalancesWithUsdQueryOptions(account, dynamicProps, allTokens) {
2147
- return queryOptions({
2148
- queryKey: [
2149
- "assets",
2150
- "hive-engine",
2151
- "balances-with-usd",
2152
- account,
2153
- dynamicProps,
2154
- allTokens
2155
- ],
2156
- queryFn: async () => {
2157
- if (!account) {
2158
- throw new Error("[HiveEngine] No account in a balances query");
2159
- }
2160
- const balances = await getHiveEngineTokensBalances(account);
2161
- const tokens = await getHiveEngineTokensMetadata(
2162
- balances.map((t) => t.symbol)
2163
- );
2164
- const pricePerHive = dynamicProps ? dynamicProps.base / dynamicProps.quote : 0;
2165
- const metrics = Array.isArray(
2166
- allTokens
2167
- ) ? allTokens : [];
2168
- return balances.map((balance) => {
2169
- const token = tokens.find((t) => t.symbol === balance.symbol);
2170
- let tokenMetadata;
2171
- if (token?.metadata) {
2172
- try {
2173
- tokenMetadata = JSON.parse(token.metadata);
2174
- } catch {
2175
- tokenMetadata = void 0;
2176
- }
2177
- }
2178
- const metric = metrics.find((m) => m.symbol === balance.symbol);
2179
- const lastPrice = Number(metric?.lastPrice ?? "0");
2180
- const balanceAmount = Number(balance.balance);
2181
- const usdValue = balance.symbol === "SWAP.HIVE" ? pricePerHive * balanceAmount : lastPrice === 0 ? 0 : Number(
2182
- (lastPrice * pricePerHive * balanceAmount).toFixed(10)
2183
- );
2184
- return new HiveEngineToken({
2185
- symbol: balance.symbol,
2186
- name: token?.name ?? balance.symbol,
2187
- icon: tokenMetadata?.icon ?? "",
2188
- precision: token?.precision ?? 0,
2189
- stakingEnabled: token?.stakingEnabled ?? false,
2190
- delegationEnabled: token?.delegationEnabled ?? false,
2191
- balance: balance.balance,
2192
- stake: balance.stake,
2193
- delegationsIn: balance.delegationsIn,
2194
- delegationsOut: balance.delegationsOut,
2195
- usdValue
2196
- });
2197
- });
2198
- },
2199
- enabled: !!account
2200
- });
2201
- }
2202
- function getHiveEngineTokensMetadataQueryOptions(tokens) {
2203
- return queryOptions({
2204
- queryKey: ["assets", "hive-engine", "metadata-list", tokens],
2205
- staleTime: 6e4,
2206
- refetchInterval: 9e4,
2207
- queryFn: async () => {
2208
- return getHiveEngineTokensMetadata(tokens);
2209
- }
2210
- });
2211
- }
2212
- function getHiveEngineTokensBalancesQueryOptions(username) {
2213
- return queryOptions({
2214
- queryKey: ["assets", "hive-engine", "balances", username],
2215
- staleTime: 6e4,
2216
- refetchInterval: 9e4,
2217
- queryFn: async () => {
2218
- return getHiveEngineTokensBalances(username);
2219
- }
2220
- });
2221
- }
2222
- function getHiveEngineTokensMarketQueryOptions() {
2223
- return queryOptions({
2224
- queryKey: ["assets", "hive-engine", "markets"],
2225
- staleTime: 6e4,
2226
- refetchInterval: 9e4,
2227
- queryFn: async () => {
2228
- return getHiveEngineTokensMarket();
2229
- }
2230
- });
2231
- }
2232
-
2233
- // src/modules/assets/hive-engine/queries/get-hive-engine-token-general-info-query-options.ts
2234
- function getHiveEngineTokenGeneralInfoQueryOptions(username, symbol) {
2235
- return queryOptions({
2236
- queryKey: ["assets", "hive-engine", symbol, "general-info", username],
2237
- enabled: !!symbol && !!username,
2238
- staleTime: 6e4,
2239
- refetchInterval: 9e4,
2240
- queryFn: async () => {
2241
- if (!symbol || !username) {
2242
- throw new Error(
2243
- "[SDK][Wallets] \u2013 hive engine token or username missed"
2244
- );
2245
- }
2246
- const queryClient = getQueryClient();
2247
- const hiveQuery = getHiveAssetGeneralInfoQueryOptions(username);
2248
- await queryClient.prefetchQuery(hiveQuery);
2249
- const hiveData = queryClient.getQueryData(
2250
- hiveQuery.queryKey
2251
- );
2252
- const metadataList = await queryClient.ensureQueryData(
2253
- getHiveEngineTokensMetadataQueryOptions([symbol])
2254
- );
2255
- const balanceList = await queryClient.ensureQueryData(
2256
- getHiveEngineTokensBalancesQueryOptions(username)
2257
- );
2258
- const marketList = await queryClient.ensureQueryData(
2259
- getHiveEngineTokensMarketQueryOptions()
2260
- );
2261
- const metadata = metadataList?.find((i) => i.symbol === symbol);
2262
- const balance = balanceList?.find((i) => i.symbol === symbol);
2263
- const market = marketList?.find((i) => i.symbol === symbol);
2264
- const lastPrice = +(market?.lastPrice ?? "0");
2265
- const liquidBalance = parseFloat(balance?.balance ?? "0");
2266
- const stakedBalance = parseFloat(balance?.stake ?? "0");
2267
- const unstakingBalance = parseFloat(balance?.pendingUnstake ?? "0");
2268
- const parts = [
2269
- { name: "liquid", balance: liquidBalance },
2270
- { name: "staked", balance: stakedBalance }
2271
- ];
2272
- if (unstakingBalance > 0) {
2273
- parts.push({ name: "unstaking", balance: unstakingBalance });
2274
- }
2275
- return {
2276
- name: symbol,
2277
- title: metadata?.name ?? "",
2278
- price: lastPrice === 0 ? 0 : Number(lastPrice * (hiveData?.price ?? 0)),
2279
- accountBalance: liquidBalance + stakedBalance,
2280
- layer: "ENGINE",
2281
- parts
2282
- };
2283
- }
2284
- });
2285
- }
2286
- function getHiveEngineTokenTransactionsQueryOptions(username, symbol, limit = 20) {
2287
- return infiniteQueryOptions({
2288
- queryKey: ["assets", "hive-engine", symbol, "transactions", username],
2289
- enabled: !!symbol && !!username,
2290
- initialPageParam: 0,
2291
- getNextPageParam: (lastPage) => (lastPage?.length ?? 0) + limit,
2292
- queryFn: async ({ pageParam }) => {
2293
- if (!symbol || !username) {
2294
- throw new Error(
2295
- "[SDK][Wallets] \u2013 hive engine token or username missed"
2296
- );
2297
- }
2298
- return getHiveEngineTokenTransactions(
2299
- username,
2300
- symbol,
2301
- limit,
2302
- pageParam
2303
- );
2304
- }
2305
- });
2306
- }
2307
- function getHiveEngineTokensMetricsQueryOptions(symbol, interval = "daily") {
2308
- return queryOptions({
2309
- queryKey: ["assets", "hive-engine", symbol],
2310
- staleTime: 6e4,
2311
- refetchInterval: 9e4,
2312
- queryFn: async () => {
2313
- return getHiveEngineTokenMetrics(symbol, interval);
2314
- }
2315
- });
2316
- }
2317
- function getHiveEngineUnclaimedRewardsQueryOptions(username) {
2318
- return queryOptions({
2319
- queryKey: ["assets", "hive-engine", "unclaimed", username],
2320
- staleTime: 6e4,
2321
- refetchInterval: 9e4,
2322
- enabled: !!username,
2323
- queryFn: async () => {
2324
- try {
2325
- const data = await getHiveEngineUnclaimedRewards(
2326
- username
2327
- );
2328
- return Object.values(data).filter(
2329
- ({ pending_token }) => pending_token > 0
2330
- );
2331
- } catch (e) {
2332
- return [];
2333
- }
2334
- }
2335
- });
2336
- }
2337
-
2338
- // src/modules/assets/hive-engine/mutations/broadcast-hive-engine-operation.ts
2339
- async function broadcastHiveEngineOperation(payload, operation, auth) {
2340
- if (payload.type === "keychain") {
2341
- if (auth?.broadcast) {
2342
- return auth.broadcast([operation], "active");
2343
- }
2344
- return broadcastWithKeychainFallback(payload.from, [operation], "Active");
2345
- }
2346
- if (payload.type === "hiveauth") {
2347
- if (auth?.broadcast) {
2348
- return auth.broadcast([operation], "active");
2349
- }
2350
- return broadcastWithWalletHiveAuth(payload.from, [operation], "active");
2351
- }
2352
- throw new Error("[SDK][Wallets] \u2013 missing broadcaster");
2353
- }
2354
-
2355
- // src/modules/assets/hive-engine/mutations/delegate.ts
2356
- async function delegateEngineToken(payload, auth) {
2357
- const parsedAsset = parseAsset(payload.amount);
2358
- const quantity = parsedAsset.amount.toString();
2359
- const operation = [
2360
- "custom_json",
2361
- {
2362
- id: "ssc-mainnet-hive",
2363
- required_auths: [payload.from],
2364
- required_posting_auths: [],
2365
- json: JSON.stringify({
2366
- contractName: "tokens",
2367
- contractAction: "delegate",
2368
- contractPayload: {
2369
- symbol: payload.asset,
2370
- to: payload.to,
2371
- quantity
2372
- }
2373
- })
2374
- }
2375
- ];
2376
- if (payload.type === "key" && "key" in payload) {
2377
- const { key, type, ...params } = payload;
2378
- const op = {
2379
- id: "ssc-mainnet-hive",
2380
- json: JSON.stringify({
2381
- contractName: "tokens",
2382
- contractAction: "delegate",
2383
- contractPayload: {
2384
- symbol: params.asset,
2385
- to: params.to,
2386
- quantity
2387
- }
2388
- }),
2389
- required_auths: [params.from],
2390
- required_posting_auths: []
2391
- };
2392
- return CONFIG.hiveClient.broadcast.json(op, key);
2393
- } else if (payload.type === "keychain" || payload.type === "hiveauth") {
2394
- return broadcastHiveEngineOperation(payload, operation, auth);
2395
- } else {
2396
- return hs.sendOperation(
2397
- operation,
2398
- { callback: `https://ecency.com/@${payload.from}/wallet` },
2399
- () => {
2400
- }
2401
- );
2402
- }
2403
- }
2404
- async function undelegateEngineToken(payload, auth) {
2405
- const parsedAsset = parseAsset(payload.amount);
2406
- const quantity = parsedAsset.amount.toString();
2407
- const operation = [
2408
- "custom_json",
2409
- {
2410
- id: "ssc-mainnet-hive",
2411
- required_auths: [payload.from],
2412
- required_posting_auths: [],
2413
- json: JSON.stringify({
2414
- contractName: "tokens",
2415
- contractAction: "undelegate",
2416
- contractPayload: {
2417
- symbol: payload.asset,
2418
- from: payload.to,
2419
- quantity
2420
- }
2421
- })
2422
- }
2423
- ];
2424
- if (payload.type === "key" && "key" in payload) {
2425
- const { key, type, ...params } = payload;
2426
- const op = {
2427
- id: "ssc-mainnet-hive",
2428
- json: JSON.stringify({
2429
- contractName: "tokens",
2430
- contractAction: "undelegate",
2431
- contractPayload: {
2432
- symbol: params.asset,
2433
- from: params.to,
2434
- quantity
2435
- }
2436
- }),
2437
- required_auths: [params.from],
2438
- required_posting_auths: []
2439
- };
2440
- return CONFIG.hiveClient.broadcast.json(op, key);
2441
- } else if (payload.type === "keychain" || payload.type === "hiveauth") {
2442
- return broadcastHiveEngineOperation(payload, operation, auth);
2443
- } else {
2444
- return hs.sendOperation(
2445
- operation,
2446
- { callback: `https://ecency.com/@${payload.from}/wallet` },
2447
- () => {
2448
- }
2449
- );
2450
- }
2451
- }
2452
- async function stakeEngineToken(payload, auth) {
2453
- const parsedAsset = parseAsset(payload.amount);
2454
- const quantity = parsedAsset.amount.toString();
2455
- const operation = [
2456
- "custom_json",
2457
- {
2458
- id: "ssc-mainnet-hive",
2459
- required_auths: [payload.from],
2460
- required_posting_auths: [],
2461
- json: JSON.stringify({
2462
- contractName: "tokens",
2463
- contractAction: "stake",
2464
- contractPayload: {
2465
- symbol: payload.asset,
2466
- to: payload.to,
2467
- quantity
2468
- }
2469
- })
2470
- }
2471
- ];
2472
- if (payload.type === "key" && "key" in payload) {
2473
- const { key, type, ...params } = payload;
2474
- const op = {
2475
- id: "ssc-mainnet-hive",
2476
- json: JSON.stringify({
2477
- contractName: "tokens",
2478
- contractAction: "stake",
2479
- contractPayload: {
2480
- symbol: params.asset,
2481
- to: params.to,
2482
- quantity
2483
- }
2484
- }),
2485
- required_auths: [params.from],
2486
- required_posting_auths: []
2487
- };
2488
- return CONFIG.hiveClient.broadcast.json(op, key);
2489
- } else if (payload.type === "keychain" || payload.type === "hiveauth") {
2490
- return broadcastHiveEngineOperation(payload, operation, auth);
2491
- } else {
2492
- return hs.sendOperation(
2493
- operation,
2494
- { callback: `https://ecency.com/@${payload.from}/wallet` },
2495
- () => {
2496
- }
2497
- );
2498
- }
2499
- }
2500
- async function unstakeEngineToken(payload, auth) {
2501
- const parsedAsset = parseAsset(payload.amount);
2502
- const quantity = parsedAsset.amount.toString();
2503
- const operation = [
2504
- "custom_json",
2505
- {
2506
- id: "ssc-mainnet-hive",
2507
- required_auths: [payload.from],
2508
- required_posting_auths: [],
2509
- json: JSON.stringify({
2510
- contractName: "tokens",
2511
- contractAction: "unstake",
2512
- contractPayload: {
2513
- symbol: payload.asset,
2514
- to: payload.to,
2515
- quantity
2516
- }
2517
- })
2518
- }
2519
- ];
2520
- if (payload.type === "key" && "key" in payload) {
2521
- const { key, type, ...params } = payload;
2522
- const op = {
2523
- id: "ssc-mainnet-hive",
2524
- json: JSON.stringify({
2525
- contractName: "tokens",
2526
- contractAction: "unstake",
2527
- contractPayload: {
2528
- symbol: params.asset,
2529
- to: params.to,
2530
- quantity
2531
- }
2532
- }),
2533
- required_auths: [params.from],
2534
- required_posting_auths: []
2535
- };
2536
- return CONFIG.hiveClient.broadcast.json(op, key);
2537
- } else if (payload.type === "keychain" || payload.type === "hiveauth") {
2538
- return broadcastHiveEngineOperation(payload, operation, auth);
2539
- } else {
2540
- return hs.sendOperation(
2541
- operation,
2542
- { callback: `https://ecency.com/@${payload.from}/wallet` },
2543
- () => {
2544
- }
2545
- );
2546
- }
2547
- }
2548
- async function transferEngineToken(payload, auth) {
2549
- const parsedAsset = parseAsset(payload.amount);
2550
- const quantity = parsedAsset.amount.toString();
2551
- const operation = [
2552
- "custom_json",
2553
- {
2554
- id: "ssc-mainnet-hive",
2555
- required_auths: [payload.from],
2556
- required_posting_auths: [],
2557
- json: JSON.stringify({
2558
- contractName: "tokens",
2559
- contractAction: "transfer",
2560
- contractPayload: {
2561
- symbol: payload.asset,
2562
- to: payload.to,
2563
- quantity,
2564
- memo: payload.memo
2565
- }
2566
- })
2567
- }
2568
- ];
2569
- if (payload.type === "key" && "key" in payload) {
2570
- const { key, type, ...params } = payload;
2571
- const op = {
2572
- id: "ssc-mainnet-hive",
2573
- json: JSON.stringify({
2574
- contractName: "tokens",
2575
- contractAction: "transfer",
2576
- contractPayload: {
2577
- symbol: params.asset,
2578
- to: params.to,
2579
- quantity,
2580
- memo: params.memo
2581
- }
2582
- }),
2583
- required_auths: [params.from],
2584
- required_posting_auths: []
2585
- };
2586
- return CONFIG.hiveClient.broadcast.json(op, key);
2587
- } else if (payload.type === "keychain" || payload.type === "hiveauth") {
2588
- return broadcastHiveEngineOperation(payload, operation, auth);
2589
- } else {
2590
- return hs.sendOperation(
2591
- operation,
2592
- { callback: `https://ecency.com/@${payload.from}/wallet` },
2593
- () => {
2594
- }
2595
- );
2596
- }
2597
- }
2598
- var ENGINE_CONTRACT_ID = "ssc-mainnet-hive";
2599
- function buildEngineOrderPayload(action, symbol, quantity, price) {
2600
- return {
2601
- contractName: "market",
2602
- contractAction: action,
2603
- contractPayload: { symbol, quantity, price }
2604
- };
2605
- }
2606
- function buildEngineCancelPayload(type, orderId) {
2607
- return {
2608
- contractName: "market",
2609
- contractAction: "cancel",
2610
- contractPayload: { type, id: orderId }
2611
- };
2612
- }
2613
- function buildEngineOperation(account, payload) {
2614
- return {
2615
- id: ENGINE_CONTRACT_ID,
2616
- required_auths: [account],
2617
- required_posting_auths: [],
2618
- json: JSON.stringify(payload)
2619
- };
2620
- }
2621
- async function broadcastEngineOperation(account, payload, options2) {
2622
- const operation = buildEngineOperation(account, payload);
2623
- const opTuple = ["custom_json", operation];
2624
- switch (options2?.method) {
2625
- case "key": {
2626
- if (!options2.key) {
2627
- throw new Error("[SDK][Wallets] \u2013 active key is required");
2628
- }
2629
- return CONFIG.hiveClient.broadcast.json(operation, options2.key);
2630
- }
2631
- case "keychain": {
2632
- if (options2.auth?.broadcast) {
2633
- return options2.auth.broadcast([opTuple], "active");
2634
- }
2635
- return broadcastWithKeychainFallback(account, [opTuple], "Active");
2636
- }
2637
- case "hiveauth": {
2638
- if (options2.auth?.broadcast) {
2639
- return options2.auth.broadcast([opTuple], "active");
2640
- }
2641
- return broadcastWithWalletHiveAuth(account, [opTuple], "active");
2642
- }
2643
- case "hivesigner":
2644
- return hs.sendOperation(
2645
- opTuple,
2646
- { callback: `https://ecency.com/@${account}/wallet/engine` },
2647
- () => {
2648
- }
2649
- );
2650
- default:
2651
- throw new Error("[SDK][Wallets] \u2013 broadcast method is required");
2652
- }
2653
- }
2654
- var placeHiveEngineBuyOrder = async (account, symbol, quantity, price, options2) => broadcastEngineOperation(
2655
- account,
2656
- buildEngineOrderPayload("buy", symbol, quantity, price),
2657
- options2
2658
- );
2659
- var placeHiveEngineSellOrder = async (account, symbol, quantity, price, options2) => broadcastEngineOperation(
2660
- account,
2661
- buildEngineOrderPayload("sell", symbol, quantity, price),
2662
- options2
2663
- );
2664
- var cancelHiveEngineOrder = async (account, type, orderId, options2) => broadcastEngineOperation(
2665
- account,
2666
- buildEngineCancelPayload(type, orderId),
2667
- options2
2668
- );
2669
- async function claimHiveEngineRewards(payload, auth) {
2670
- const json = JSON.stringify(payload.tokens.map((symbol) => ({ symbol })));
2671
- const operation = [
2672
- "custom_json",
2673
- {
2674
- id: "scot_claim_token",
2675
- required_auths: [],
2676
- required_posting_auths: [payload.account],
2677
- json
2678
- }
2679
- ];
2680
- if (payload.type === "key" && "key" in payload) {
2681
- return CONFIG.hiveClient.broadcast.sendOperations([operation], payload.key);
2682
- }
2683
- if (auth?.broadcast) {
2684
- return auth.broadcast([operation], "posting");
2685
- }
2686
- if (auth?.postingKey) {
2687
- const key = PrivateKey.fromString(auth.postingKey);
2688
- return CONFIG.hiveClient.broadcast.sendOperations([operation], key);
2689
- }
2690
- if (auth?.accessToken) {
2691
- const client = new hs.Client({ accessToken: auth.accessToken });
2692
- return client.broadcast([operation]);
2693
- }
2694
- if (payload.type === "hiveauth") {
2695
- return broadcastWithWalletHiveAuth(payload.account, [operation], "posting");
2696
- }
2697
- throw new Error("[SDK][Wallets] \u2013 cannot broadcast without auth context");
2698
- }
2699
- function getPointsQueryOptions(username) {
2700
- return queryOptions({
2701
- queryKey: ["assets", "points", username],
2702
- queryFn: async () => {
2703
- if (!username) {
2704
- throw new Error(
2705
- "[SDK][Wallets][Assets][Points][Query] \u2013 username wasn`t provided"
2706
- );
2707
- }
2708
- const response = await fetch(
2709
- CONFIG.privateApiHost + "/private-api/points",
2710
- {
2711
- method: "POST",
2712
- headers: {
2713
- "Content-Type": "application/json"
2714
- },
2715
- body: JSON.stringify({ username })
2716
- }
2717
- );
2718
- const points = await response.json();
2719
- return {
2720
- points: points.points,
2721
- uPoints: points.unclaimed_points
2722
- };
2723
- },
2724
- staleTime: 6e4,
2725
- refetchInterval: 9e4,
2726
- refetchOnMount: true,
2727
- enabled: !!username
2728
- });
2729
- }
2730
- function getPointsAssetGeneralInfoQueryOptions(username) {
2731
- return queryOptions({
2732
- queryKey: ["assets", "points", "general-info", username],
2733
- staleTime: 6e4,
2734
- refetchInterval: 9e4,
2735
- queryFn: async () => {
2736
- await getQueryClient().prefetchQuery(getPointsQueryOptions(username));
2737
- const data = getQueryClient().getQueryData(
2738
- getPointsQueryOptions(username).queryKey
2739
- );
2740
- return {
2741
- name: "POINTS",
2742
- title: "Ecency Points",
2743
- price: 2e-3,
2744
- accountBalance: +data?.points
2745
- };
2746
- }
2747
- });
2748
- }
2749
- function getPointsAssetTransactionsQueryOptions(username, type) {
2750
- return queryOptions({
2751
- queryKey: ["assets", "points", "transactions", username, type],
2752
- queryFn: async () => {
2753
- const response = await fetch(
2754
- `${CONFIG.privateApiHost}/private-api/point-list`,
2755
- {
2756
- method: "POST",
2757
- headers: {
2758
- "Content-Type": "application/json"
2759
- },
2760
- body: JSON.stringify({
2761
- username,
2762
- type: type ?? 0
2763
- })
2764
- }
2765
- );
2766
- const data = await response.json();
2767
- return data.map(({ created, type: type2, amount, id, sender, receiver, memo }) => ({
2768
- created: new Date(created),
2769
- type: type2,
2770
- results: [
2771
- {
2772
- amount: parseFloat(amount),
2773
- asset: "POINTS"
2774
- }
2775
- ],
2776
- id,
2777
- from: sender ?? void 0,
2778
- to: receiver ?? void 0,
2779
- memo: memo ?? void 0
2780
- }));
2781
- }
2782
- });
2783
- }
2784
-
2785
- // src/modules/assets/points/mutations/claim-points.ts
2786
- function useClaimPoints(username, accessToken, onSuccess, onError) {
2787
- const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(
2788
- username,
2789
- "points-claimed"
2790
- );
2791
- const fetchApi = getBoundFetch();
2792
- return useMutation({
2793
- mutationFn: async () => {
2794
- if (!username) {
2795
- throw new Error(
2796
- "[SDK][Wallets][Assets][Points][Claim] \u2013 username wasn't provided"
2797
- );
2798
- }
2799
- if (!accessToken) {
2800
- throw new Error(
2801
- "[SDK][Wallets][Assets][Points][Claim] \u2013 access token wasn't found"
2802
- );
2803
- }
2804
- const response = await fetchApi(
2805
- CONFIG.privateApiHost + "/private-api/points-claim",
2806
- {
2807
- method: "POST",
2808
- headers: {
2809
- "Content-Type": "application/json"
2810
- },
2811
- body: JSON.stringify({ code: accessToken })
2812
- }
2813
- );
2814
- if (!response.ok) {
2815
- const body = await response.text();
2816
- if (response.status === 406) {
2817
- try {
2818
- return JSON.parse(body);
2819
- } catch {
2820
- return { message: body, code: response.status };
2821
- }
2822
- }
2823
- throw new Error(
2824
- `[SDK][Wallets][Assets][Points][Claim] \u2013 failed with status ${response.status}${body ? `: ${body}` : ""}`
2825
- );
2826
- }
2827
- return response.json();
2828
- },
2829
- onError,
2830
- onSuccess: () => {
2831
- recordActivity();
2832
- CONFIG.queryClient.setQueryData(
2833
- getPointsQueryOptions(username).queryKey,
2834
- (data) => {
2835
- if (!data) {
2836
- return data;
2837
- }
2838
- return {
2839
- points: (parseFloat(data.points) + parseFloat(data.uPoints)).toFixed(3),
2840
- uPoints: "0"
2841
- };
2842
- }
2843
- );
2844
- onSuccess?.();
2845
- }
2846
- });
2847
- }
2848
- async function transferPoint({
2849
- from,
2850
- to,
2851
- amount,
2852
- memo,
2853
- type,
2854
- ...payload
2855
- }, auth) {
2856
- const op = [
2857
- "custom_json",
2858
- {
2859
- id: "ecency_point_transfer",
2860
- json: JSON.stringify({
2861
- sender: from,
2862
- receiver: to,
2863
- amount: amount.replace("POINTS", "POINT"),
2864
- memo
2865
- }),
2866
- required_auths: [from],
2867
- required_posting_auths: []
2868
- }
2869
- ];
2870
- if (type === "key" && "key" in payload) {
2871
- const { key } = payload;
2872
- return CONFIG.hiveClient.broadcast.sendOperations([op], key);
2873
- }
2874
- if (type === "keychain") {
2875
- if (auth?.broadcast) {
2876
- return auth.broadcast([op], "active");
2877
- }
2878
- throw new Error("[SDK][Wallets] \u2013 missing broadcaster");
2879
- }
2880
- if (type === "hiveauth") {
2881
- if (auth?.broadcast) {
2882
- return auth.broadcast([op], "active");
2883
- }
2884
- return broadcastWithWalletHiveAuth(from, [op], "active");
2885
- }
2886
- return hs.sendOperation(op, { callback: `https://ecency.com/@${from}/wallet` }, () => {
2887
- });
2888
- }
2889
-
2890
- // src/modules/assets/points/types/point-transaction-type.ts
2891
- var PointTransactionType = /* @__PURE__ */ ((PointTransactionType2) => {
2892
- PointTransactionType2[PointTransactionType2["CHECKIN"] = 10] = "CHECKIN";
2893
- PointTransactionType2[PointTransactionType2["LOGIN"] = 20] = "LOGIN";
2894
- PointTransactionType2[PointTransactionType2["CHECKIN_EXTRA"] = 30] = "CHECKIN_EXTRA";
2895
- PointTransactionType2[PointTransactionType2["POST"] = 100] = "POST";
2896
- PointTransactionType2[PointTransactionType2["COMMENT"] = 110] = "COMMENT";
2897
- PointTransactionType2[PointTransactionType2["VOTE"] = 120] = "VOTE";
2898
- PointTransactionType2[PointTransactionType2["REBLOG"] = 130] = "REBLOG";
2899
- PointTransactionType2[PointTransactionType2["DELEGATION"] = 150] = "DELEGATION";
2900
- PointTransactionType2[PointTransactionType2["REFERRAL"] = 160] = "REFERRAL";
2901
- PointTransactionType2[PointTransactionType2["COMMUNITY"] = 170] = "COMMUNITY";
2902
- PointTransactionType2[PointTransactionType2["TRANSFER_SENT"] = 998] = "TRANSFER_SENT";
2903
- PointTransactionType2[PointTransactionType2["TRANSFER_INCOMING"] = 999] = "TRANSFER_INCOMING";
2904
- PointTransactionType2[PointTransactionType2["MINTED"] = 991] = "MINTED";
2905
- return PointTransactionType2;
2906
- })(PointTransactionType || {});
2907
582
  function createFallbackTokenMetadata(symbol) {
2908
583
  return {
2909
584
  issuer: "",
@@ -2975,11 +650,6 @@ function getAllTokensListQueryOptions(username) {
2975
650
  }
2976
651
  });
2977
652
  }
2978
- function getVisionPortfolioQueryOptions(username, currency = "usd") {
2979
- return getPortfolioQueryOptions(username, currency, true);
2980
- }
2981
-
2982
- // src/modules/wallets/queries/use-get-account-wallet-list-query.ts
2983
653
  function normalizeAccountTokens(tokens) {
2984
654
  if (Array.isArray(tokens)) {
2985
655
  return tokens.filter(Boolean);
@@ -3002,7 +672,7 @@ function getAccountWalletListQueryOptions(username, currency = "usd") {
3002
672
  queryKey: ["ecency-wallets", "list", username, currency],
3003
673
  enabled: !!username,
3004
674
  queryFn: async () => {
3005
- const portfolioQuery = getVisionPortfolioQueryOptions(username, currency);
675
+ const portfolioQuery = getPortfolioQueryOptions(username, currency, true);
3006
676
  const queryClient = getQueryClient();
3007
677
  const accountQuery = getAccountFullQueryOptions(username);
3008
678
  let account;
@@ -3056,561 +726,6 @@ function getAccountWalletListQueryOptions(username, currency = "usd") {
3056
726
  }
3057
727
  });
3058
728
  }
3059
-
3060
- // src/modules/assets/external/common/parse-private-api-balance.ts
3061
- function normalizeBalance2(balance) {
3062
- if (typeof balance === "number") {
3063
- if (!Number.isFinite(balance)) {
3064
- throw new Error("Private API returned a non-finite numeric balance");
3065
- }
3066
- return Math.trunc(balance).toString();
3067
- }
3068
- if (typeof balance === "string") {
3069
- const trimmed = balance.trim();
3070
- if (trimmed === "") {
3071
- throw new Error("Private API returned an empty balance string");
3072
- }
3073
- return trimmed;
3074
- }
3075
- throw new Error("Private API returned balance in an unexpected format");
3076
- }
3077
- function parsePrivateApiBalance2(result, expectedChain) {
3078
- if (!result || typeof result !== "object") {
3079
- throw new Error("Private API returned an unexpected response");
3080
- }
3081
- const { chain, balance, unit, raw, nodeId } = result;
3082
- if (typeof chain !== "string" || chain !== expectedChain) {
3083
- throw new Error("Private API response chain did not match request");
3084
- }
3085
- if (typeof unit !== "string" || unit.length === 0) {
3086
- throw new Error("Private API response is missing unit information");
3087
- }
3088
- if (balance === void 0 || balance === null) {
3089
- throw new Error("Private API response is missing balance information");
3090
- }
3091
- const balanceString = normalizeBalance2(balance);
3092
- let balanceBigInt;
3093
- try {
3094
- balanceBigInt = BigInt(balanceString);
3095
- } catch (error) {
3096
- throw new Error("Private API returned a balance that is not an integer");
3097
- }
3098
- return {
3099
- chain,
3100
- unit,
3101
- raw,
3102
- nodeId: typeof nodeId === "string" && nodeId.length > 0 ? nodeId : void 0,
3103
- balanceBigInt,
3104
- balanceString
3105
- };
3106
- }
3107
-
3108
- // src/modules/assets/external/apt/get-apt-asset-balance-query-options.ts
3109
- function getAptAssetBalanceQueryOptions(address) {
3110
- return queryOptions({
3111
- queryKey: ["assets", "apt", "balance", address],
3112
- queryFn: async () => {
3113
- const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/apt/${encodeURIComponent(
3114
- address
3115
- )}`;
3116
- try {
3117
- const response = await fetch(baseUrl);
3118
- if (!response.ok) {
3119
- throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
3120
- }
3121
- return +parsePrivateApiBalance2(await response.json(), "apt").balanceString;
3122
- } catch (error) {
3123
- console.error(error);
3124
- const response = await fetch(`${baseUrl}?provider=chainz`);
3125
- return +parsePrivateApiBalance2(await response.json(), "apt").balanceString;
3126
- }
3127
- }
3128
- });
3129
- }
3130
- async function getAddressFromAccount(username, tokenName) {
3131
- await CONFIG.queryClient.prefetchQuery(getAccountFullQueryOptions(username));
3132
- const account = CONFIG.queryClient.getQueryData(
3133
- getAccountFullQueryOptions(username).queryKey
3134
- );
3135
- const address = account?.profile?.tokens?.find((t) => t.symbol === tokenName)?.meta?.address;
3136
- if (!address) {
3137
- throw new Error(
3138
- "[SDK][Wallets] \u2013\xA0cannot fetch APT balance with empty adrress"
3139
- );
3140
- }
3141
- return address;
3142
- }
3143
-
3144
- // src/modules/assets/external/apt/get-apt-asset-general-info-query-options.ts
3145
- function getAptAssetGeneralInfoQueryOptions(username) {
3146
- return queryOptions({
3147
- queryKey: ["assets", "apt", "general-info", username],
3148
- staleTime: 6e4,
3149
- refetchInterval: 9e4,
3150
- queryFn: async () => {
3151
- const address = await getAddressFromAccount(username, "APT");
3152
- await CONFIG.queryClient.fetchQuery(
3153
- getAptAssetBalanceQueryOptions(address)
3154
- );
3155
- const accountBalance = (CONFIG.queryClient.getQueryData(
3156
- getAptAssetBalanceQueryOptions(address).queryKey
3157
- ) ?? 0) / 1e8;
3158
- await CONFIG.queryClient.prefetchQuery(
3159
- getTokenPriceQueryOptions("APT")
3160
- );
3161
- const price = CONFIG.queryClient.getQueryData(
3162
- getTokenPriceQueryOptions("APT").queryKey
3163
- ) ?? 0;
3164
- return {
3165
- name: "APT",
3166
- title: "Aptos",
3167
- price,
3168
- accountBalance
3169
- };
3170
- }
3171
- });
3172
- }
3173
- function getBnbAssetBalanceQueryOptions(address) {
3174
- return queryOptions({
3175
- queryKey: ["assets", "bnb", "balance", address],
3176
- queryFn: async () => {
3177
- const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/bnb/${encodeURIComponent(
3178
- address
3179
- )}`;
3180
- try {
3181
- const response = await fetch(baseUrl);
3182
- if (!response.ok) {
3183
- throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
3184
- }
3185
- return +parsePrivateApiBalance2(await response.json(), "bnb").balanceString;
3186
- } catch (error) {
3187
- console.error(error);
3188
- const response = await fetch(`${baseUrl}?provider=chainz`);
3189
- return +parsePrivateApiBalance2(await response.json(), "bnb").balanceString;
3190
- }
3191
- }
3192
- });
3193
- }
3194
-
3195
- // src/modules/assets/external/bnb/get-bnb-asset-general-info-query-options.ts
3196
- function getBnbAssetGeneralInfoQueryOptions(username) {
3197
- return queryOptions({
3198
- queryKey: ["assets", "bnb", "general-info", username],
3199
- staleTime: 6e4,
3200
- refetchInterval: 9e4,
3201
- queryFn: async () => {
3202
- const address = await getAddressFromAccount(username, "BNB");
3203
- await CONFIG.queryClient.fetchQuery(
3204
- getBnbAssetBalanceQueryOptions(address)
3205
- );
3206
- const accountBalance = (CONFIG.queryClient.getQueryData(
3207
- getBnbAssetBalanceQueryOptions(address).queryKey
3208
- ) ?? 0) / 1e18;
3209
- await CONFIG.queryClient.prefetchQuery(
3210
- getTokenPriceQueryOptions("BNB")
3211
- );
3212
- const price = CONFIG.queryClient.getQueryData(
3213
- getTokenPriceQueryOptions("BNB").queryKey
3214
- ) ?? 0;
3215
- return {
3216
- name: "BNB",
3217
- title: "Binance coin",
3218
- price,
3219
- accountBalance
3220
- };
3221
- }
3222
- });
3223
- }
3224
- function getBtcAssetBalanceQueryOptions(address) {
3225
- return queryOptions({
3226
- queryKey: ["assets", "btc", "balance", address],
3227
- queryFn: async () => {
3228
- const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/btc/${encodeURIComponent(
3229
- address
3230
- )}`;
3231
- try {
3232
- const response = await fetch(baseUrl);
3233
- if (!response.ok) {
3234
- throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
3235
- }
3236
- return +parsePrivateApiBalance2(await response.json(), "btc").balanceString;
3237
- } catch (error) {
3238
- console.error(error);
3239
- const response = await fetch(`${baseUrl}?provider=chainz`);
3240
- return +parsePrivateApiBalance2(await response.json(), "btc").balanceString;
3241
- }
3242
- }
3243
- });
3244
- }
3245
-
3246
- // src/modules/assets/external/btc/get-btc-asset-general-info-query-options.ts
3247
- function getBtcAssetGeneralInfoQueryOptions(username) {
3248
- return queryOptions({
3249
- queryKey: ["assets", "btc", "general-info", username],
3250
- staleTime: 6e4,
3251
- refetchInterval: 9e4,
3252
- queryFn: async () => {
3253
- const address = await getAddressFromAccount(username, "BTC");
3254
- await CONFIG.queryClient.fetchQuery(
3255
- getBtcAssetBalanceQueryOptions(address)
3256
- );
3257
- const accountBalance = (CONFIG.queryClient.getQueryData(
3258
- getBtcAssetBalanceQueryOptions(address).queryKey
3259
- ) ?? 0) / 1e8;
3260
- await CONFIG.queryClient.prefetchQuery(
3261
- getTokenPriceQueryOptions("BTC")
3262
- );
3263
- const price = CONFIG.queryClient.getQueryData(
3264
- getTokenPriceQueryOptions("BTC").queryKey
3265
- ) ?? 0;
3266
- return {
3267
- name: "BTC",
3268
- title: "Bitcoin",
3269
- price,
3270
- accountBalance
3271
- };
3272
- }
3273
- });
3274
- }
3275
- function getEthAssetBalanceQueryOptions(address) {
3276
- return queryOptions({
3277
- queryKey: ["assets", "eth", "balance", address],
3278
- queryFn: async () => {
3279
- const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/eth/${encodeURIComponent(
3280
- address
3281
- )}`;
3282
- try {
3283
- const response = await fetch(baseUrl);
3284
- if (!response.ok) {
3285
- throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
3286
- }
3287
- return +parsePrivateApiBalance2(await response.json(), "eth").balanceString;
3288
- } catch (error) {
3289
- console.error(error);
3290
- const response = await fetch(`${baseUrl}?provider=chainz`);
3291
- return +parsePrivateApiBalance2(await response.json(), "eth").balanceString;
3292
- }
3293
- }
3294
- });
3295
- }
3296
-
3297
- // src/modules/assets/external/eth/get-eth-asset-general-info-query-options.ts
3298
- function getEthAssetGeneralInfoQueryOptions(username) {
3299
- return queryOptions({
3300
- queryKey: ["assets", "eth", "general-info", username],
3301
- staleTime: 6e4,
3302
- refetchInterval: 9e4,
3303
- queryFn: async () => {
3304
- const address = await getAddressFromAccount(username, "ETH");
3305
- await CONFIG.queryClient.fetchQuery(
3306
- getEthAssetBalanceQueryOptions(address)
3307
- );
3308
- const accountBalance = (CONFIG.queryClient.getQueryData(
3309
- getEthAssetBalanceQueryOptions(address).queryKey
3310
- ) ?? 0) / 1e18;
3311
- await CONFIG.queryClient.prefetchQuery(
3312
- getTokenPriceQueryOptions("ETH")
3313
- );
3314
- const price = CONFIG.queryClient.getQueryData(
3315
- getTokenPriceQueryOptions("ETH").queryKey
3316
- ) ?? 0;
3317
- return {
3318
- name: "ETH",
3319
- title: "Ethereum",
3320
- price,
3321
- accountBalance
3322
- };
3323
- }
3324
- });
3325
- }
3326
- function getSolAssetBalanceQueryOptions(address) {
3327
- return queryOptions({
3328
- queryKey: ["assets", "sol", "balance", address],
3329
- queryFn: async () => {
3330
- const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/sol/${encodeURIComponent(
3331
- address
3332
- )}`;
3333
- try {
3334
- const response = await fetch(baseUrl);
3335
- if (!response.ok) {
3336
- throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
3337
- }
3338
- return +parsePrivateApiBalance2(await response.json(), "sol").balanceString;
3339
- } catch (error) {
3340
- console.error(error);
3341
- const response = await fetch(`${baseUrl}?provider=chainz`);
3342
- return +parsePrivateApiBalance2(await response.json(), "sol").balanceString;
3343
- }
3344
- }
3345
- });
3346
- }
3347
-
3348
- // src/modules/assets/external/sol/get-sol-asset-general-info-query-options.ts
3349
- function getSolAssetGeneralInfoQueryOptions(username) {
3350
- return queryOptions({
3351
- queryKey: ["assets", "sol", "general-info", username],
3352
- staleTime: 6e4,
3353
- refetchInterval: 9e4,
3354
- queryFn: async () => {
3355
- const address = await getAddressFromAccount(username, "SOL");
3356
- await CONFIG.queryClient.fetchQuery(
3357
- getSolAssetBalanceQueryOptions(address)
3358
- );
3359
- const accountBalance = (CONFIG.queryClient.getQueryData(
3360
- getSolAssetBalanceQueryOptions(address).queryKey
3361
- ) ?? 0) / 1e9;
3362
- await CONFIG.queryClient.prefetchQuery(
3363
- getTokenPriceQueryOptions("SOL")
3364
- );
3365
- const price = CONFIG.queryClient.getQueryData(
3366
- getTokenPriceQueryOptions("SOL").queryKey
3367
- ) ?? 0;
3368
- return {
3369
- name: "SOL",
3370
- title: "Solana",
3371
- price,
3372
- accountBalance
3373
- };
3374
- }
3375
- });
3376
- }
3377
- function getTonAssetBalanceQueryOptions(address) {
3378
- return queryOptions({
3379
- queryKey: ["assets", "ton", "balance", address],
3380
- queryFn: async () => {
3381
- const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/ton/${encodeURIComponent(
3382
- address
3383
- )}`;
3384
- try {
3385
- const response = await fetch(baseUrl);
3386
- if (!response.ok) {
3387
- throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
3388
- }
3389
- return +parsePrivateApiBalance2(await response.json(), "ton").balanceString;
3390
- } catch (error) {
3391
- console.error(error);
3392
- const response = await fetch(`${baseUrl}?provider=chainz`);
3393
- return +parsePrivateApiBalance2(await response.json(), "ton").balanceString;
3394
- }
3395
- }
3396
- });
3397
- }
3398
-
3399
- // src/modules/assets/external/ton/get-ton-asset-general-info-query-options.ts
3400
- function getTonAssetGeneralInfoQueryOptions(username) {
3401
- return queryOptions({
3402
- queryKey: ["assets", "ton", "general-info", username],
3403
- staleTime: 6e4,
3404
- refetchInterval: 9e4,
3405
- queryFn: async () => {
3406
- const address = await getAddressFromAccount(username, "TON");
3407
- await CONFIG.queryClient.fetchQuery(
3408
- getTonAssetBalanceQueryOptions(address)
3409
- );
3410
- const accountBalance = (CONFIG.queryClient.getQueryData(
3411
- getTonAssetBalanceQueryOptions(address).queryKey
3412
- ) ?? 0) / 1e9;
3413
- await CONFIG.queryClient.prefetchQuery(
3414
- getTokenPriceQueryOptions("TON")
3415
- );
3416
- const price = CONFIG.queryClient.getQueryData(
3417
- getTokenPriceQueryOptions("TON").queryKey
3418
- ) ?? 0;
3419
- return {
3420
- name: "TON",
3421
- title: "The open network",
3422
- price,
3423
- accountBalance
3424
- };
3425
- }
3426
- });
3427
- }
3428
- function getTronAssetBalanceQueryOptions(address) {
3429
- return queryOptions({
3430
- queryKey: ["assets", "tron", "balance", address],
3431
- queryFn: async () => {
3432
- const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/tron/${encodeURIComponent(
3433
- address
3434
- )}`;
3435
- try {
3436
- const response = await fetch(baseUrl);
3437
- if (!response.ok) {
3438
- throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
3439
- }
3440
- return +parsePrivateApiBalance2(await response.json(), "tron").balanceString;
3441
- } catch (error) {
3442
- console.error(error);
3443
- const response = await fetch(`${baseUrl}?provider=chainz`);
3444
- return +parsePrivateApiBalance2(await response.json(), "tron").balanceString;
3445
- }
3446
- }
3447
- });
3448
- }
3449
-
3450
- // src/modules/assets/external/tron/get-tron-asset-general-info-query-options.ts
3451
- function getTronAssetGeneralInfoQueryOptions(username) {
3452
- return queryOptions({
3453
- queryKey: ["assets", "tron", "general-info", username],
3454
- staleTime: 6e4,
3455
- refetchInterval: 9e4,
3456
- queryFn: async () => {
3457
- const address = await getAddressFromAccount(username, "TRX");
3458
- await CONFIG.queryClient.fetchQuery(
3459
- getTronAssetBalanceQueryOptions(address)
3460
- );
3461
- const accountBalance = (CONFIG.queryClient.getQueryData(
3462
- getTronAssetBalanceQueryOptions(address).queryKey
3463
- ) ?? 0) / 1e6;
3464
- await CONFIG.queryClient.prefetchQuery(
3465
- getTokenPriceQueryOptions("TRX")
3466
- );
3467
- const price = CONFIG.queryClient.getQueryData(
3468
- getTokenPriceQueryOptions("TRX").queryKey
3469
- ) ?? 0;
3470
- return {
3471
- name: "TRX",
3472
- title: "Tron",
3473
- price,
3474
- accountBalance
3475
- };
3476
- }
3477
- });
3478
- }
3479
-
3480
- // src/modules/wallets/queries/get-account-wallet-asset-info-query-options.ts
3481
- function getAccountWalletAssetInfoQueryOptions(username, asset, options2 = { refetch: false }) {
3482
- const queryClient = getQueryClient();
3483
- const currency = options2.currency ?? "usd";
3484
- const fetchQuery = async (queryOptions42) => {
3485
- if (options2.refetch) {
3486
- await queryClient.fetchQuery(queryOptions42);
3487
- } else {
3488
- await queryClient.prefetchQuery(queryOptions42);
3489
- }
3490
- return queryClient.getQueryData(queryOptions42.queryKey);
3491
- };
3492
- const convertPriceToUserCurrency = async (assetInfo) => {
3493
- if (!assetInfo || currency === "usd") {
3494
- return assetInfo;
3495
- }
3496
- try {
3497
- const conversionRate = await getCurrencyRate(currency);
3498
- return {
3499
- ...assetInfo,
3500
- price: assetInfo.price * conversionRate
3501
- };
3502
- } catch (error) {
3503
- console.warn(`Failed to convert price from USD to ${currency}:`, error);
3504
- return assetInfo;
3505
- }
3506
- };
3507
- const portfolioQuery = getVisionPortfolioQueryOptions(username, currency);
3508
- const getPortfolioAssetInfo = async () => {
3509
- try {
3510
- const portfolio = await queryClient.fetchQuery(portfolioQuery);
3511
- const assetInfo = portfolio.wallets.find(
3512
- (assetItem) => assetItem.symbol.toUpperCase() === asset.toUpperCase()
3513
- );
3514
- if (!assetInfo) return void 0;
3515
- const parts = [];
3516
- if (assetInfo.liquid !== void 0 && assetInfo.liquid !== null) {
3517
- parts.push({ name: "liquid", balance: assetInfo.liquid });
3518
- }
3519
- if (assetInfo.staked !== void 0 && assetInfo.staked !== null && assetInfo.staked > 0) {
3520
- parts.push({ name: "staked", balance: assetInfo.staked });
3521
- }
3522
- if (assetInfo.savings !== void 0 && assetInfo.savings !== null && assetInfo.savings > 0) {
3523
- parts.push({ name: "savings", balance: assetInfo.savings });
3524
- }
3525
- if (assetInfo.extraData && Array.isArray(assetInfo.extraData)) {
3526
- for (const extraItem of assetInfo.extraData) {
3527
- if (!extraItem || typeof extraItem !== "object") continue;
3528
- const dataKey = extraItem.dataKey;
3529
- const value = extraItem.value;
3530
- if (typeof value === "string") {
3531
- const cleanValue = value.replace(/,/g, "");
3532
- const match = cleanValue.match(/[+-]?\s*(\d+(?:\.\d+)?)/);
3533
- if (match) {
3534
- const numValue = Math.abs(Number.parseFloat(match[1]));
3535
- if (dataKey === "delegated_hive_power") {
3536
- parts.push({ name: "outgoing_delegations", balance: numValue });
3537
- } else if (dataKey === "received_hive_power") {
3538
- parts.push({ name: "incoming_delegations", balance: numValue });
3539
- } else if (dataKey === "powering_down_hive_power") {
3540
- parts.push({ name: "pending_power_down", balance: numValue });
3541
- }
3542
- }
3543
- }
3544
- }
3545
- }
3546
- return {
3547
- name: assetInfo.symbol,
3548
- title: assetInfo.name,
3549
- price: assetInfo.fiatRate,
3550
- accountBalance: assetInfo.balance,
3551
- apr: assetInfo.apr?.toString(),
3552
- layer: assetInfo.layer,
3553
- pendingRewards: assetInfo.pendingRewards,
3554
- parts
3555
- };
3556
- } catch (e) {
3557
- return void 0;
3558
- }
3559
- };
3560
- return queryOptions({
3561
- queryKey: ["ecency-wallets", "asset-info", username, asset, currency],
3562
- queryFn: async () => {
3563
- const portfolioAssetInfo = await getPortfolioAssetInfo();
3564
- if (portfolioAssetInfo && portfolioAssetInfo.price > 0) {
3565
- return portfolioAssetInfo;
3566
- }
3567
- let assetInfo;
3568
- if (asset === "HIVE") {
3569
- assetInfo = await fetchQuery(getHiveAssetGeneralInfoQueryOptions(username));
3570
- } else if (asset === "HP") {
3571
- assetInfo = await fetchQuery(getHivePowerAssetGeneralInfoQueryOptions(username));
3572
- } else if (asset === "HBD") {
3573
- assetInfo = await fetchQuery(getHbdAssetGeneralInfoQueryOptions(username));
3574
- } else if (asset === "SPK") {
3575
- assetInfo = await fetchQuery(getSpkAssetGeneralInfoQueryOptions(username));
3576
- } else if (asset === "LARYNX") {
3577
- assetInfo = await fetchQuery(getLarynxAssetGeneralInfoQueryOptions(username));
3578
- } else if (asset === "LP") {
3579
- assetInfo = await fetchQuery(getLarynxPowerAssetGeneralInfoQueryOptions(username));
3580
- } else if (asset === "POINTS") {
3581
- assetInfo = await fetchQuery(getPointsAssetGeneralInfoQueryOptions(username));
3582
- } else if (asset === "APT") {
3583
- assetInfo = await fetchQuery(getAptAssetGeneralInfoQueryOptions(username));
3584
- } else if (asset === "BNB") {
3585
- assetInfo = await fetchQuery(getBnbAssetGeneralInfoQueryOptions(username));
3586
- } else if (asset === "BTC") {
3587
- assetInfo = await fetchQuery(getBtcAssetGeneralInfoQueryOptions(username));
3588
- } else if (asset === "ETH") {
3589
- assetInfo = await fetchQuery(getEthAssetGeneralInfoQueryOptions(username));
3590
- } else if (asset === "SOL") {
3591
- assetInfo = await fetchQuery(getSolAssetGeneralInfoQueryOptions(username));
3592
- } else if (asset === "TON") {
3593
- assetInfo = await fetchQuery(getTonAssetGeneralInfoQueryOptions(username));
3594
- } else if (asset === "TRX") {
3595
- assetInfo = await fetchQuery(getTronAssetGeneralInfoQueryOptions(username));
3596
- } else {
3597
- const balances = await queryClient.ensureQueryData(
3598
- getHiveEngineTokensBalancesQueryOptions(username)
3599
- );
3600
- if (balances.some((balance) => balance.symbol === asset)) {
3601
- assetInfo = await fetchQuery(
3602
- getHiveEngineTokenGeneralInfoQueryOptions(username, asset)
3603
- );
3604
- } else {
3605
- throw new Error(
3606
- "[SDK][Wallets] \u2013 has requested unrecognized asset info"
3607
- );
3608
- }
3609
- }
3610
- return await convertPriceToUserCurrency(assetInfo);
3611
- }
3612
- });
3613
- }
3614
729
  function getTokenOperationsQueryOptions(token, username, isForOwner = false, currency = "usd") {
3615
730
  return queryOptions({
3616
731
  queryKey: ["wallets", "token-operations", token, username, isForOwner, currency],
@@ -3622,7 +737,7 @@ function getTokenOperationsQueryOptions(token, username, isForOwner = false, cur
3622
737
  }
3623
738
  try {
3624
739
  const portfolio = await queryClient.fetchQuery(
3625
- getVisionPortfolioQueryOptions(username, currency)
740
+ getPortfolioQueryOptions(username, currency, true)
3626
741
  );
3627
742
  const assetEntry = portfolio.wallets.find(
3628
743
  (assetItem) => assetItem.symbol.toUpperCase() === normalizedToken
@@ -3642,65 +757,65 @@ function getTokenOperationsQueryOptions(token, username, isForOwner = false, cur
3642
757
  const canonical = id.trim().toLowerCase().replace(/[\s_]+/g, "-");
3643
758
  const aliasMap = {
3644
759
  // Common operations
3645
- "transfer": "transfer" /* Transfer */,
3646
- "ecency-point-transfer": "transfer" /* Transfer */,
3647
- "spkcc-spk-send": "transfer" /* Transfer */,
760
+ "transfer": AssetOperation.Transfer,
761
+ "ecency-point-transfer": AssetOperation.Transfer,
762
+ "spkcc-spk-send": AssetOperation.Transfer,
3648
763
  // Savings operations
3649
- "transfer-to-savings": "transfer-saving" /* TransferToSavings */,
3650
- "transfer-savings": "transfer-saving" /* TransferToSavings */,
3651
- "savings-transfer": "transfer-saving" /* TransferToSavings */,
3652
- "withdraw-from-savings": "withdraw-saving" /* WithdrawFromSavings */,
3653
- "transfer-from-savings": "withdraw-saving" /* WithdrawFromSavings */,
3654
- "withdraw-savings": "withdraw-saving" /* WithdrawFromSavings */,
3655
- "savings-withdraw": "withdraw-saving" /* WithdrawFromSavings */,
764
+ "transfer-to-savings": AssetOperation.TransferToSavings,
765
+ "transfer-savings": AssetOperation.TransferToSavings,
766
+ "savings-transfer": AssetOperation.TransferToSavings,
767
+ "withdraw-from-savings": AssetOperation.WithdrawFromSavings,
768
+ "transfer-from-savings": AssetOperation.WithdrawFromSavings,
769
+ "withdraw-savings": AssetOperation.WithdrawFromSavings,
770
+ "savings-withdraw": AssetOperation.WithdrawFromSavings,
3656
771
  // Vesting/Power operations
3657
- "transfer-to-vesting": "power-up" /* PowerUp */,
3658
- "powerup": "power-up" /* PowerUp */,
3659
- "power-up": "power-up" /* PowerUp */,
3660
- "withdraw-vesting": "power-down" /* PowerDown */,
3661
- "power-down": "power-down" /* PowerDown */,
3662
- "powerdown": "power-down" /* PowerDown */,
772
+ "transfer-to-vesting": AssetOperation.PowerUp,
773
+ "powerup": AssetOperation.PowerUp,
774
+ "power-up": AssetOperation.PowerUp,
775
+ "withdraw-vesting": AssetOperation.PowerDown,
776
+ "power-down": AssetOperation.PowerDown,
777
+ "powerdown": AssetOperation.PowerDown,
3663
778
  // Delegation
3664
- "delegate": "delegate" /* Delegate */,
3665
- "delegate-vesting-shares": "delegate" /* Delegate */,
3666
- "hp-delegate": "delegate" /* Delegate */,
3667
- "delegate-hp": "delegate" /* Delegate */,
3668
- "delegate-power": "delegate" /* Delegate */,
3669
- "undelegate": "undelegate" /* Undelegate */,
3670
- "undelegate-power": "undelegate" /* Undelegate */,
3671
- "undelegate-token": "undelegate" /* Undelegate */,
779
+ "delegate": AssetOperation.Delegate,
780
+ "delegate-vesting-shares": AssetOperation.Delegate,
781
+ "hp-delegate": AssetOperation.Delegate,
782
+ "delegate-hp": AssetOperation.Delegate,
783
+ "delegate-power": AssetOperation.Delegate,
784
+ "undelegate": AssetOperation.Undelegate,
785
+ "undelegate-power": AssetOperation.Undelegate,
786
+ "undelegate-token": AssetOperation.Undelegate,
3672
787
  // Staking (Layer 2)
3673
- "stake": "stake" /* Stake */,
3674
- "stake-token": "stake" /* Stake */,
3675
- "stake-power": "stake" /* Stake */,
3676
- "unstake": "unstake" /* Unstake */,
3677
- "unstake-token": "unstake" /* Unstake */,
3678
- "unstake-power": "unstake" /* Unstake */,
788
+ "stake": AssetOperation.Stake,
789
+ "stake-token": AssetOperation.Stake,
790
+ "stake-power": AssetOperation.Stake,
791
+ "unstake": AssetOperation.Unstake,
792
+ "unstake-token": AssetOperation.Unstake,
793
+ "unstake-power": AssetOperation.Unstake,
3679
794
  // Swap/Convert
3680
- "swap": "swap" /* Swap */,
3681
- "swap-token": "swap" /* Swap */,
3682
- "swap-tokens": "swap" /* Swap */,
3683
- "convert": "convert" /* Convert */,
795
+ "swap": AssetOperation.Swap,
796
+ "swap-token": AssetOperation.Swap,
797
+ "swap-tokens": AssetOperation.Swap,
798
+ "convert": AssetOperation.Convert,
3684
799
  // Points operations
3685
- "promote": "promote" /* Promote */,
3686
- "promote-post": "promote" /* Promote */,
3687
- "promote-entry": "promote" /* Promote */,
3688
- "boost": "promote" /* Promote */,
3689
- "gift": "gift" /* Gift */,
3690
- "gift-points": "gift" /* Gift */,
3691
- "points-gift": "gift" /* Gift */,
3692
- "claim": "claim" /* Claim */,
3693
- "claim-rewards": "claim" /* Claim */,
3694
- "claim-points": "claim" /* Claim */,
3695
- "buy": "buy" /* Buy */,
3696
- "buy-points": "buy" /* Buy */,
800
+ "promote": AssetOperation.Promote,
801
+ "promote-post": AssetOperation.Promote,
802
+ "promote-entry": AssetOperation.Promote,
803
+ "boost": AssetOperation.Promote,
804
+ "gift": AssetOperation.Gift,
805
+ "gift-points": AssetOperation.Gift,
806
+ "points-gift": AssetOperation.Gift,
807
+ "claim": AssetOperation.Claim,
808
+ "claim-rewards": AssetOperation.Claim,
809
+ "claim-points": AssetOperation.Claim,
810
+ "buy": AssetOperation.Buy,
811
+ "buy-points": AssetOperation.Buy,
3697
812
  // Other
3698
- "claim-interest": "claim-interest" /* ClaimInterest */,
3699
- "withdraw-routes": "withdraw-routes" /* WithdrawRoutes */,
3700
- "withdrawroutes": "withdraw-routes" /* WithdrawRoutes */,
3701
- "lock": "lock" /* LockLiquidity */,
3702
- "lock-liquidity": "lock" /* LockLiquidity */,
3703
- "lock-liq": "lock" /* LockLiquidity */
813
+ "claim-interest": AssetOperation.ClaimInterest,
814
+ "withdraw-routes": AssetOperation.WithdrawRoutes,
815
+ "withdrawroutes": AssetOperation.WithdrawRoutes,
816
+ "lock": AssetOperation.LockLiquidity,
817
+ "lock-liquidity": AssetOperation.LockLiquidity,
818
+ "lock-liq": AssetOperation.LockLiquidity
3704
819
  };
3705
820
  const mapped = aliasMap[canonical];
3706
821
  if (mapped) return mapped;
@@ -3714,7 +829,7 @@ function getTokenOperationsQueryOptions(token, username, isForOwner = false, cur
3714
829
  const hasSavings = Number(rawToken.savings ?? 0) > 0;
3715
830
  if (isHiveOrHbd && !hasSavings) {
3716
831
  return operations.filter(
3717
- (operation) => operation !== "withdraw-saving" /* WithdrawFromSavings */
832
+ (operation) => operation !== AssetOperation.WithdrawFromSavings
3718
833
  );
3719
834
  }
3720
835
  return operations;
@@ -4062,120 +1177,10 @@ function useSaveWalletInformationToMetadata(username, auth, options2) {
4062
1177
  }
4063
1178
  });
4064
1179
  }
4065
- var operationToFunctionMap = {
4066
- HIVE: {
4067
- ["transfer" /* Transfer */]: transferHive,
4068
- ["transfer-saving" /* TransferToSavings */]: transferToSavingsHive,
4069
- ["withdraw-saving" /* WithdrawFromSavings */]: transferFromSavingsHive,
4070
- ["power-up" /* PowerUp */]: powerUpHive
4071
- },
4072
- HBD: {
4073
- ["transfer" /* Transfer */]: transferHive,
4074
- ["transfer-saving" /* TransferToSavings */]: transferToSavingsHive,
4075
- ["withdraw-saving" /* WithdrawFromSavings */]: transferFromSavingsHive,
4076
- ["claim-interest" /* ClaimInterest */]: claimInterestHive,
4077
- ["convert" /* Convert */]: convertHbd
4078
- },
4079
- HP: {
4080
- ["power-down" /* PowerDown */]: powerDownHive,
4081
- ["delegate" /* Delegate */]: delegateHive,
4082
- ["withdraw-routes" /* WithdrawRoutes */]: withdrawVestingRouteHive
4083
- },
4084
- POINTS: {
4085
- ["transfer" /* Transfer */]: transferPoint,
4086
- ["gift" /* Gift */]: transferPoint
4087
- },
4088
- SPK: {
4089
- ["transfer" /* Transfer */]: transferSpk
4090
- },
4091
- LARYNX: {
4092
- ["transfer" /* Transfer */]: transferLarynx,
4093
- ["lock" /* LockLiquidity */]: lockLarynx,
4094
- ["power-up" /* PowerUp */]: powerUpLarynx
4095
- }
4096
- };
4097
- var engineOperationToFunctionMap = {
4098
- ["transfer" /* Transfer */]: transferEngineToken,
4099
- ["stake" /* Stake */]: stakeEngineToken,
4100
- ["unstake" /* Unstake */]: unstakeEngineToken,
4101
- ["delegate" /* Delegate */]: delegateEngineToken,
4102
- ["undelegate" /* Undelegate */]: undelegateEngineToken,
4103
- ["claim" /* Claim */]: (payload, auth) => {
4104
- return claimHiveEngineRewards(
4105
- {
4106
- account: payload.from,
4107
- tokens: [payload.asset],
4108
- type: payload.type,
4109
- ...payload.type === "key" && payload.key ? { key: payload.key } : {}
4110
- },
4111
- auth
4112
- );
4113
- }
4114
- };
4115
- function useWalletOperation(username, asset, operation, auth) {
4116
- const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(
4117
- username,
4118
- operation
4119
- );
4120
- return useMutation({
4121
- mutationKey: ["ecency-wallets", asset, operation],
4122
- mutationFn: async (payload) => {
4123
- const operationFn = operationToFunctionMap[asset]?.[operation];
4124
- if (operationFn) {
4125
- return operationFn(payload, auth);
4126
- }
4127
- const balancesListQuery = getHiveEngineTokensBalancesQueryOptions(username);
4128
- await getQueryClient().prefetchQuery(balancesListQuery);
4129
- const balances = getQueryClient().getQueryData(
4130
- balancesListQuery.queryKey
4131
- );
4132
- const engineBalances = balances ?? [];
4133
- if (engineBalances.some((balance) => balance.symbol === asset)) {
4134
- const operationFn2 = engineOperationToFunctionMap[operation];
4135
- if (operationFn2) {
4136
- return operationFn2({ ...payload, asset }, auth);
4137
- }
4138
- }
4139
- throw new Error("[SDK][Wallets] \u2013 no operation for given asset");
4140
- },
4141
- onSuccess: () => {
4142
- recordActivity();
4143
- const assetsToRefresh = /* @__PURE__ */ new Set([asset]);
4144
- if (asset === "HIVE") {
4145
- assetsToRefresh.add("HP");
4146
- assetsToRefresh.add("HIVE");
4147
- }
4148
- if (asset === "HBD") {
4149
- assetsToRefresh.add("HBD");
4150
- }
4151
- if (asset === "LARYNX" && operation === "power-up" /* PowerUp */) {
4152
- assetsToRefresh.add("LP");
4153
- assetsToRefresh.add("LARYNX");
4154
- }
4155
- assetsToRefresh.forEach((symbol) => {
4156
- const query = getAccountWalletAssetInfoQueryOptions(username, symbol, {
4157
- refetch: true
4158
- });
4159
- setTimeout(
4160
- () => getQueryClient().invalidateQueries({
4161
- queryKey: query.queryKey
4162
- }),
4163
- 5e3
4164
- );
4165
- });
4166
- setTimeout(
4167
- () => getQueryClient().invalidateQueries({
4168
- queryKey: ["ecency-wallets", "portfolio", "v2", username]
4169
- }),
4170
- 4e3
4171
- );
4172
- }
4173
- });
4174
- }
4175
1180
 
4176
1181
  // src/index.ts
4177
1182
  rememberScryptBsvVersion();
4178
1183
 
4179
- export { AssetOperation, EcencyWalletBasicTokens, EcencyWalletCurrency, private_api_exports as EcencyWalletsPrivateApi, HIVE_ACCOUNT_OPERATION_GROUPS, HIVE_OPERATION_LIST, HIVE_OPERATION_NAME_BY_ID, HIVE_OPERATION_ORDERS, HiveEngineToken, NaiMap, PointTransactionType, Symbol2 as Symbol, broadcastWithWalletHiveAuth, buildAptTx, buildEthTx, buildExternalTx, buildPsbt, buildSolTx, buildTonTx, buildTronTx, cancelHiveEngineOrder, claimHiveEngineRewards, claimInterestHive, convertHbd, decryptMemoWithAccounts, decryptMemoWithKeys, delay, delegateEngineToken, delegateHive, deriveHiveKey, deriveHiveKeys, deriveHiveMasterPasswordKey, deriveHiveMasterPasswordKeys, detectHiveKeyDerivation, encryptMemoWithAccounts, encryptMemoWithKeys, formattedNumber, getAccountWalletAssetInfoQueryOptions, getAccountWalletListQueryOptions, getAllHiveEngineTokensQueryOptions, getAllTokensListQueryOptions, getBoundFetch, getHbdAssetGeneralInfoQueryOptions, getHbdAssetTransactionsQueryOptions, getHiveAssetGeneralInfoQueryOptions, getHiveAssetMetricQueryOptions, getHiveAssetTransactionsQueryOptions, getHiveAssetWithdrawalRoutesQueryOptions, getHiveEngineBalancesWithUsdQueryOptions, getHiveEngineTokenGeneralInfoQueryOptions, getHiveEngineTokenTransactionsQueryOptions, getHiveEngineTokensBalancesQueryOptions, getHiveEngineTokensMarketQueryOptions, getHiveEngineTokensMetadataQueryOptions, getHiveEngineTokensMetricsQueryOptions, getHiveEngineUnclaimedRewardsQueryOptions, getHivePowerAssetGeneralInfoQueryOptions, getHivePowerAssetTransactionsQueryOptions, getHivePowerDelegatesInfiniteQueryOptions, getHivePowerDelegatingsQueryOptions, getLarynxAssetGeneralInfoQueryOptions, getLarynxPowerAssetGeneralInfoQueryOptions, getPointsAssetGeneralInfoQueryOptions, getPointsAssetTransactionsQueryOptions, getPointsQueryOptions, getSpkAssetGeneralInfoQueryOptions, getSpkMarketsQueryOptions, getSpkWalletQueryOptions, getTokenOperationsQueryOptions, getTokenPriceQueryOptions, getVisionPortfolioQueryOptions, getWallet, hasWalletHiveAuthBroadcast, isEmptyDate, lockLarynx, mnemonicToSeedBip39, parseAsset, placeHiveEngineBuyOrder, placeHiveEngineSellOrder, powerDownHive, powerUpHive, powerUpLarynx, registerWalletHiveAuthBroadcast, resolveHiveOperationFilters, rewardSpk, signDigest, signExternalTx, signExternalTxAndBroadcast, signTx, signTxAndBroadcast, stakeEngineToken, transferEngineToken, transferFromSavingsHive, transferHive, transferLarynx, transferPoint, transferSpk, transferToSavingsHive, undelegateEngineToken, unstakeEngineToken, useClaimPoints, useClaimRewards, useGetExternalWalletBalanceQuery, useHiveKeysQuery, useImportWallet, useSaveWalletInformationToMetadata, useSeedPhrase, useWalletCreate, useWalletOperation, useWalletsCacheQuery, vestsToHp, withdrawVestingRouteHive };
1184
+ export { EcencyWalletBasicTokens, EcencyWalletCurrency, private_api_exports as EcencyWalletsPrivateApi, buildAptTx, buildEthTx, buildExternalTx, buildPsbt, buildSolTx, buildTonTx, buildTronTx, decryptMemoWithAccounts, decryptMemoWithKeys, delay, deriveHiveKey, deriveHiveKeys, deriveHiveMasterPasswordKey, deriveHiveMasterPasswordKeys, detectHiveKeyDerivation, encryptMemoWithAccounts, encryptMemoWithKeys, getAccountWalletListQueryOptions, getAllTokensListQueryOptions, getBoundFetch, getTokenOperationsQueryOptions, getTokenPriceQueryOptions, getWallet, mnemonicToSeedBip39, signDigest, signExternalTx, signExternalTxAndBroadcast, signTx, signTxAndBroadcast, useGetExternalWalletBalanceQuery, useHiveKeysQuery, useImportWallet, useSaveWalletInformationToMetadata, useSeedPhrase, useWalletCreate, useWalletsCacheQuery };
4180
1185
  //# sourceMappingURL=index.js.map
4181
1186
  //# sourceMappingURL=index.js.map