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