@ecency/wallets 1.4.1 → 1.4.5

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.
Files changed (170) hide show
  1. package/dist/browser/index.d.ts +1643 -0
  2. package/dist/browser/index.js +3328 -0
  3. package/dist/browser/index.js.map +1 -0
  4. package/dist/index.browser.mjs +3338 -0
  5. package/dist/index.browser.mjs.map +1 -0
  6. package/dist/index.cjs +3453 -0
  7. package/dist/index.cjs.map +1 -0
  8. package/dist/index.d.ts +1643 -2
  9. package/dist/index.mjs +3338 -0
  10. package/dist/index.mjs.map +1 -0
  11. package/dist/node/index.cjs +3443 -0
  12. package/dist/node/index.cjs.map +1 -0
  13. package/dist/node/index.mjs +3328 -0
  14. package/dist/node/index.mjs.map +1 -0
  15. package/package.json +58 -28
  16. package/dist/ecency-sdk.es.js +0 -23225
  17. package/dist/internal/scrypt-guard.d.ts +0 -1
  18. package/dist/modules/assets/external/apt/get-apt-asset-balance-query-options.d.ts +0 -8
  19. package/dist/modules/assets/external/apt/get-apt-asset-general-info-query-options.d.ts +0 -28
  20. package/dist/modules/assets/external/apt/index.d.ts +0 -2
  21. package/dist/modules/assets/external/bnb/get-bnb-asset-balance-query-options.d.ts +0 -8
  22. package/dist/modules/assets/external/bnb/get-bnb-asset-general-info-query-options.d.ts +0 -28
  23. package/dist/modules/assets/external/bnb/index.d.ts +0 -2
  24. package/dist/modules/assets/external/btc/get-btc-asset-balance-query-options.d.ts +0 -8
  25. package/dist/modules/assets/external/btc/get-btc-asset-general-info-query-options.d.ts +0 -28
  26. package/dist/modules/assets/external/btc/index.d.ts +0 -2
  27. package/dist/modules/assets/external/common/index.d.ts +0 -1
  28. package/dist/modules/assets/external/common/parse-private-api-balance.d.ts +0 -23
  29. package/dist/modules/assets/external/eth/get-eth-asset-balance-query-options.d.ts +0 -8
  30. package/dist/modules/assets/external/eth/get-eth-asset-general-info-query-options.d.ts +0 -28
  31. package/dist/modules/assets/external/eth/index.d.ts +0 -2
  32. package/dist/modules/assets/external/index.d.ts +0 -7
  33. package/dist/modules/assets/external/sol/get-sol-asset-balance-query-options.d.ts +0 -8
  34. package/dist/modules/assets/external/sol/get-sol-asset-general-info-query-options.d.ts +0 -28
  35. package/dist/modules/assets/external/sol/index.d.ts +0 -2
  36. package/dist/modules/assets/external/ton/get-ton-asset-balance-query-options.d.ts +0 -8
  37. package/dist/modules/assets/external/ton/get-ton-asset-general-info-query-options.d.ts +0 -28
  38. package/dist/modules/assets/external/ton/index.d.ts +0 -2
  39. package/dist/modules/assets/external/tron/get-tron-asset-balance-query-options.d.ts +0 -8
  40. package/dist/modules/assets/external/tron/get-tron-asset-general-info-query-options.d.ts +0 -28
  41. package/dist/modules/assets/external/tron/index.d.ts +0 -2
  42. package/dist/modules/assets/hive/consts/hive-account-operation-groups.d.ts +0 -2
  43. package/dist/modules/assets/hive/consts/index.d.ts +0 -1
  44. package/dist/modules/assets/hive/index.d.ts +0 -2
  45. package/dist/modules/assets/hive/mutations/claim-rewards.d.ts +0 -1
  46. package/dist/modules/assets/hive/mutations/delegate.d.ts +0 -13
  47. package/dist/modules/assets/hive/mutations/index.d.ts +0 -7
  48. package/dist/modules/assets/hive/mutations/power-down.d.ts +0 -11
  49. package/dist/modules/assets/hive/mutations/power-up.d.ts +0 -13
  50. package/dist/modules/assets/hive/mutations/transfer-to-savings.d.ts +0 -13
  51. package/dist/modules/assets/hive/mutations/transfer.d.ts +0 -12
  52. package/dist/modules/assets/hive/mutations/withdraw-route.d.ts +0 -13
  53. package/dist/modules/assets/hive/queries/get-hbd-asset-general-info-query-options.d.ts +0 -76
  54. package/dist/modules/assets/hive/queries/get-hbd-asset-transactions-query-options.d.ts +0 -9
  55. package/dist/modules/assets/hive/queries/get-hive-asset-general-info-query-options.d.ts +0 -28
  56. package/dist/modules/assets/hive/queries/get-hive-asset-metric-query-options.d.ts +0 -43
  57. package/dist/modules/assets/hive/queries/get-hive-asset-transactions-query-options.d.ts +0 -9
  58. package/dist/modules/assets/hive/queries/get-hive-asset-withdrawal-routes-query-options.d.ts +0 -9
  59. package/dist/modules/assets/hive/queries/get-hive-power-asset-general-info-query-options.d.ts +0 -76
  60. package/dist/modules/assets/hive/queries/get-hive-power-asset-transactions-query-options.d.ts +0 -9
  61. package/dist/modules/assets/hive/queries/get-hive-power-delegates-query-options.d.ts +0 -9
  62. package/dist/modules/assets/hive/queries/get-hive-power-delegatings-query-options.d.ts +0 -9
  63. package/dist/modules/assets/hive/queries/index.d.ts +0 -10
  64. package/dist/modules/assets/hive/types/delegated-vesting-share.d.ts +0 -7
  65. package/dist/modules/assets/hive/types/hive-market-metric.d.ts +0 -19
  66. package/dist/modules/assets/hive/types/hive-operation-group.d.ts +0 -1
  67. package/dist/modules/assets/hive/types/hive-transaction.d.ts +0 -198
  68. package/dist/modules/assets/hive/types/hive-withdraw-route.d.ts +0 -7
  69. package/dist/modules/assets/hive/types/index.d.ts +0 -6
  70. package/dist/modules/assets/hive/types/received-vesting-share.d.ts +0 -6
  71. package/dist/modules/assets/hive-engine/index.d.ts +0 -3
  72. package/dist/modules/assets/hive-engine/mutations/delegate.d.ts +0 -12
  73. package/dist/modules/assets/hive-engine/mutations/index.d.ts +0 -5
  74. package/dist/modules/assets/hive-engine/mutations/stake.d.ts +0 -12
  75. package/dist/modules/assets/hive-engine/mutations/transfer.d.ts +0 -13
  76. package/dist/modules/assets/hive-engine/mutations/undelegate.d.ts +0 -12
  77. package/dist/modules/assets/hive-engine/mutations/unstake.d.ts +0 -12
  78. package/dist/modules/assets/hive-engine/queries/get-hive-engine-token-general-info-query-options.d.ts +0 -32
  79. package/dist/modules/assets/hive-engine/queries/get-hive-engine-token-metrics-query-options.d.ts +0 -9
  80. package/dist/modules/assets/hive-engine/queries/get-hive-engine-token-transactions-query-options.d.ts +0 -9
  81. package/dist/modules/assets/hive-engine/queries/get-hive-engine-tokens-balances-query-options.d.ts +0 -9
  82. package/dist/modules/assets/hive-engine/queries/get-hive-engine-tokens-market-query-options.d.ts +0 -9
  83. package/dist/modules/assets/hive-engine/queries/get-hive-engine-tokens-metadata-query-options.d.ts +0 -9
  84. package/dist/modules/assets/hive-engine/queries/index.d.ts +0 -6
  85. package/dist/modules/assets/hive-engine/types/hive-engine-list-response.d.ts +0 -13
  86. package/dist/modules/assets/hive-engine/types/hive-engine-metric.d.ts +0 -9
  87. package/dist/modules/assets/hive-engine/types/hive-engine-token-balance.d.ts +0 -10
  88. package/dist/modules/assets/hive-engine/types/hive-engine-token-metadata-response.d.ts +0 -16
  89. package/dist/modules/assets/hive-engine/types/hive-engine-transaction.d.ts +0 -14
  90. package/dist/modules/assets/hive-engine/types/index.d.ts +0 -6
  91. package/dist/modules/assets/index.d.ts +0 -6
  92. package/dist/modules/assets/points/index.d.ts +0 -3
  93. package/dist/modules/assets/points/mutations/claim-points.d.ts +0 -2
  94. package/dist/modules/assets/points/mutations/gift.d.ts +0 -14
  95. package/dist/modules/assets/points/mutations/index.d.ts +0 -2
  96. package/dist/modules/assets/points/queries/get-points-asset-general-info-query-options.d.ts +0 -28
  97. package/dist/modules/assets/points/queries/get-points-asset-transactions-query-options.d.ts +0 -41
  98. package/dist/modules/assets/points/queries/get-points-query-options.d.ts +0 -20
  99. package/dist/modules/assets/points/queries/index.d.ts +0 -3
  100. package/dist/modules/assets/points/types/index.d.ts +0 -4
  101. package/dist/modules/assets/points/types/point-transaction-type.d.ts +0 -15
  102. package/dist/modules/assets/points/types/point-transaction.d.ts +0 -10
  103. package/dist/modules/assets/points/types/points-response.d.ts +0 -4
  104. package/dist/modules/assets/points/types/points.d.ts +0 -4
  105. package/dist/modules/assets/spk/index.d.ts +0 -2
  106. package/dist/modules/assets/spk/mutations/index.d.ts +0 -4
  107. package/dist/modules/assets/spk/mutations/lock.d.ts +0 -12
  108. package/dist/modules/assets/spk/mutations/power-up.d.ts +0 -12
  109. package/dist/modules/assets/spk/mutations/transfer.d.ts +0 -14
  110. package/dist/modules/assets/spk/queries/get-larynx-asset-general-info-query-options.d.ts +0 -56
  111. package/dist/modules/assets/spk/queries/get-larynx-power-asset-general-info-query-options.d.ts +0 -76
  112. package/dist/modules/assets/spk/queries/get-spk-asset-general-info-query-options.d.ts +0 -28
  113. package/dist/modules/assets/spk/queries/get-spk-markets-query-options.d.ts +0 -33
  114. package/dist/modules/assets/spk/queries/get-spk-wallet-query-options.d.ts +0 -9
  115. package/dist/modules/assets/spk/queries/index.d.ts +0 -4
  116. package/dist/modules/assets/types/asset-operation.d.ts +0 -17
  117. package/dist/modules/assets/types/general-asset-info.d.ts +0 -12
  118. package/dist/modules/assets/types/general-asset-transaction.d.ts +0 -13
  119. package/dist/modules/assets/types/hive-based-asset-sign-type.d.ts +0 -1
  120. package/dist/modules/assets/types/index.d.ts +0 -5
  121. package/dist/modules/assets/types/spk-wallet.d.ts +0 -60
  122. package/dist/modules/assets/utils/index.d.ts +0 -4
  123. package/dist/modules/assets/utils/is-empty-date.d.ts +0 -1
  124. package/dist/modules/assets/utils/parse-asset.d.ts +0 -17
  125. package/dist/modules/assets/utils/reward-spk.d.ts +0 -2
  126. package/dist/modules/assets/utils/vests-to-hp.d.ts +0 -1
  127. package/dist/modules/wallets/consts/hive-engine-tokens.d.ts +0 -1
  128. package/dist/modules/wallets/consts/index.d.ts +0 -1
  129. package/dist/modules/wallets/enums/ecency-wallet-basic-tokens.d.ts +0 -7
  130. package/dist/modules/wallets/enums/ecency-wallet-currency.d.ts +0 -9
  131. package/dist/modules/wallets/enums/index.d.ts +0 -2
  132. package/dist/modules/wallets/functions/get-keys-from-seed.d.ts +0 -3
  133. package/dist/modules/wallets/functions/index.d.ts +0 -1
  134. package/dist/modules/wallets/index.d.ts +0 -5
  135. package/dist/modules/wallets/mutations/index.d.ts +0 -5
  136. package/dist/modules/wallets/mutations/private-api/check-wallet-existence.d.ts +0 -7
  137. package/dist/modules/wallets/mutations/private-api/create-account-with-wallets.d.ts +0 -6
  138. package/dist/modules/wallets/mutations/private-api/index.d.ts +0 -2
  139. package/dist/modules/wallets/mutations/private-api-namespace.d.ts +0 -2
  140. package/dist/modules/wallets/mutations/save-wallet-information-to-metadata.d.ts +0 -9
  141. package/dist/modules/wallets/mutations/use-import-wallet.d.ts +0 -15
  142. package/dist/modules/wallets/mutations/use-wallet-create.d.ts +0 -11
  143. package/dist/modules/wallets/mutations/wallet-operation.d.ts +0 -2
  144. package/dist/modules/wallets/queries/get-account-wallet-asset-info-query-options.d.ts +0 -13
  145. package/dist/modules/wallets/queries/get-all-tokens-list-query-options.d.ts +0 -30
  146. package/dist/modules/wallets/queries/get-coingecko-price-query-options.d.ts +0 -8
  147. package/dist/modules/wallets/queries/get-tokens-operations-query-options.d.ts +0 -9
  148. package/dist/modules/wallets/queries/index.d.ts +0 -8
  149. package/dist/modules/wallets/queries/use-get-account-wallet-list-query.d.ts +0 -8
  150. package/dist/modules/wallets/queries/use-get-external-wallet-query.d.ts +0 -17
  151. package/dist/modules/wallets/queries/use-hive-keys-query.d.ts +0 -2
  152. package/dist/modules/wallets/queries/use-seed-phrase.d.ts +0 -1
  153. package/dist/modules/wallets/types/account-points-response.d.ts +0 -4
  154. package/dist/modules/wallets/types/ecency-create-wallet-information.d.ts +0 -13
  155. package/dist/modules/wallets/types/ecency-hive-keys.d.ts +0 -12
  156. package/dist/modules/wallets/types/index.d.ts +0 -3
  157. package/dist/modules/wallets/utils/build-external-transaction.d.ts +0 -48
  158. package/dist/modules/wallets/utils/decrypt-memo.d.ts +0 -12
  159. package/dist/modules/wallets/utils/delay.d.ts +0 -1
  160. package/dist/modules/wallets/utils/derive-hive-bip44-keys.d.ts +0 -15
  161. package/dist/modules/wallets/utils/derive-hive-master-password-keys.d.ts +0 -15
  162. package/dist/modules/wallets/utils/detect-hive-key-derivation.d.ts +0 -2
  163. package/dist/modules/wallets/utils/encrypt-memo.d.ts +0 -16
  164. package/dist/modules/wallets/utils/get-wallet.d.ts +0 -3
  165. package/dist/modules/wallets/utils/index.d.ts +0 -12
  166. package/dist/modules/wallets/utils/mnemonic-to-seed-bip-39.d.ts +0 -1
  167. package/dist/modules/wallets/utils/sign-digest.d.ts +0 -7
  168. package/dist/modules/wallets/utils/sign-external-transaction.d.ts +0 -18
  169. package/dist/modules/wallets/utils/sign-transaction.d.ts +0 -23
  170. package/dist/vite.config.d.ts +0 -2
@@ -0,0 +1,3338 @@
1
+ import { CONFIG, getAccountFullQueryOptions, getQueryClient, getDynamicPropsQueryOptions, Keychain, useBroadcastMutation, EcencyAnalytics, getAccessToken, useAccountUpdate } from '@ecency/sdk';
2
+ import { useQuery, queryOptions, infiniteQueryOptions, useQueryClient, useMutation } from '@tanstack/react-query';
3
+ import bip39, { mnemonicToSeedSync } from 'bip39';
4
+ import { LRUCache } from 'lru-cache';
5
+ import { BtcWallet, buildPsbt as buildPsbt$1 } from '@okxweb3/coin-bitcoin';
6
+ import { EthWallet } from '@okxweb3/coin-ethereum';
7
+ import { TrxWallet } from '@okxweb3/coin-tron';
8
+ import { TonWallet } from '@okxweb3/coin-ton';
9
+ import { SolWallet } from '@okxweb3/coin-solana';
10
+ import { AptosWallet } from '@okxweb3/coin-aptos';
11
+ import { bip32 } from '@okxweb3/crypto-lib';
12
+ import { utils, PrivateKey } from '@hiveio/dhive';
13
+ import { cryptoUtils } from '@hiveio/dhive/lib/crypto';
14
+ import { Memo } from '@hiveio/dhive/lib/memo';
15
+ import dayjs from 'dayjs';
16
+ import hs from 'hivesigner';
17
+ import * as R from 'remeda';
18
+
19
+ var __defProp = Object.defineProperty;
20
+ var __export = (target, all) => {
21
+ for (var name in all)
22
+ __defProp(target, name, { get: all[name], enumerable: true });
23
+ };
24
+
25
+ // src/internal/scrypt-guard.ts
26
+ var globalLike = globalThis;
27
+ if (typeof globalLike._scrypt_bsv !== "undefined") {
28
+ if (typeof globalLike._scrypt_bsv === "string") {
29
+ globalLike.__scryptBsvPreviousVersion = globalLike._scrypt_bsv;
30
+ }
31
+ try {
32
+ delete globalLike._scrypt_bsv;
33
+ } catch {
34
+ globalLike._scrypt_bsv = void 0;
35
+ }
36
+ }
37
+ function rememberScryptBsvVersion() {
38
+ if (typeof globalLike._scrypt_bsv === "string") {
39
+ globalLike.__scryptBsvPreviousVersion = globalLike._scrypt_bsv;
40
+ }
41
+ }
42
+
43
+ // src/modules/wallets/enums/ecency-wallet-currency.ts
44
+ var EcencyWalletCurrency = /* @__PURE__ */ ((EcencyWalletCurrency2) => {
45
+ EcencyWalletCurrency2["BTC"] = "BTC";
46
+ EcencyWalletCurrency2["ETH"] = "ETH";
47
+ EcencyWalletCurrency2["BNB"] = "BNB";
48
+ EcencyWalletCurrency2["APT"] = "APT";
49
+ EcencyWalletCurrency2["TON"] = "TON";
50
+ EcencyWalletCurrency2["TRON"] = "TRX";
51
+ EcencyWalletCurrency2["SOL"] = "SOL";
52
+ return EcencyWalletCurrency2;
53
+ })(EcencyWalletCurrency || {});
54
+
55
+ // src/modules/wallets/enums/ecency-wallet-basic-tokens.ts
56
+ var EcencyWalletBasicTokens = /* @__PURE__ */ ((EcencyWalletBasicTokens2) => {
57
+ EcencyWalletBasicTokens2["Points"] = "POINTS";
58
+ EcencyWalletBasicTokens2["HivePower"] = "HP";
59
+ EcencyWalletBasicTokens2["Hive"] = "HIVE";
60
+ EcencyWalletBasicTokens2["HiveDollar"] = "HBD";
61
+ EcencyWalletBasicTokens2["Spk"] = "SPK";
62
+ return EcencyWalletBasicTokens2;
63
+ })(EcencyWalletBasicTokens || {});
64
+ var currencyChainMap = {
65
+ ["BTC" /* BTC */]: "btc",
66
+ ["ETH" /* ETH */]: "eth",
67
+ ["BNB" /* BNB */]: "bnb",
68
+ ["SOL" /* SOL */]: "sol",
69
+ ["TRX" /* TRON */]: "tron",
70
+ ["TON" /* TON */]: "ton",
71
+ ["APT" /* APT */]: "apt"
72
+ };
73
+ function normalizeBalance(balance) {
74
+ if (typeof balance === "number") {
75
+ if (!Number.isFinite(balance)) {
76
+ throw new Error("Private API returned a non-finite numeric balance");
77
+ }
78
+ return Math.trunc(balance).toString();
79
+ }
80
+ if (typeof balance === "string") {
81
+ const trimmed = balance.trim();
82
+ if (trimmed === "") {
83
+ throw new Error("Private API returned an empty balance string");
84
+ }
85
+ return trimmed;
86
+ }
87
+ throw new Error("Private API returned balance in an unexpected format");
88
+ }
89
+ function parsePrivateApiBalance(result, expectedChain) {
90
+ if (!result || typeof result !== "object") {
91
+ throw new Error("Private API returned an unexpected response");
92
+ }
93
+ const { chain, balance, unit, raw, nodeId } = result;
94
+ if (typeof chain !== "string" || chain !== expectedChain) {
95
+ throw new Error("Private API response chain did not match request");
96
+ }
97
+ if (typeof unit !== "string" || unit.length === 0) {
98
+ throw new Error("Private API response is missing unit information");
99
+ }
100
+ if (balance === void 0 || balance === null) {
101
+ throw new Error("Private API response is missing balance information");
102
+ }
103
+ const balanceString = normalizeBalance(balance);
104
+ let balanceBigInt;
105
+ try {
106
+ balanceBigInt = BigInt(balanceString);
107
+ } catch (error) {
108
+ throw new Error("Private API returned a balance that is not an integer");
109
+ }
110
+ return {
111
+ chain,
112
+ unit,
113
+ raw,
114
+ nodeId: typeof nodeId === "string" && nodeId.length > 0 ? nodeId : void 0,
115
+ balanceBigInt,
116
+ balanceString
117
+ };
118
+ }
119
+ function useGetExternalWalletBalanceQuery(currency, address) {
120
+ return useQuery({
121
+ queryKey: ["ecency-wallets", "external-wallet-balance", currency, address],
122
+ queryFn: async () => {
123
+ const chain = currencyChainMap[currency];
124
+ if (!chain) {
125
+ throw new Error(`Unsupported currency ${currency}`);
126
+ }
127
+ if (!CONFIG.privateApiHost) {
128
+ throw new Error("Private API host is not configured");
129
+ }
130
+ const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/${chain}/${encodeURIComponent(
131
+ address
132
+ )}`;
133
+ let primaryResponse;
134
+ let primaryError;
135
+ try {
136
+ primaryResponse = await fetch(baseUrl);
137
+ } catch (error) {
138
+ primaryError = error;
139
+ }
140
+ let response = primaryResponse;
141
+ if (!response || !response.ok) {
142
+ const fallbackUrl = `${baseUrl}?provider=chainz`;
143
+ let fallbackError;
144
+ try {
145
+ const fallbackResponse = await fetch(fallbackUrl);
146
+ if (fallbackResponse.ok) {
147
+ response = fallbackResponse;
148
+ } else {
149
+ fallbackError = new Error(
150
+ `Fallback provider responded with status ${fallbackResponse.status}`
151
+ );
152
+ }
153
+ } catch (error) {
154
+ fallbackError = error;
155
+ }
156
+ if (!response || !response.ok) {
157
+ const failureReasons = [];
158
+ if (primaryError) {
159
+ const message = primaryError instanceof Error ? primaryError.message : String(primaryError);
160
+ failureReasons.push(`primary provider failed: ${message}`);
161
+ } else if (primaryResponse && !primaryResponse.ok) {
162
+ failureReasons.push(
163
+ `primary provider status ${primaryResponse.status}`
164
+ );
165
+ }
166
+ if (fallbackError) {
167
+ const message = fallbackError instanceof Error ? fallbackError.message : String(fallbackError);
168
+ failureReasons.push(`fallback provider failed: ${message}`);
169
+ }
170
+ if (failureReasons.length === 0) {
171
+ failureReasons.push("unknown error");
172
+ }
173
+ throw new Error(
174
+ `Private API request failed (${failureReasons.join(", ")})`
175
+ );
176
+ }
177
+ }
178
+ const result = await response.json();
179
+ return parsePrivateApiBalance(result, chain);
180
+ }
181
+ });
182
+ }
183
+ function useSeedPhrase(username) {
184
+ return useQuery({
185
+ queryKey: ["ecency-wallets", "seed", username],
186
+ queryFn: async () => bip39.generateMnemonic(128)
187
+ });
188
+ }
189
+ var options = {
190
+ max: 500,
191
+ // how long to live in ms
192
+ ttl: 1e3 * 60 * 5,
193
+ // return stale items before removing from cache?
194
+ allowStale: false,
195
+ updateAgeOnGet: false,
196
+ updateAgeOnHas: false
197
+ };
198
+ var cache = new LRUCache(options);
199
+ var undefinedValue = Symbol("undefined");
200
+ var cacheSet = (key, value) => cache.set(key, value === void 0 ? undefinedValue : value);
201
+ var cacheGet = (key) => {
202
+ const v = cache.get(key);
203
+ return v === undefinedValue ? void 0 : v;
204
+ };
205
+ function getCoinGeckoPriceQueryOptions(currency) {
206
+ return queryOptions({
207
+ queryKey: ["ecency-wallets", "coingecko-price", currency],
208
+ queryFn: async () => {
209
+ let curr = currency;
210
+ switch (currency) {
211
+ case "BTC" /* BTC */:
212
+ curr = "bitcoin";
213
+ break;
214
+ case "ETH" /* ETH */:
215
+ curr = "ethereum";
216
+ break;
217
+ case "SOL" /* SOL */:
218
+ curr = "solana";
219
+ break;
220
+ case "TON" /* TON */:
221
+ curr = "ton";
222
+ break;
223
+ case "TRX" /* TRON */:
224
+ curr = "tron";
225
+ break;
226
+ case "APT" /* APT */:
227
+ curr = "aptos";
228
+ break;
229
+ case "BNB" /* BNB */:
230
+ curr = "binancecoin";
231
+ break;
232
+ case "TON" /* TON */:
233
+ curr = "the-open-network";
234
+ break;
235
+ default:
236
+ curr = currency;
237
+ }
238
+ let rate = cacheGet("gecko");
239
+ let response;
240
+ if (rate) {
241
+ response = rate;
242
+ } else {
243
+ const httpResponse = await fetch(
244
+ `https://api.coingecko.com/api/v3/simple/price?ids=${curr}&vs_currencies=usd`,
245
+ {
246
+ method: "GET"
247
+ }
248
+ );
249
+ const data = await httpResponse.json();
250
+ cacheSet("gecko", data === void 0 ? undefinedValue : data);
251
+ response = data;
252
+ }
253
+ return +response[curr].usd;
254
+ },
255
+ enabled: !!currency
256
+ });
257
+ }
258
+
259
+ // src/modules/wallets/utils/delay.ts
260
+ function delay(ms) {
261
+ return new Promise((resolve) => setTimeout(resolve, ms));
262
+ }
263
+ function getWallet(currency) {
264
+ switch (currency) {
265
+ case "BTC" /* BTC */:
266
+ return new BtcWallet();
267
+ case "ETH" /* ETH */:
268
+ case "BNB" /* BNB */:
269
+ return new EthWallet();
270
+ case "TRX" /* TRON */:
271
+ return new TrxWallet();
272
+ case "TON" /* TON */:
273
+ return new TonWallet();
274
+ case "SOL" /* SOL */:
275
+ return new SolWallet();
276
+ case "APT" /* APT */:
277
+ return new AptosWallet();
278
+ default:
279
+ return void 0;
280
+ }
281
+ }
282
+ function mnemonicToSeedBip39(value) {
283
+ return mnemonicToSeedSync(value).toString("hex");
284
+ }
285
+ var ROLE_INDEX = {
286
+ owner: 0,
287
+ active: 1,
288
+ posting: 2,
289
+ memo: 3
290
+ };
291
+ function deriveHiveKey(mnemonic, role, accountIndex = 0) {
292
+ const seed = mnemonicToSeedSync(mnemonic);
293
+ const master = bip32.fromSeed(seed);
294
+ const path = `m/44'/3054'/${accountIndex}'/0'/${ROLE_INDEX[role]}'`;
295
+ const child = master.derivePath(path);
296
+ if (!child.privateKey) {
297
+ throw new Error("[Ecency][Wallets] - hive key derivation failed");
298
+ }
299
+ const pk = PrivateKey.from(child.privateKey);
300
+ return {
301
+ privateKey: pk.toString(),
302
+ publicKey: pk.createPublic().toString()
303
+ };
304
+ }
305
+ function deriveHiveKeys(mnemonic, accountIndex = 0) {
306
+ const owner = deriveHiveKey(mnemonic, "owner", accountIndex);
307
+ const active = deriveHiveKey(mnemonic, "active", accountIndex);
308
+ const posting = deriveHiveKey(mnemonic, "posting", accountIndex);
309
+ const memo = deriveHiveKey(mnemonic, "memo", accountIndex);
310
+ return {
311
+ owner: owner.privateKey,
312
+ active: active.privateKey,
313
+ posting: posting.privateKey,
314
+ memo: memo.privateKey,
315
+ ownerPubkey: owner.publicKey,
316
+ activePubkey: active.publicKey,
317
+ postingPubkey: posting.publicKey,
318
+ memoPubkey: memo.publicKey
319
+ };
320
+ }
321
+ function deriveHiveMasterPasswordKey(username, masterPassword, role) {
322
+ const pk = PrivateKey.fromLogin(username, masterPassword, role);
323
+ return {
324
+ privateKey: pk.toString(),
325
+ publicKey: pk.createPublic().toString()
326
+ };
327
+ }
328
+ function deriveHiveMasterPasswordKeys(username, masterPassword) {
329
+ const owner = deriveHiveMasterPasswordKey(username, masterPassword, "owner");
330
+ const active = deriveHiveMasterPasswordKey(username, masterPassword, "active");
331
+ const posting = deriveHiveMasterPasswordKey(
332
+ username,
333
+ masterPassword,
334
+ "posting"
335
+ );
336
+ const memo = deriveHiveMasterPasswordKey(username, masterPassword, "memo");
337
+ return {
338
+ owner: owner.privateKey,
339
+ active: active.privateKey,
340
+ posting: posting.privateKey,
341
+ memo: memo.privateKey,
342
+ ownerPubkey: owner.publicKey,
343
+ activePubkey: active.publicKey,
344
+ postingPubkey: posting.publicKey,
345
+ memoPubkey: memo.publicKey
346
+ };
347
+ }
348
+ async function detectHiveKeyDerivation(username, seed, type = "active") {
349
+ await CONFIG.queryClient.prefetchQuery(getAccountFullQueryOptions(username));
350
+ const account = CONFIG.queryClient.getQueryData(
351
+ getAccountFullQueryOptions(username).queryKey
352
+ );
353
+ if (!account) {
354
+ throw new Error(`[Ecency][Wallets] - account ${username} not found`);
355
+ }
356
+ const bip44 = deriveHiveKeys(seed);
357
+ const bip44Active = bip44.activePubkey;
358
+ const matchBip44 = account.active.key_auths.some(
359
+ ([pub]) => pub.toString() === bip44Active
360
+ );
361
+ if (matchBip44) {
362
+ return "bip44";
363
+ }
364
+ const legacyActive = PrivateKey.fromLogin(username, seed, type).createPublic().toString();
365
+ const matchLegacy = account[type].key_auths.some(
366
+ ([pub]) => pub.toString() === legacyActive
367
+ );
368
+ if (matchLegacy) {
369
+ return "master-password";
370
+ }
371
+ return "unknown";
372
+ }
373
+ function signDigest(digest, privateKey) {
374
+ const key = PrivateKey.fromString(privateKey);
375
+ const buf = typeof digest === "string" ? Buffer.from(digest, "hex") : digest;
376
+ return key.sign(buf).toString();
377
+ }
378
+ function signTx(tx, privateKey, chainId) {
379
+ const key = PrivateKey.fromString(privateKey);
380
+ const chain = chainId ? Buffer.from(chainId, "hex") : void 0;
381
+ return cryptoUtils.signTransaction(tx, key, chain);
382
+ }
383
+ async function signTxAndBroadcast(client, tx, privateKey, chainId) {
384
+ const signed = signTx(tx, privateKey, chainId);
385
+ return client.broadcast.send(signed);
386
+ }
387
+ function encryptMemoWithKeys(privateKey, publicKey, memo) {
388
+ return Memo.encode(PrivateKey.fromString(privateKey), publicKey, memo);
389
+ }
390
+ async function encryptMemoWithAccounts(client, fromPrivateKey, toAccount, memo) {
391
+ const [account] = await client.database.getAccounts([toAccount]);
392
+ if (!account) {
393
+ throw new Error("Account not found");
394
+ }
395
+ return Memo.encode(PrivateKey.fromString(fromPrivateKey), account.memo_key, memo);
396
+ }
397
+ function decryptMemoWithKeys(privateKey, memo) {
398
+ return Memo.decode(PrivateKey.fromString(privateKey), memo);
399
+ }
400
+ var decryptMemoWithAccounts = decryptMemoWithKeys;
401
+ async function signExternalTx(currency, params) {
402
+ const wallet = getWallet(currency);
403
+ if (!wallet) throw new Error("Unsupported currency");
404
+ return wallet.signTransaction(params);
405
+ }
406
+ async function signExternalTxAndBroadcast(currency, params) {
407
+ const signed = await signExternalTx(currency, params);
408
+ switch (currency) {
409
+ case "BTC" /* BTC */: {
410
+ const res = await fetch("https://mempool.space/api/tx", {
411
+ method: "POST",
412
+ body: signed
413
+ });
414
+ if (!res.ok) throw new Error("Broadcast failed");
415
+ return res.text();
416
+ }
417
+ case "ETH" /* ETH */:
418
+ case "BNB" /* BNB */: {
419
+ const rpcUrl = currency === "ETH" /* ETH */ ? "https://rpc.ankr.com/eth" : "https://bsc-dataseed.binance.org";
420
+ const res = await fetch(rpcUrl, {
421
+ method: "POST",
422
+ headers: { "Content-Type": "application/json" },
423
+ body: JSON.stringify({
424
+ jsonrpc: "2.0",
425
+ id: 1,
426
+ method: "eth_sendRawTransaction",
427
+ params: [signed]
428
+ })
429
+ });
430
+ const json = await res.json();
431
+ if (json.error) throw new Error(json.error.message);
432
+ return json.result;
433
+ }
434
+ case "SOL" /* SOL */: {
435
+ const res = await fetch(
436
+ `https://rpc.helius.xyz/?api-key=${CONFIG.heliusApiKey}`,
437
+ {
438
+ method: "POST",
439
+ headers: { "Content-Type": "application/json" },
440
+ body: JSON.stringify({
441
+ jsonrpc: "2.0",
442
+ id: 1,
443
+ method: "sendTransaction",
444
+ params: [signed]
445
+ })
446
+ }
447
+ );
448
+ const json = await res.json();
449
+ if (json.error) throw new Error(json.error.message);
450
+ return json.result;
451
+ }
452
+ case "TRX" /* TRON */: {
453
+ const res = await fetch(
454
+ "https://api.trongrid.io/wallet/broadcasttransaction",
455
+ {
456
+ method: "POST",
457
+ headers: { "Content-Type": "application/json" },
458
+ body: typeof signed === "string" ? signed : JSON.stringify(signed)
459
+ }
460
+ );
461
+ const json = await res.json();
462
+ if (json.result === false) throw new Error(json.message);
463
+ return json.txid || json.result;
464
+ }
465
+ case "TON" /* TON */: {
466
+ const res = await fetch("https://toncenter.com/api/v2/sendTransaction", {
467
+ method: "POST",
468
+ headers: { "Content-Type": "application/json" },
469
+ body: JSON.stringify({ boc: signed })
470
+ });
471
+ const json = await res.json();
472
+ if (json.error) throw new Error(json.error.message || json.result);
473
+ return json.result;
474
+ }
475
+ case "APT" /* APT */: {
476
+ const res = await fetch(
477
+ "https://fullnode.mainnet.aptoslabs.com/v1/transactions",
478
+ {
479
+ method: "POST",
480
+ headers: { "Content-Type": "application/json" },
481
+ body: typeof signed === "string" ? signed : JSON.stringify(signed)
482
+ }
483
+ );
484
+ if (!res.ok) throw new Error("Broadcast failed");
485
+ return res.json();
486
+ }
487
+ default:
488
+ throw new Error("Unsupported currency");
489
+ }
490
+ }
491
+ function buildPsbt(tx, network, maximumFeeRate) {
492
+ return buildPsbt$1(tx, network, maximumFeeRate);
493
+ }
494
+ function buildEthTx(data) {
495
+ return data;
496
+ }
497
+ function buildSolTx(data) {
498
+ return data;
499
+ }
500
+ function buildTronTx(data) {
501
+ return data;
502
+ }
503
+ function buildTonTx(data) {
504
+ return data;
505
+ }
506
+ function buildAptTx(data) {
507
+ return data;
508
+ }
509
+ function buildExternalTx(currency, tx) {
510
+ switch (currency) {
511
+ case "BTC" /* BTC */:
512
+ return buildPsbt(tx);
513
+ case "ETH" /* ETH */:
514
+ case "BNB" /* BNB */:
515
+ return buildEthTx(tx);
516
+ case "SOL" /* SOL */:
517
+ return buildSolTx(tx);
518
+ case "TRX" /* TRON */:
519
+ return buildTronTx(tx);
520
+ case "TON" /* TON */:
521
+ return buildTonTx(tx);
522
+ case "APT" /* APT */:
523
+ return buildAptTx(tx);
524
+ default:
525
+ throw new Error("Unsupported currency");
526
+ }
527
+ }
528
+
529
+ // src/modules/wallets/utils/get-bound-fetch.ts
530
+ var cachedFetch;
531
+ function getBoundFetch() {
532
+ if (!cachedFetch) {
533
+ if (typeof globalThis.fetch !== "function") {
534
+ throw new Error("[Ecency][Wallets] - global fetch is not available");
535
+ }
536
+ cachedFetch = globalThis.fetch.bind(globalThis);
537
+ }
538
+ return cachedFetch;
539
+ }
540
+
541
+ // src/modules/wallets/queries/use-hive-keys-query.ts
542
+ function useHiveKeysQuery(username) {
543
+ const { data: seed } = useSeedPhrase(username);
544
+ return useQuery({
545
+ queryKey: ["ecenc\u0443-wallets", "hive-keys", username, seed],
546
+ staleTime: Infinity,
547
+ queryFn: async () => {
548
+ if (!seed) {
549
+ throw new Error("[Ecency][Wallets] - no seed to create Hive account");
550
+ }
551
+ const method = await detectHiveKeyDerivation(username, seed).catch(
552
+ () => "bip44"
553
+ );
554
+ const keys = method === "master-password" ? deriveHiveMasterPasswordKeys(username, seed) : deriveHiveKeys(seed);
555
+ return {
556
+ username,
557
+ ...keys
558
+ };
559
+ }
560
+ });
561
+ }
562
+
563
+ // src/modules/assets/utils/parse-asset.ts
564
+ var Symbol2 = /* @__PURE__ */ ((Symbol3) => {
565
+ Symbol3["HIVE"] = "HIVE";
566
+ Symbol3["HBD"] = "HBD";
567
+ Symbol3["VESTS"] = "VESTS";
568
+ Symbol3["SPK"] = "SPK";
569
+ return Symbol3;
570
+ })(Symbol2 || {});
571
+ var NaiMap = /* @__PURE__ */ ((NaiMap2) => {
572
+ NaiMap2["@@000000021"] = "HIVE";
573
+ NaiMap2["@@000000013"] = "HBD";
574
+ NaiMap2["@@000000037"] = "VESTS";
575
+ return NaiMap2;
576
+ })(NaiMap || {});
577
+ function parseAsset(sval) {
578
+ if (typeof sval === "string") {
579
+ const sp = sval.split(" ");
580
+ return {
581
+ amount: parseFloat(sp[0]),
582
+ // @ts-ignore
583
+ symbol: Symbol2[sp[1]]
584
+ };
585
+ } else {
586
+ return {
587
+ amount: parseFloat(sval.amount.toString()) / Math.pow(10, sval.precision),
588
+ // @ts-ignore
589
+ symbol: NaiMap[sval.nai]
590
+ };
591
+ }
592
+ }
593
+
594
+ // src/modules/assets/utils/is-empty-date.ts
595
+ function isEmptyDate(s) {
596
+ if (s === void 0) {
597
+ return true;
598
+ }
599
+ return parseInt(s.split("-")[0], 10) < 1980;
600
+ }
601
+
602
+ // src/modules/assets/utils/vests-to-hp.ts
603
+ function vestsToHp(vests, hivePerMVests) {
604
+ return vests / 1e6 * hivePerMVests;
605
+ }
606
+
607
+ // src/modules/assets/utils/reward-spk.ts
608
+ function rewardSpk(data, sstats) {
609
+ let a = 0, b = 0, c = 0, t = 0, diff = data.head_block - data.spk_block;
610
+ if (!data.spk_block) {
611
+ return 0;
612
+ } else if (diff < 28800) {
613
+ return 0;
614
+ } else {
615
+ t = diff / 28800;
616
+ a = data.gov ? simpleInterest(data.gov, t, sstats.spk_rate_lgov) : 0;
617
+ b = data.pow ? simpleInterest(data.pow, t, sstats.spk_rate_lpow) : 0;
618
+ c = simpleInterest(
619
+ (data.granted.t > 0 ? data.granted.t : 0) + (data.granting.t && data.granting.t > 0 ? data.granting.t : 0),
620
+ t,
621
+ sstats.spk_rate_ldel
622
+ );
623
+ const i = a + b + c;
624
+ if (i) {
625
+ return i;
626
+ } else {
627
+ return 0;
628
+ }
629
+ }
630
+ function simpleInterest(p, t2, r) {
631
+ const amount = p * (1 + r / 365);
632
+ const interest = amount - p;
633
+ return interest * t2;
634
+ }
635
+ }
636
+
637
+ // src/modules/assets/hive/queries/get-hive-asset-general-info-query-options.ts
638
+ function getHiveAssetGeneralInfoQueryOptions(username) {
639
+ return queryOptions({
640
+ queryKey: ["assets", "hive", "general-info", username],
641
+ staleTime: 6e4,
642
+ refetchInterval: 9e4,
643
+ queryFn: async () => {
644
+ await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());
645
+ await getQueryClient().prefetchQuery(
646
+ getAccountFullQueryOptions(username)
647
+ );
648
+ const dynamicProps = getQueryClient().getQueryData(
649
+ getDynamicPropsQueryOptions().queryKey
650
+ );
651
+ const accountData = getQueryClient().getQueryData(
652
+ getAccountFullQueryOptions(username).queryKey
653
+ );
654
+ return {
655
+ name: "HIVE",
656
+ title: "Hive",
657
+ price: dynamicProps ? dynamicProps.base / dynamicProps.quote : 0,
658
+ accountBalance: accountData ? parseAsset(accountData.balance).amount : 0
659
+ };
660
+ }
661
+ });
662
+ }
663
+ function getAPR(dynamicProps) {
664
+ const initialInflationRate = 9.5;
665
+ const initialBlock = 7e6;
666
+ const decreaseRate = 25e4;
667
+ const decreasePercentPerIncrement = 0.01;
668
+ const headBlock = dynamicProps.headBlock;
669
+ const deltaBlocks = headBlock - initialBlock;
670
+ const decreaseIncrements = deltaBlocks / decreaseRate;
671
+ let currentInflationRate = initialInflationRate - decreaseIncrements * decreasePercentPerIncrement;
672
+ if (currentInflationRate < 0.95) {
673
+ currentInflationRate = 0.95;
674
+ }
675
+ const vestingRewardPercent = dynamicProps.vestingRewardPercent / 1e4;
676
+ const virtualSupply = dynamicProps.virtualSupply;
677
+ const totalVestingFunds = dynamicProps.totalVestingFund;
678
+ return (virtualSupply * currentInflationRate * vestingRewardPercent / totalVestingFunds).toFixed(3);
679
+ }
680
+ function getHivePowerAssetGeneralInfoQueryOptions(username) {
681
+ return queryOptions({
682
+ queryKey: ["assets", "hive-power", "general-info", username],
683
+ staleTime: 6e4,
684
+ refetchInterval: 9e4,
685
+ queryFn: async () => {
686
+ await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());
687
+ await getQueryClient().prefetchQuery(
688
+ getAccountFullQueryOptions(username)
689
+ );
690
+ const dynamicProps = getQueryClient().getQueryData(
691
+ getDynamicPropsQueryOptions().queryKey
692
+ );
693
+ const accountData = getQueryClient().getQueryData(
694
+ getAccountFullQueryOptions(username).queryKey
695
+ );
696
+ if (!dynamicProps || !accountData) {
697
+ return {
698
+ name: "HP",
699
+ title: "Hive Power",
700
+ price: 0,
701
+ accountBalance: 0
702
+ };
703
+ }
704
+ return {
705
+ name: "HP",
706
+ title: "Hive Power",
707
+ price: dynamicProps ? dynamicProps.base / dynamicProps.quote : 0,
708
+ accountBalance: +vestsToHp(
709
+ parseAsset(accountData.vesting_shares).amount,
710
+ // parseAsset(accountData.delegated_vesting_shares).amount +
711
+ // parseAsset(accountData.received_vesting_shares).amount -
712
+ // nextVestingSharesWithdrawal,
713
+ dynamicProps.hivePerMVests
714
+ ).toFixed(3),
715
+ apr: getAPR(dynamicProps),
716
+ parts: [
717
+ {
718
+ name: "delegating",
719
+ balance: +vestsToHp(
720
+ parseAsset(accountData.delegated_vesting_shares).amount,
721
+ dynamicProps.hivePerMVests
722
+ ).toFixed(3)
723
+ },
724
+ {
725
+ name: "received",
726
+ balance: +vestsToHp(
727
+ parseAsset(accountData.received_vesting_shares).amount,
728
+ dynamicProps.hivePerMVests
729
+ ).toFixed(3)
730
+ }
731
+ ]
732
+ };
733
+ }
734
+ });
735
+ }
736
+ function getHbdAssetGeneralInfoQueryOptions(username) {
737
+ return queryOptions({
738
+ queryKey: ["assets", "hbd", "general-info", username],
739
+ staleTime: 6e4,
740
+ refetchInterval: 9e4,
741
+ queryFn: async () => {
742
+ await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());
743
+ await getQueryClient().prefetchQuery(
744
+ getAccountFullQueryOptions(username)
745
+ );
746
+ const accountData = getQueryClient().getQueryData(
747
+ getAccountFullQueryOptions(username).queryKey
748
+ );
749
+ const dynamicProps = getQueryClient().getQueryData(
750
+ getDynamicPropsQueryOptions().queryKey
751
+ );
752
+ if (!accountData) {
753
+ return {
754
+ name: "HBD",
755
+ title: "Hive-based dollar",
756
+ price: 1,
757
+ accountBalance: 0
758
+ };
759
+ }
760
+ return {
761
+ name: "HBD",
762
+ title: "Hive-based dollar",
763
+ price: 1,
764
+ accountBalance: parseAsset(accountData.hbd_balance).amount + parseAsset(accountData?.savings_hbd_balance).amount,
765
+ apr: ((dynamicProps?.hbdInterestRate ?? 0) / 100).toFixed(3),
766
+ parts: [
767
+ {
768
+ name: "account",
769
+ balance: parseAsset(accountData.hbd_balance).amount
770
+ },
771
+ {
772
+ name: "savings",
773
+ balance: parseAsset(accountData.savings_hbd_balance).amount
774
+ }
775
+ ]
776
+ };
777
+ }
778
+ });
779
+ }
780
+ var ops = utils.operationOrders;
781
+ var HIVE_ACCOUNT_OPERATION_GROUPS = {
782
+ transfers: [
783
+ ops.transfer,
784
+ ops.transfer_to_savings,
785
+ ops.transfer_from_savings,
786
+ ops.cancel_transfer_from_savings,
787
+ ops.recurrent_transfer,
788
+ ops.fill_recurrent_transfer,
789
+ ops.escrow_transfer,
790
+ ops.fill_recurrent_transfer
791
+ ],
792
+ "market-orders": [
793
+ ops.fill_convert_request,
794
+ ops.fill_order,
795
+ ops.fill_collateralized_convert_request,
796
+ ops.limit_order_create2,
797
+ ops.limit_order_create,
798
+ ops.limit_order_cancel
799
+ ],
800
+ interests: [ops.interest],
801
+ "stake-operations": [
802
+ ops.return_vesting_delegation,
803
+ ops.withdraw_vesting,
804
+ ops.transfer_to_vesting,
805
+ ops.set_withdraw_vesting_route,
806
+ ops.update_proposal_votes,
807
+ ops.fill_vesting_withdraw,
808
+ ops.account_witness_proxy,
809
+ ops.delegate_vesting_shares
810
+ ],
811
+ rewards: [
812
+ ops.author_reward,
813
+ ops.curation_reward,
814
+ ops.producer_reward,
815
+ ops.claim_reward_balance,
816
+ ops.comment_benefactor_reward,
817
+ ops.liquidity_reward,
818
+ ops.proposal_pay
819
+ ]};
820
+
821
+ // src/modules/assets/hive/queries/get-hive-asset-transactions-query-options.ts
822
+ function getHiveAssetTransactionsQueryOptions(username, limit = 20, group) {
823
+ return infiniteQueryOptions({
824
+ queryKey: ["assets", "hive", "transactions", username, limit, group],
825
+ initialData: { pages: [], pageParams: [] },
826
+ initialPageParam: -1,
827
+ getNextPageParam: (lastPage, __) => lastPage ? +(lastPage[lastPage.length - 1]?.num ?? 0) - 1 : -1,
828
+ queryFn: async ({ pageParam }) => {
829
+ let filters = [];
830
+ switch (group) {
831
+ case "transfers":
832
+ filters = utils.makeBitMaskFilter(
833
+ HIVE_ACCOUNT_OPERATION_GROUPS["transfers"]
834
+ );
835
+ break;
836
+ case "market-orders":
837
+ filters = utils.makeBitMaskFilter(
838
+ HIVE_ACCOUNT_OPERATION_GROUPS["market-orders"]
839
+ );
840
+ break;
841
+ case "interests":
842
+ filters = utils.makeBitMaskFilter(
843
+ HIVE_ACCOUNT_OPERATION_GROUPS["interests"]
844
+ );
845
+ break;
846
+ case "stake-operations":
847
+ filters = utils.makeBitMaskFilter(
848
+ HIVE_ACCOUNT_OPERATION_GROUPS["stake-operations"]
849
+ );
850
+ break;
851
+ case "rewards":
852
+ filters = utils.makeBitMaskFilter(
853
+ HIVE_ACCOUNT_OPERATION_GROUPS["rewards"]
854
+ );
855
+ break;
856
+ default:
857
+ filters = utils.makeBitMaskFilter([]);
858
+ }
859
+ const response = await CONFIG.hiveClient.call(
860
+ "condenser_api",
861
+ "get_account_history",
862
+ [username, pageParam, limit, ...filters]
863
+ );
864
+ return response.map(
865
+ (x) => ({
866
+ num: x[0],
867
+ type: x[1].op[0],
868
+ timestamp: x[1].timestamp,
869
+ trx_id: x[1].trx_id,
870
+ ...x[1].op[1]
871
+ })
872
+ );
873
+ },
874
+ select: ({ pages, pageParams }) => ({
875
+ pageParams,
876
+ pages: pages.map(
877
+ (page) => page.filter((item) => {
878
+ switch (item.type) {
879
+ case "author_reward":
880
+ case "comment_benefactor_reward":
881
+ const hivePayout = parseAsset(item.hive_payout);
882
+ return hivePayout.amount > 0;
883
+ case "transfer":
884
+ case "transfer_to_savings":
885
+ case "transfer_to_vesting":
886
+ case "recurrent_transfer":
887
+ return ["HIVE"].includes(item.amount);
888
+ case "fill_recurrent_transfer":
889
+ const asset = parseAsset(item.amount);
890
+ return ["HIVE"].includes(asset.symbol);
891
+ case "claim_reward_balance":
892
+ const rewardHive = parseAsset(
893
+ item.reward_hive
894
+ );
895
+ return rewardHive.amount > 0;
896
+ case "cancel_transfer_from_savings":
897
+ case "fill_order":
898
+ case "limit_order_create":
899
+ case "limit_order_cancel":
900
+ case "interest":
901
+ case "fill_convert_request":
902
+ case "fill_collateralized_convert_request":
903
+ case "proposal_pay":
904
+ case "update_proposal_votes":
905
+ case "comment_payout_update":
906
+ case "collateralized_convert":
907
+ case "account_witness_proxy":
908
+ return true;
909
+ default:
910
+ return false;
911
+ }
912
+ })
913
+ )
914
+ })
915
+ });
916
+ }
917
+ function getHivePowerAssetTransactionsQueryOptions(username, limit = 20, group) {
918
+ return infiniteQueryOptions({
919
+ ...getHiveAssetTransactionsQueryOptions(username, limit, group),
920
+ queryKey: ["assets", "hive-power", "transactions", username, limit, group],
921
+ select: ({ pages, pageParams }) => ({
922
+ pageParams,
923
+ pages: pages.map(
924
+ (page) => page.filter((item) => {
925
+ switch (item.type) {
926
+ case "author_reward":
927
+ case "comment_benefactor_reward":
928
+ const vestingPayout = parseAsset(
929
+ item.vesting_payout
930
+ );
931
+ return vestingPayout.amount > 0;
932
+ case "claim_reward_balance":
933
+ const rewardVests = parseAsset(
934
+ item.reward_vests
935
+ );
936
+ return rewardVests.amount > 0;
937
+ case "transfer":
938
+ case "transfer_to_savings":
939
+ case "transfer_to_vesting":
940
+ case "recurrent_transfer":
941
+ return ["VESTS", "HP"].includes(item.amount);
942
+ case "fill_recurrent_transfer":
943
+ const asset = parseAsset(item.amount);
944
+ return ["VESTS", "HP"].includes(asset.symbol);
945
+ case "curation_reward":
946
+ case "withdraw_vesting":
947
+ case "delegate_vesting_shares":
948
+ case "fill_vesting_withdraw":
949
+ case "return_vesting_delegation":
950
+ case "producer_reward":
951
+ case "set_withdraw_vesting_route":
952
+ return true;
953
+ default:
954
+ return false;
955
+ }
956
+ })
957
+ )
958
+ })
959
+ });
960
+ }
961
+ function getHbdAssetTransactionsQueryOptions(username, limit = 20, group) {
962
+ return infiniteQueryOptions({
963
+ ...getHiveAssetTransactionsQueryOptions(username, limit, group),
964
+ queryKey: ["assets", "hbd", "transactions", username, limit, group],
965
+ select: ({ pages, pageParams }) => ({
966
+ pageParams,
967
+ pages: pages.map(
968
+ (page) => page.filter((item) => {
969
+ switch (item.type) {
970
+ case "author_reward":
971
+ case "comment_benefactor_reward":
972
+ const hbdPayout = parseAsset(item.hbd_payout);
973
+ return hbdPayout.amount > 0;
974
+ case "claim_reward_balance":
975
+ const rewardHbd = parseAsset(
976
+ item.reward_hbd
977
+ );
978
+ return rewardHbd.amount > 0;
979
+ case "transfer":
980
+ case "transfer_to_savings":
981
+ case "transfer_to_vesting":
982
+ case "recurrent_transfer":
983
+ return ["HBD"].includes(item.amount);
984
+ case "fill_recurrent_transfer":
985
+ const asset = parseAsset(item.amount);
986
+ return ["HBD"].includes(asset.symbol);
987
+ case "comment_reward":
988
+ case "effective_comment_vote":
989
+ return true;
990
+ default:
991
+ return false;
992
+ }
993
+ })
994
+ )
995
+ })
996
+ });
997
+ }
998
+ function getHiveAssetMetricQueryOptions(bucketSeconds = 86400) {
999
+ return infiniteQueryOptions({
1000
+ queryKey: ["assets", "hive", "metrics", bucketSeconds],
1001
+ queryFn: async ({ pageParam: [startDate, endDate] }) => {
1002
+ const apiData = await CONFIG.hiveClient.call(
1003
+ "condenser_api",
1004
+ "get_market_history",
1005
+ [
1006
+ bucketSeconds,
1007
+ dayjs(startDate).format("YYYY-MM-DDTHH:mm:ss"),
1008
+ dayjs(endDate).format("YYYY-MM-DDTHH:mm:ss")
1009
+ ]
1010
+ );
1011
+ return apiData.map(({ hive, non_hive, open }) => ({
1012
+ close: non_hive.close / hive.close,
1013
+ open: non_hive.open / hive.open,
1014
+ low: non_hive.low / hive.low,
1015
+ high: non_hive.high / hive.high,
1016
+ volume: hive.volume,
1017
+ time: new Date(open)
1018
+ }));
1019
+ },
1020
+ initialPageParam: [
1021
+ // Fetch at least 8 hours or given interval
1022
+ dayjs().subtract(Math.max(100 * bucketSeconds, 28800), "second").toDate(),
1023
+ /* @__PURE__ */ new Date()
1024
+ ],
1025
+ getNextPageParam: (_, __, [prevStartDate]) => [
1026
+ dayjs(prevStartDate.getTime()).subtract(Math.max(100 * bucketSeconds, 28800), "second").toDate(),
1027
+ dayjs(prevStartDate.getTime()).subtract(bucketSeconds, "second").toDate()
1028
+ ]
1029
+ });
1030
+ }
1031
+ function getHiveAssetWithdrawalRoutesQueryOptions(username) {
1032
+ return queryOptions({
1033
+ queryKey: ["assets", "hive", "withdrawal-routes", username],
1034
+ queryFn: () => CONFIG.hiveClient.database.call("get_withdraw_routes", [
1035
+ username,
1036
+ "outgoing"
1037
+ ])
1038
+ });
1039
+ }
1040
+ function getHivePowerDelegatesInfiniteQueryOptions(username, limit = 50) {
1041
+ return queryOptions({
1042
+ queryKey: ["assets", "hive-power", "delegates", username],
1043
+ enabled: !!username,
1044
+ queryFn: () => CONFIG.hiveClient.database.call("get_vesting_delegations", [
1045
+ username,
1046
+ "",
1047
+ limit
1048
+ ])
1049
+ });
1050
+ }
1051
+ function getHivePowerDelegatingsQueryOptions(username) {
1052
+ return queryOptions({
1053
+ queryKey: ["assets", "hive-power", "delegatings", username],
1054
+ queryFn: async () => {
1055
+ const response = await fetch(
1056
+ CONFIG.privateApiHost + `/private-api/received-vesting/${username}`,
1057
+ {
1058
+ headers: {
1059
+ "Content-Type": "application/json"
1060
+ }
1061
+ }
1062
+ );
1063
+ return (await response.json()).list;
1064
+ },
1065
+ select: (data) => data.sort(
1066
+ (a, b) => parseAsset(b.vesting_shares).amount - parseAsset(a.vesting_shares).amount
1067
+ )
1068
+ });
1069
+ }
1070
+ async function transferHive(payload) {
1071
+ const parsedAsset = parseAsset(payload.amount);
1072
+ const token = parsedAsset.symbol;
1073
+ if (payload.type === "key" && "key" in payload) {
1074
+ const { key, type, ...params } = payload;
1075
+ return CONFIG.hiveClient.broadcast.transfer(
1076
+ {
1077
+ from: params.from,
1078
+ to: params.to,
1079
+ amount: params.amount,
1080
+ memo: params.memo
1081
+ },
1082
+ key
1083
+ );
1084
+ } else if (payload.type === "keychain") {
1085
+ return new Promise(
1086
+ (resolve, reject) => window.hive_keychain?.requestTransfer(
1087
+ payload.from,
1088
+ payload.to,
1089
+ payload.amount,
1090
+ payload.memo,
1091
+ token,
1092
+ (resp) => {
1093
+ if (!resp.success) {
1094
+ reject({ message: "Operation cancelled" });
1095
+ }
1096
+ resolve(resp);
1097
+ },
1098
+ true,
1099
+ null
1100
+ )
1101
+ );
1102
+ } else {
1103
+ return hs.sendOperation(
1104
+ [
1105
+ "transfer",
1106
+ {
1107
+ from: payload.from,
1108
+ to: payload.to,
1109
+ amount: payload.amount,
1110
+ memo: payload.memo
1111
+ }
1112
+ ],
1113
+ { callback: `https://ecency.com/@${payload.from}/wallet` },
1114
+ () => {
1115
+ }
1116
+ );
1117
+ }
1118
+ }
1119
+ async function transferToSavingsHive(payload) {
1120
+ if (payload.type === "key" && "key" in payload) {
1121
+ const { key, type, ...params } = payload;
1122
+ return CONFIG.hiveClient.broadcast.sendOperations(
1123
+ [["transfer_to_savings", params]],
1124
+ key
1125
+ );
1126
+ } else if (payload.type === "keychain") {
1127
+ return Keychain.broadcast(
1128
+ payload.from,
1129
+ [["transfer_to_savings", payload]],
1130
+ "Active"
1131
+ );
1132
+ } else {
1133
+ return hs.sendOperation(
1134
+ ["transfer_to_savings", payload],
1135
+ { callback: `https://ecency.com/@${payload.from}/wallet` },
1136
+ () => {
1137
+ }
1138
+ );
1139
+ }
1140
+ }
1141
+ async function powerUpHive(payload) {
1142
+ if (payload.type === "key" && "key" in payload) {
1143
+ const { key, type, ...params } = payload;
1144
+ return CONFIG.hiveClient.broadcast.sendOperations(
1145
+ [["transfer_to_vesting", params]],
1146
+ key
1147
+ );
1148
+ } else if (payload.type === "keychain") {
1149
+ return Keychain.broadcast(
1150
+ payload.from,
1151
+ [["transfer_to_vesting", payload]],
1152
+ "Active"
1153
+ );
1154
+ } else {
1155
+ return hs.sendOperation(
1156
+ ["transfer_to_vesting", payload],
1157
+ { callback: `https://ecency.com/@${payload.from}/wallet` },
1158
+ () => {
1159
+ }
1160
+ );
1161
+ }
1162
+ }
1163
+ async function delegateHive(payload) {
1164
+ const operationPayload = {
1165
+ delegator: payload.from,
1166
+ delegatee: payload.to,
1167
+ vesting_shares: payload.amount
1168
+ };
1169
+ if (payload.type === "key" && "key" in payload) {
1170
+ const { key } = payload;
1171
+ return CONFIG.hiveClient.broadcast.sendOperations(
1172
+ [["delegate_vesting_shares", operationPayload]],
1173
+ key
1174
+ );
1175
+ } else if (payload.type === "keychain") {
1176
+ return Keychain.broadcast(
1177
+ payload.from,
1178
+ [["delegate_vesting_shares", operationPayload]],
1179
+ "Active"
1180
+ );
1181
+ } else {
1182
+ return hs.sendOperation(
1183
+ ["delegate_vesting_shares", operationPayload],
1184
+ { callback: `https://ecency.com/@${payload.from}/wallet` },
1185
+ () => {
1186
+ }
1187
+ );
1188
+ }
1189
+ }
1190
+ async function powerDownHive(payload) {
1191
+ const operationPayload = {
1192
+ account: payload.from,
1193
+ vesting_shares: payload.amount
1194
+ };
1195
+ if (payload.type === "key" && "key" in payload) {
1196
+ const { key } = payload;
1197
+ return CONFIG.hiveClient.broadcast.sendOperations(
1198
+ [["withdraw_vesting", operationPayload]],
1199
+ key
1200
+ );
1201
+ } else if (payload.type === "keychain") {
1202
+ return Keychain.broadcast(
1203
+ payload.from,
1204
+ [["withdraw_vesting", operationPayload]],
1205
+ "Active"
1206
+ );
1207
+ } else {
1208
+ return hs.sendOperation(
1209
+ ["withdraw_vesting", operationPayload],
1210
+ { callback: `https://ecency.com/@${payload.from}/wallet` },
1211
+ () => {
1212
+ }
1213
+ );
1214
+ }
1215
+ }
1216
+ async function withdrawVestingRouteHive(payload) {
1217
+ if (payload.type === "key" && "key" in payload) {
1218
+ const { key, type: type2, ...params2 } = payload;
1219
+ return CONFIG.hiveClient.broadcast.sendOperations(
1220
+ [["set_withdraw_vesting_route", params2]],
1221
+ key
1222
+ );
1223
+ }
1224
+ if (payload.type === "keychain") {
1225
+ const { type: type2, ...params2 } = payload;
1226
+ return Keychain.broadcast(
1227
+ params2.from_account,
1228
+ [["set_withdraw_vesting_route", params2]],
1229
+ "Active"
1230
+ );
1231
+ }
1232
+ const { type, ...params } = payload;
1233
+ return hs.sendOperation(
1234
+ ["set_withdraw_vesting_route", params],
1235
+ { callback: `https://ecency.com/@${params.from_account}/wallet` },
1236
+ () => {
1237
+ }
1238
+ );
1239
+ }
1240
+ function useClaimRewards(username, onSuccess) {
1241
+ const { data } = useQuery(getAccountFullQueryOptions(username));
1242
+ const queryClient = useQueryClient();
1243
+ return useBroadcastMutation(
1244
+ ["assets", "hive", "claim-rewards", data?.name],
1245
+ username,
1246
+ () => {
1247
+ if (!data) {
1248
+ throw new Error("Failed to fetch account while claiming balance");
1249
+ }
1250
+ const {
1251
+ reward_hive_balance: hiveBalance,
1252
+ reward_hbd_balance: hbdBalance,
1253
+ reward_vesting_balance: vestingBalance
1254
+ } = data;
1255
+ return [
1256
+ [
1257
+ "claim_reward_balance",
1258
+ {
1259
+ account: username,
1260
+ reward_hive: hiveBalance,
1261
+ reward_hbd: hbdBalance,
1262
+ reward_vests: vestingBalance
1263
+ }
1264
+ ]
1265
+ ];
1266
+ },
1267
+ async () => {
1268
+ onSuccess();
1269
+ await delay(1e3);
1270
+ queryClient.invalidateQueries({
1271
+ queryKey: getAccountFullQueryOptions(username).queryKey
1272
+ });
1273
+ queryClient.invalidateQueries({
1274
+ queryKey: getHivePowerAssetGeneralInfoQueryOptions(username).queryKey
1275
+ });
1276
+ }
1277
+ );
1278
+ }
1279
+
1280
+ // src/modules/assets/types/asset-operation.ts
1281
+ var AssetOperation = /* @__PURE__ */ ((AssetOperation2) => {
1282
+ AssetOperation2["Transfer"] = "transfer";
1283
+ AssetOperation2["TransferToSavings"] = "transfer-saving";
1284
+ AssetOperation2["Delegate"] = "delegate";
1285
+ AssetOperation2["PowerUp"] = "power-up";
1286
+ AssetOperation2["PowerDown"] = "power-down";
1287
+ AssetOperation2["WithdrawRoutes"] = "withdraw-saving";
1288
+ AssetOperation2["Swap"] = "swap";
1289
+ AssetOperation2["Gift"] = "gift";
1290
+ AssetOperation2["Promote"] = "promote";
1291
+ AssetOperation2["Claim"] = "claim";
1292
+ AssetOperation2["Buy"] = "buy";
1293
+ AssetOperation2["LockLiquidity"] = "lock";
1294
+ AssetOperation2["Stake"] = "stake";
1295
+ AssetOperation2["Unstake"] = "unstake";
1296
+ AssetOperation2["Undelegate"] = "undelegate";
1297
+ return AssetOperation2;
1298
+ })(AssetOperation || {});
1299
+ async function transferSpk(payload) {
1300
+ const json = JSON.stringify({
1301
+ to: payload.to,
1302
+ amount: +payload.amount * 1e3,
1303
+ ...typeof payload.memo === "string" ? { memo: payload.memo } : {}
1304
+ });
1305
+ const op = {
1306
+ id: payload.id,
1307
+ json,
1308
+ required_auths: [payload.from],
1309
+ required_posting_auths: []
1310
+ };
1311
+ if (payload.type === "key" && "key" in payload) {
1312
+ const { key } = payload;
1313
+ return CONFIG.hiveClient.broadcast.json(op, key);
1314
+ } else if (payload.type === "keychain") {
1315
+ return Keychain.customJson(
1316
+ payload.from,
1317
+ payload.id,
1318
+ "Active",
1319
+ json,
1320
+ payload.to
1321
+ );
1322
+ } else {
1323
+ const { amount } = parseAsset(payload.amount);
1324
+ return hs.sign(
1325
+ "custom_json",
1326
+ {
1327
+ authority: "active",
1328
+ required_auths: `["${payload.from}"]`,
1329
+ required_posting_auths: "[]",
1330
+ id: payload.id,
1331
+ json: JSON.stringify({
1332
+ to: payload.to,
1333
+ amount: +amount * 1e3,
1334
+ ...typeof payload.memo === "string" ? { memo: payload.memo } : {}
1335
+ })
1336
+ },
1337
+ `https://ecency.com/@${payload.from}/wallet`
1338
+ );
1339
+ }
1340
+ }
1341
+ var lockLarynx = async (payload) => {
1342
+ const json = JSON.stringify({ amount: +payload.amount * 1e3 });
1343
+ const op = {
1344
+ id: payload.mode === "lock" ? "spkcc_gov_up" : "spkcc_gov_down",
1345
+ json,
1346
+ required_auths: [payload.from],
1347
+ required_posting_auths: []
1348
+ };
1349
+ if (payload.type === "key" && "key" in payload) {
1350
+ const { key } = payload;
1351
+ return CONFIG.hiveClient.broadcast.json(op, key);
1352
+ } else if (payload.type === "keychain") {
1353
+ return Keychain.customJson(
1354
+ payload.from,
1355
+ op.id,
1356
+ "Active",
1357
+ json,
1358
+ payload.from
1359
+ );
1360
+ } else {
1361
+ const { amount } = parseAsset(payload.amount);
1362
+ return hs.sign(
1363
+ "custom_json",
1364
+ {
1365
+ authority: "active",
1366
+ required_auths: `["${payload.from}"]`,
1367
+ required_posting_auths: "[]",
1368
+ id: op.id,
1369
+ json: JSON.stringify({ amount: +amount * 1e3 })
1370
+ },
1371
+ `https://ecency.com/@${payload.from}/wallet`
1372
+ );
1373
+ }
1374
+ };
1375
+ async function powerUpLarynx(payload) {
1376
+ const json = JSON.stringify({ amount: +payload.amount * 1e3 });
1377
+ const op = {
1378
+ id: `spkcc_power_${payload.mode}`,
1379
+ json,
1380
+ required_auths: [payload.from],
1381
+ required_posting_auths: []
1382
+ };
1383
+ if (payload.type === "key" && "key" in payload) {
1384
+ const { key } = payload;
1385
+ return CONFIG.hiveClient.broadcast.json(op, key);
1386
+ } else if (payload.type === "keychain") {
1387
+ return Keychain.customJson(
1388
+ payload.from,
1389
+ `spkcc_power_${payload.mode}`,
1390
+ "Active",
1391
+ json,
1392
+ ""
1393
+ );
1394
+ } else {
1395
+ const { amount } = parseAsset(payload.amount);
1396
+ return hs.sign(
1397
+ "custom_json",
1398
+ {
1399
+ authority: "active",
1400
+ required_auths: `["${payload.from}"]`,
1401
+ required_posting_auths: "[]",
1402
+ id: `spkcc_power_${payload.mode}`,
1403
+ json: JSON.stringify({ amount: +amount * 1e3 })
1404
+ },
1405
+ `https://ecency.com/@${payload.from}/wallet`
1406
+ );
1407
+ }
1408
+ }
1409
+ function getSpkMarketsQueryOptions() {
1410
+ return queryOptions({
1411
+ queryKey: ["assets", "spk", "markets"],
1412
+ staleTime: 6e4,
1413
+ refetchInterval: 9e4,
1414
+ queryFn: async () => {
1415
+ const response = await fetch(`${CONFIG.spkNode}/markets`);
1416
+ const data = await response.json();
1417
+ return {
1418
+ list: Object.entries(data.markets.node).map(([name, node]) => ({
1419
+ name,
1420
+ status: node.lastGood >= data.head_block - 1200 ? "\u{1F7E9}" : node.lastGood > data.head_block - 28800 ? "\u{1F7E8}" : "\u{1F7E5}"
1421
+ })),
1422
+ raw: data
1423
+ };
1424
+ }
1425
+ });
1426
+ }
1427
+ function getSpkWalletQueryOptions(username) {
1428
+ return queryOptions({
1429
+ queryKey: ["assets", "spk", "wallet", username],
1430
+ queryFn: async () => {
1431
+ const response = await fetch(CONFIG.spkNode + `/@${username}`);
1432
+ return response.json();
1433
+ },
1434
+ enabled: !!username,
1435
+ staleTime: 6e4,
1436
+ refetchInterval: 9e4
1437
+ });
1438
+ }
1439
+
1440
+ // src/modules/assets/spk/queries/get-larynx-asset-general-info-query-options.ts
1441
+ function format(value) {
1442
+ return value.toFixed(3);
1443
+ }
1444
+ function getLarynxAssetGeneralInfoQueryOptions(username) {
1445
+ return queryOptions({
1446
+ queryKey: ["assets", "larynx", "general-info", username],
1447
+ staleTime: 6e4,
1448
+ refetchInterval: 9e4,
1449
+ queryFn: async () => {
1450
+ await getQueryClient().prefetchQuery(getSpkWalletQueryOptions(username));
1451
+ await getQueryClient().prefetchQuery(getSpkMarketsQueryOptions());
1452
+ await getQueryClient().prefetchQuery(
1453
+ getHiveAssetGeneralInfoQueryOptions(username)
1454
+ );
1455
+ const wallet = getQueryClient().getQueryData(
1456
+ getSpkWalletQueryOptions(username).queryKey
1457
+ );
1458
+ const market = getQueryClient().getQueryData(
1459
+ getSpkMarketsQueryOptions().queryKey
1460
+ );
1461
+ const hiveAsset = getQueryClient().getQueryData(
1462
+ getHiveAssetGeneralInfoQueryOptions(username).queryKey
1463
+ );
1464
+ if (!wallet || !market) {
1465
+ return {
1466
+ name: "LARYNX",
1467
+ title: "SPK Network / LARYNX",
1468
+ price: 1,
1469
+ accountBalance: 0
1470
+ };
1471
+ }
1472
+ const price = +format(
1473
+ wallet.balance / 1e3 * +wallet.tick * (hiveAsset?.price ?? 0)
1474
+ );
1475
+ const accountBalance = +format(wallet.balance / 1e3);
1476
+ return {
1477
+ name: "LARYNX",
1478
+ layer: "SPK",
1479
+ title: "LARYNX",
1480
+ price: price / accountBalance,
1481
+ accountBalance
1482
+ };
1483
+ }
1484
+ });
1485
+ }
1486
+ function format2(value) {
1487
+ return value.toFixed(3);
1488
+ }
1489
+ function getSpkAssetGeneralInfoQueryOptions(username) {
1490
+ return queryOptions({
1491
+ queryKey: ["assets", "spk", "general-info", username],
1492
+ staleTime: 6e4,
1493
+ refetchInterval: 9e4,
1494
+ queryFn: async () => {
1495
+ await getQueryClient().prefetchQuery(getSpkWalletQueryOptions(username));
1496
+ await getQueryClient().prefetchQuery(getSpkMarketsQueryOptions());
1497
+ await getQueryClient().prefetchQuery(
1498
+ getHiveAssetGeneralInfoQueryOptions(username)
1499
+ );
1500
+ const wallet = getQueryClient().getQueryData(
1501
+ getSpkWalletQueryOptions(username).queryKey
1502
+ );
1503
+ const market = getQueryClient().getQueryData(
1504
+ getSpkMarketsQueryOptions().queryKey
1505
+ );
1506
+ const hiveAsset = getQueryClient().getQueryData(
1507
+ getHiveAssetGeneralInfoQueryOptions(username).queryKey
1508
+ );
1509
+ if (!wallet || !market) {
1510
+ return {
1511
+ name: "SPK",
1512
+ title: "SPK Network",
1513
+ price: 1,
1514
+ accountBalance: 0
1515
+ };
1516
+ }
1517
+ const price = +format2(
1518
+ (wallet.gov + wallet.spk) / 1e3 * +wallet.tick * (hiveAsset?.price ?? 0)
1519
+ );
1520
+ const accountBalance = +format2(
1521
+ (wallet.spk + rewardSpk(
1522
+ wallet,
1523
+ market.raw.stats || {
1524
+ spk_rate_lgov: "0.001",
1525
+ spk_rate_lpow: format2(
1526
+ parseFloat(market.raw.stats.spk_rate_lpow) * 100
1527
+ ),
1528
+ spk_rate_ldel: format2(
1529
+ parseFloat(market.raw.stats.spk_rate_ldel) * 100
1530
+ )
1531
+ }
1532
+ )) / 1e3
1533
+ );
1534
+ return {
1535
+ name: "SPK",
1536
+ title: "SPK Network",
1537
+ price: price / accountBalance,
1538
+ accountBalance
1539
+ };
1540
+ }
1541
+ });
1542
+ }
1543
+ function format3(value) {
1544
+ return value.toFixed(3);
1545
+ }
1546
+ function getLarynxPowerAssetGeneralInfoQueryOptions(username) {
1547
+ return queryOptions({
1548
+ queryKey: ["assets", "larynx-power", "general-info", username],
1549
+ staleTime: 6e4,
1550
+ refetchInterval: 9e4,
1551
+ queryFn: async () => {
1552
+ await getQueryClient().prefetchQuery(getSpkWalletQueryOptions(username));
1553
+ await getQueryClient().prefetchQuery(getSpkMarketsQueryOptions());
1554
+ await getQueryClient().prefetchQuery(
1555
+ getHiveAssetGeneralInfoQueryOptions(username)
1556
+ );
1557
+ const wallet = getQueryClient().getQueryData(
1558
+ getSpkWalletQueryOptions(username).queryKey
1559
+ );
1560
+ const market = getQueryClient().getQueryData(
1561
+ getSpkMarketsQueryOptions().queryKey
1562
+ );
1563
+ const hiveAsset = getQueryClient().getQueryData(
1564
+ getHiveAssetGeneralInfoQueryOptions(username).queryKey
1565
+ );
1566
+ if (!wallet || !market) {
1567
+ return {
1568
+ name: "LP",
1569
+ title: "SPK Network / LARYNX Power",
1570
+ price: 1,
1571
+ accountBalance: 0
1572
+ };
1573
+ }
1574
+ const price = +format3(
1575
+ wallet.poweredUp / 1e3 * +wallet.tick * (hiveAsset?.price ?? 0)
1576
+ );
1577
+ const accountBalance = +format3(wallet.poweredUp / 1e3);
1578
+ return {
1579
+ name: "LP",
1580
+ title: "LARYNX Power",
1581
+ layer: "SPK",
1582
+ price: price / accountBalance,
1583
+ accountBalance,
1584
+ parts: [
1585
+ {
1586
+ name: "delegating",
1587
+ balance: wallet.granting?.t ? +format3(wallet.granting.t / 1e3) : 0
1588
+ },
1589
+ {
1590
+ name: "recieved",
1591
+ balance: wallet.granted?.t ? +format3(wallet.granted.t / 1e3) : 0
1592
+ }
1593
+ ]
1594
+ };
1595
+ }
1596
+ });
1597
+ }
1598
+ function getHiveEngineTokensMetadataQueryOptions(tokens) {
1599
+ return queryOptions({
1600
+ queryKey: ["assets", "hive-engine", "metadata-list", tokens],
1601
+ staleTime: 6e4,
1602
+ refetchInterval: 9e4,
1603
+ queryFn: async () => {
1604
+ const response = await fetch(
1605
+ `${CONFIG.privateApiHost}/private-api/engine-api`,
1606
+ {
1607
+ method: "POST",
1608
+ body: JSON.stringify({
1609
+ jsonrpc: "2.0",
1610
+ method: "find",
1611
+ params: {
1612
+ contract: "tokens",
1613
+ table: "tokens",
1614
+ query: {
1615
+ symbol: { $in: tokens }
1616
+ }
1617
+ },
1618
+ id: 2
1619
+ }),
1620
+ headers: { "Content-type": "application/json" }
1621
+ }
1622
+ );
1623
+ const data = await response.json();
1624
+ return data.result;
1625
+ }
1626
+ });
1627
+ }
1628
+
1629
+ // src/modules/wallets/consts/hive-engine-tokens.ts
1630
+ var HiveEngineTokens = [
1631
+ "LEO",
1632
+ "ARCHON",
1633
+ "WAIV",
1634
+ "CHOISM",
1635
+ "CCC",
1636
+ "POB",
1637
+ "PHOTO",
1638
+ "LUV",
1639
+ "ALIVE",
1640
+ "LOLZ",
1641
+ "CENT",
1642
+ "FUN",
1643
+ "VYB",
1644
+ "VKBT",
1645
+ "BUIDL",
1646
+ "NEOXAG",
1647
+ "BEE",
1648
+ "PIMP",
1649
+ "PEPE",
1650
+ "PAY",
1651
+ "SPT",
1652
+ "ONEUP",
1653
+ "SPORTS",
1654
+ "CURE"
1655
+ ];
1656
+ function getHiveEngineTokensBalancesQueryOptions(username) {
1657
+ return queryOptions({
1658
+ queryKey: ["assets", "hive-engine", "balances", username],
1659
+ staleTime: 6e4,
1660
+ refetchInterval: 9e4,
1661
+ queryFn: async () => {
1662
+ const response = await fetch(
1663
+ `${CONFIG.privateApiHost}/private-api/engine-api`,
1664
+ {
1665
+ method: "POST",
1666
+ body: JSON.stringify({
1667
+ jsonrpc: "2.0",
1668
+ method: "find",
1669
+ params: {
1670
+ contract: "tokens",
1671
+ table: "balances",
1672
+ query: {
1673
+ account: username
1674
+ }
1675
+ },
1676
+ id: 1
1677
+ }),
1678
+ headers: { "Content-type": "application/json" }
1679
+ }
1680
+ );
1681
+ const data = await response.json();
1682
+ return data.result;
1683
+ }
1684
+ });
1685
+ }
1686
+ function getHiveEngineTokensMarketQueryOptions() {
1687
+ return queryOptions({
1688
+ queryKey: ["assets", "hive-engine", "markets"],
1689
+ staleTime: 6e4,
1690
+ refetchInterval: 9e4,
1691
+ queryFn: async () => {
1692
+ const response = await fetch(
1693
+ `${CONFIG.privateApiHost}/private-api/engine-api`,
1694
+ {
1695
+ method: "POST",
1696
+ body: JSON.stringify({
1697
+ jsonrpc: "2.0",
1698
+ method: "find",
1699
+ params: {
1700
+ contract: "market",
1701
+ table: "metrics",
1702
+ query: {}
1703
+ },
1704
+ id: 1
1705
+ }),
1706
+ headers: { "Content-type": "application/json" }
1707
+ }
1708
+ );
1709
+ const data = await response.json();
1710
+ return data.result;
1711
+ }
1712
+ });
1713
+ }
1714
+
1715
+ // src/modules/assets/hive-engine/queries/get-hive-engine-token-general-info-query-options.ts
1716
+ function getHiveEngineTokenGeneralInfoQueryOptions(username, symbol) {
1717
+ return queryOptions({
1718
+ queryKey: ["assets", "hive-engine", symbol, "general-info", username],
1719
+ enabled: !!symbol && !!username,
1720
+ staleTime: 6e4,
1721
+ refetchInterval: 9e4,
1722
+ queryFn: async () => {
1723
+ if (!symbol || !username) {
1724
+ throw new Error(
1725
+ "[SDK][Wallets] \u2013 hive engine token or username missed"
1726
+ );
1727
+ }
1728
+ const hiveQuery = getHiveAssetGeneralInfoQueryOptions(username);
1729
+ await getQueryClient().prefetchQuery(hiveQuery);
1730
+ const hiveData = getQueryClient().getQueryData(
1731
+ hiveQuery.queryKey
1732
+ );
1733
+ const metadataQuery = getHiveEngineTokensMetadataQueryOptions(HiveEngineTokens);
1734
+ await getQueryClient().prefetchQuery(metadataQuery);
1735
+ const metadataList = getQueryClient().getQueryData(metadataQuery.queryKey);
1736
+ const balancesQuery = getHiveEngineTokensBalancesQueryOptions(username);
1737
+ await getQueryClient().prefetchQuery(balancesQuery);
1738
+ const balanceList = getQueryClient().getQueryData(balancesQuery.queryKey);
1739
+ const marketQuery = getHiveEngineTokensMarketQueryOptions();
1740
+ await getQueryClient().prefetchQuery(marketQuery);
1741
+ const marketList = getQueryClient().getQueryData(marketQuery.queryKey);
1742
+ const metadata = metadataList?.find((i) => i.symbol === symbol);
1743
+ const balance = balanceList?.find((i) => i.symbol === symbol);
1744
+ const market = marketList?.find((i) => i.symbol === symbol);
1745
+ const lastPrice = +(market?.lastPrice ?? "0");
1746
+ return {
1747
+ name: symbol,
1748
+ title: metadata?.name ?? "",
1749
+ price: lastPrice === 0 ? 0 : Number(lastPrice * (hiveData?.price ?? 0)),
1750
+ accountBalance: parseFloat(balance?.balance ?? "0"),
1751
+ layer: "ENGINE"
1752
+ };
1753
+ }
1754
+ });
1755
+ }
1756
+ function getHiveEngineTokenTransactionsQueryOptions(username, symbol, limit = 20) {
1757
+ return infiniteQueryOptions({
1758
+ queryKey: ["assets", "hive-engine", symbol, "transactions", username],
1759
+ enabled: !!symbol && !!username,
1760
+ initialPageParam: 0,
1761
+ getNextPageParam: (lastPage) => (lastPage?.length ?? 0) + limit,
1762
+ queryFn: async ({ pageParam }) => {
1763
+ if (!symbol || !username) {
1764
+ throw new Error(
1765
+ "[SDK][Wallets] \u2013 hive engine token or username missed"
1766
+ );
1767
+ }
1768
+ const url = new URL(
1769
+ `${CONFIG.privateApiHost}/private-api/engine-account-history`
1770
+ );
1771
+ url.searchParams.set("account", username);
1772
+ url.searchParams.set("symbol", symbol);
1773
+ url.searchParams.set("limit", limit.toString());
1774
+ url.searchParams.set("offset", pageParam.toString());
1775
+ const response = await fetch(url, {
1776
+ method: "GET",
1777
+ headers: { "Content-type": "application/json" }
1778
+ });
1779
+ return await response.json();
1780
+ }
1781
+ });
1782
+ }
1783
+ function getHiveEngineTokensMetricsQueryOptions(symbol, interval = "daily") {
1784
+ return queryOptions({
1785
+ queryKey: ["assets", "hive-engine", symbol],
1786
+ staleTime: 6e4,
1787
+ refetchInterval: 9e4,
1788
+ queryFn: async () => {
1789
+ const url = new URL(
1790
+ `${CONFIG.privateApiHost}/private-api/engine-chart-api`
1791
+ );
1792
+ url.searchParams.set("symbol", symbol);
1793
+ url.searchParams.set("interval", interval);
1794
+ const response = await fetch(url, {
1795
+ headers: { "Content-type": "application/json" }
1796
+ });
1797
+ return await response.json();
1798
+ }
1799
+ });
1800
+ }
1801
+ async function delegateEngineToken(payload) {
1802
+ const parsedAsset = parseAsset(payload.amount);
1803
+ const quantity = parsedAsset.amount.toString();
1804
+ if (payload.type === "key" && "key" in payload) {
1805
+ const { key, type, ...params } = payload;
1806
+ const op = {
1807
+ id: "ssc-mainnet-hive",
1808
+ json: JSON.stringify({
1809
+ contractName: "tokens",
1810
+ contractAction: "delegate",
1811
+ contractPayload: {
1812
+ symbol: params.asset,
1813
+ to: params.to,
1814
+ quantity
1815
+ }
1816
+ }),
1817
+ required_auths: [params.from],
1818
+ required_posting_auths: []
1819
+ };
1820
+ return CONFIG.hiveClient.broadcast.json(op, key);
1821
+ } else if (payload.type === "keychain") {
1822
+ return new Promise(
1823
+ (resolve, reject) => window.hive_keychain?.requestCustomJson(
1824
+ payload.from,
1825
+ "ssc-mainnet-hive",
1826
+ "Active",
1827
+ JSON.stringify({
1828
+ contractName: "tokens",
1829
+ contractAction: "delegate",
1830
+ contractPayload: {
1831
+ symbol: payload.asset,
1832
+ to: payload.to,
1833
+ quantity
1834
+ }
1835
+ }),
1836
+ "Token Delegation",
1837
+ (resp) => {
1838
+ if (!resp.success) {
1839
+ reject({ message: "Operation cancelled" });
1840
+ }
1841
+ resolve(resp);
1842
+ }
1843
+ )
1844
+ );
1845
+ } else {
1846
+ return hs.sendOperation(
1847
+ [
1848
+ "custom_json",
1849
+ {
1850
+ id: "ssc-mainnet-hive",
1851
+ required_auths: [payload.from],
1852
+ required_posting_auths: [],
1853
+ json: JSON.stringify({
1854
+ contractName: "tokens",
1855
+ contractAction: "delegate",
1856
+ contractPayload: {
1857
+ symbol: payload.asset,
1858
+ to: payload.to,
1859
+ quantity
1860
+ }
1861
+ })
1862
+ }
1863
+ ],
1864
+ { callback: `https://ecency.com/@${payload.from}/wallet` },
1865
+ () => {
1866
+ }
1867
+ );
1868
+ }
1869
+ }
1870
+ async function undelegateEngineToken(payload) {
1871
+ const parsedAsset = parseAsset(payload.amount);
1872
+ const quantity = parsedAsset.amount.toString();
1873
+ if (payload.type === "key" && "key" in payload) {
1874
+ const { key, type, ...params } = payload;
1875
+ const op = {
1876
+ id: "ssc-mainnet-hive",
1877
+ json: JSON.stringify({
1878
+ contractName: "tokens",
1879
+ contractAction: "undelegate",
1880
+ contractPayload: {
1881
+ symbol: params.asset,
1882
+ from: params.to,
1883
+ quantity
1884
+ }
1885
+ }),
1886
+ required_auths: [params.from],
1887
+ required_posting_auths: []
1888
+ };
1889
+ return CONFIG.hiveClient.broadcast.json(op, key);
1890
+ } else if (payload.type === "keychain") {
1891
+ return new Promise(
1892
+ (resolve, reject) => window.hive_keychain?.requestCustomJson(
1893
+ payload.from,
1894
+ "ssc-mainnet-hive",
1895
+ "Active",
1896
+ JSON.stringify({
1897
+ contractName: "tokens",
1898
+ contractAction: "undelegate",
1899
+ contractPayload: {
1900
+ symbol: payload.asset,
1901
+ from: payload.to,
1902
+ quantity
1903
+ }
1904
+ }),
1905
+ "Token Undelegation",
1906
+ (resp) => {
1907
+ if (!resp.success) {
1908
+ reject({ message: "Operation cancelled" });
1909
+ }
1910
+ resolve(resp);
1911
+ }
1912
+ )
1913
+ );
1914
+ } else {
1915
+ return hs.sendOperation(
1916
+ [
1917
+ "custom_json",
1918
+ {
1919
+ id: "ssc-mainnet-hive",
1920
+ required_auths: [payload.from],
1921
+ required_posting_auths: [],
1922
+ json: JSON.stringify({
1923
+ contractName: "tokens",
1924
+ contractAction: "undelegate",
1925
+ contractPayload: {
1926
+ symbol: payload.asset,
1927
+ from: payload.to,
1928
+ quantity
1929
+ }
1930
+ })
1931
+ }
1932
+ ],
1933
+ { callback: `https://ecency.com/@${payload.from}/wallet` },
1934
+ () => {
1935
+ }
1936
+ );
1937
+ }
1938
+ }
1939
+ async function stakeEngineToken(payload) {
1940
+ const parsedAsset = parseAsset(payload.amount);
1941
+ const quantity = parsedAsset.amount.toString();
1942
+ if (payload.type === "key" && "key" in payload) {
1943
+ const { key, type, ...params } = payload;
1944
+ const op = {
1945
+ id: "ssc-mainnet-hive",
1946
+ json: JSON.stringify({
1947
+ contractName: "tokens",
1948
+ contractAction: "stake",
1949
+ contractPayload: {
1950
+ symbol: params.asset,
1951
+ to: params.to,
1952
+ quantity
1953
+ }
1954
+ }),
1955
+ required_auths: [params.from],
1956
+ required_posting_auths: []
1957
+ };
1958
+ return CONFIG.hiveClient.broadcast.json(op, key);
1959
+ } else if (payload.type === "keychain") {
1960
+ return new Promise(
1961
+ (resolve, reject) => window.hive_keychain?.requestCustomJson(
1962
+ payload.from,
1963
+ "ssc-mainnet-hive",
1964
+ "Active",
1965
+ JSON.stringify({
1966
+ contractName: "tokens",
1967
+ contractAction: "stake",
1968
+ contractPayload: {
1969
+ symbol: payload.asset,
1970
+ to: payload.to,
1971
+ quantity
1972
+ }
1973
+ }),
1974
+ "Token Staking",
1975
+ (resp) => {
1976
+ if (!resp.success) {
1977
+ reject({ message: "Operation cancelled" });
1978
+ }
1979
+ resolve(resp);
1980
+ }
1981
+ )
1982
+ );
1983
+ } else {
1984
+ return hs.sendOperation(
1985
+ [
1986
+ "custom_json",
1987
+ {
1988
+ id: "ssc-mainnet-hive",
1989
+ required_auths: [payload.from],
1990
+ required_posting_auths: [],
1991
+ json: JSON.stringify({
1992
+ contractName: "tokens",
1993
+ contractAction: "stake",
1994
+ contractPayload: {
1995
+ symbol: payload.asset,
1996
+ to: payload.to,
1997
+ quantity
1998
+ }
1999
+ })
2000
+ }
2001
+ ],
2002
+ { callback: `https://ecency.com/@${payload.from}/wallet` },
2003
+ () => {
2004
+ }
2005
+ );
2006
+ }
2007
+ }
2008
+ async function unstakeEngineToken(payload) {
2009
+ const parsedAsset = parseAsset(payload.amount);
2010
+ const quantity = parsedAsset.amount.toString();
2011
+ if (payload.type === "key" && "key" in payload) {
2012
+ const { key, type, ...params } = payload;
2013
+ const op = {
2014
+ id: "ssc-mainnet-hive",
2015
+ json: JSON.stringify({
2016
+ contractName: "tokens",
2017
+ contractAction: "unstake",
2018
+ contractPayload: {
2019
+ symbol: params.asset,
2020
+ to: params.to,
2021
+ quantity
2022
+ }
2023
+ }),
2024
+ required_auths: [params.from],
2025
+ required_posting_auths: []
2026
+ };
2027
+ return CONFIG.hiveClient.broadcast.json(op, key);
2028
+ } else if (payload.type === "keychain") {
2029
+ return new Promise(
2030
+ (resolve, reject) => window.hive_keychain?.requestCustomJson(
2031
+ payload.from,
2032
+ "ssc-mainnet-hive",
2033
+ "Active",
2034
+ JSON.stringify({
2035
+ contractName: "tokens",
2036
+ contractAction: "unstake",
2037
+ contractPayload: {
2038
+ symbol: payload.asset,
2039
+ to: payload.to,
2040
+ quantity
2041
+ }
2042
+ }),
2043
+ "Token Unstaking",
2044
+ (resp) => {
2045
+ if (!resp.success) {
2046
+ reject({ message: "Operation cancelled" });
2047
+ }
2048
+ resolve(resp);
2049
+ }
2050
+ )
2051
+ );
2052
+ } else {
2053
+ return hs.sendOperation(
2054
+ [
2055
+ "custom_json",
2056
+ {
2057
+ id: "ssc-mainnet-hive",
2058
+ required_auths: [payload.from],
2059
+ required_posting_auths: [],
2060
+ json: JSON.stringify({
2061
+ contractName: "tokens",
2062
+ contractAction: "unstake",
2063
+ contractPayload: {
2064
+ symbol: payload.asset,
2065
+ to: payload.to,
2066
+ quantity
2067
+ }
2068
+ })
2069
+ }
2070
+ ],
2071
+ { callback: `https://ecency.com/@${payload.from}/wallet` },
2072
+ () => {
2073
+ }
2074
+ );
2075
+ }
2076
+ }
2077
+ async function transferEngineToken(payload) {
2078
+ const parsedAsset = parseAsset(payload.amount);
2079
+ const quantity = parsedAsset.amount.toString();
2080
+ if (payload.type === "key" && "key" in payload) {
2081
+ const { key, type, ...params } = payload;
2082
+ const op = {
2083
+ id: "ssc-mainnet-hive",
2084
+ json: JSON.stringify({
2085
+ contractName: "tokens",
2086
+ contractAction: "transfer",
2087
+ contractPayload: {
2088
+ symbol: params.asset,
2089
+ to: params.to,
2090
+ quantity,
2091
+ memo: params.memo
2092
+ }
2093
+ }),
2094
+ required_auths: [params.from],
2095
+ required_posting_auths: []
2096
+ };
2097
+ return CONFIG.hiveClient.broadcast.json(op, key);
2098
+ } else if (payload.type === "keychain") {
2099
+ return new Promise(
2100
+ (resolve, reject) => window.hive_keychain?.requestCustomJson(
2101
+ payload.from,
2102
+ "ssc-mainnet-hive",
2103
+ "Active",
2104
+ JSON.stringify({
2105
+ contractName: "tokens",
2106
+ contractAction: "transfer",
2107
+ contractPayload: {
2108
+ symbol: payload.asset,
2109
+ to: payload.to,
2110
+ quantity,
2111
+ memo: payload.memo
2112
+ }
2113
+ }),
2114
+ "Token Transfer",
2115
+ (resp) => {
2116
+ if (!resp.success) {
2117
+ reject({ message: "Operation cancelled" });
2118
+ }
2119
+ resolve(resp);
2120
+ }
2121
+ )
2122
+ );
2123
+ } else {
2124
+ return hs.sendOperation(
2125
+ [
2126
+ "custom_json",
2127
+ {
2128
+ id: "ssc-mainnet-hive",
2129
+ required_auths: [payload.from],
2130
+ required_posting_auths: [],
2131
+ json: JSON.stringify({
2132
+ contractName: "tokens",
2133
+ contractAction: "transfer",
2134
+ contractPayload: {
2135
+ symbol: payload.asset,
2136
+ to: payload.to,
2137
+ quantity,
2138
+ memo: payload.memo
2139
+ }
2140
+ })
2141
+ }
2142
+ ],
2143
+ { callback: `https://ecency.com/@${payload.from}/wallet` },
2144
+ () => {
2145
+ }
2146
+ );
2147
+ }
2148
+ }
2149
+ function getPointsQueryOptions(username) {
2150
+ return queryOptions({
2151
+ queryKey: ["assets", "points", username],
2152
+ queryFn: async () => {
2153
+ if (!username) {
2154
+ throw new Error(
2155
+ "[SDK][Wallets][Assets][Points][Query] \u2013 username wasn`t provided"
2156
+ );
2157
+ }
2158
+ const response = await fetch(
2159
+ CONFIG.privateApiHost + "/private-api/points",
2160
+ {
2161
+ method: "POST",
2162
+ headers: {
2163
+ "Content-Type": "application/json"
2164
+ },
2165
+ body: JSON.stringify({ username })
2166
+ }
2167
+ );
2168
+ const points = await response.json();
2169
+ return {
2170
+ points: points.points,
2171
+ uPoints: points.unclaimed_points
2172
+ };
2173
+ },
2174
+ staleTime: 6e4,
2175
+ refetchInterval: 9e4,
2176
+ refetchOnMount: true,
2177
+ enabled: !!username
2178
+ });
2179
+ }
2180
+ function getPointsAssetGeneralInfoQueryOptions(username) {
2181
+ return queryOptions({
2182
+ queryKey: ["assets", "points", "general-info", username],
2183
+ staleTime: 6e4,
2184
+ refetchInterval: 9e4,
2185
+ queryFn: async () => {
2186
+ await getQueryClient().prefetchQuery(getPointsQueryOptions(username));
2187
+ const data = getQueryClient().getQueryData(
2188
+ getPointsQueryOptions(username).queryKey
2189
+ );
2190
+ return {
2191
+ name: "POINTS",
2192
+ title: "Ecency Points",
2193
+ price: 2e-3,
2194
+ accountBalance: +data?.points
2195
+ };
2196
+ }
2197
+ });
2198
+ }
2199
+ function getPointsAssetTransactionsQueryOptions(username, type) {
2200
+ return queryOptions({
2201
+ queryKey: ["assets", "points", "transactions", username, type],
2202
+ queryFn: async () => {
2203
+ const response = await fetch(
2204
+ `${CONFIG.privateApiHost}/private-api/point-list`,
2205
+ {
2206
+ method: "POST",
2207
+ body: JSON.stringify({
2208
+ username,
2209
+ type: type ?? 0
2210
+ })
2211
+ }
2212
+ );
2213
+ const data = await response.json();
2214
+ return data.map(({ created, type: type2, amount, id }) => ({
2215
+ created: new Date(created),
2216
+ type: type2,
2217
+ results: [
2218
+ {
2219
+ amount: parseInt(amount),
2220
+ asset: "POINTS"
2221
+ }
2222
+ ],
2223
+ id
2224
+ }));
2225
+ }
2226
+ });
2227
+ }
2228
+
2229
+ // src/modules/assets/points/mutations/claim-points.ts
2230
+ function useClaimPoints(username, onSuccess, onError) {
2231
+ const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(
2232
+ username,
2233
+ "points-claimed"
2234
+ );
2235
+ const fetchApi = getBoundFetch();
2236
+ return useMutation({
2237
+ mutationFn: async () => {
2238
+ if (!username) {
2239
+ throw new Error(
2240
+ "[SDK][Wallets][Assets][Points][Claim] \u2013 username wasn`t provided"
2241
+ );
2242
+ }
2243
+ return fetchApi(CONFIG.privateApiHost + "/private-api/points-claim", {
2244
+ method: "POST",
2245
+ headers: {
2246
+ "Content-Type": "application/json"
2247
+ },
2248
+ body: JSON.stringify({ code: getAccessToken(username) })
2249
+ });
2250
+ },
2251
+ onError,
2252
+ onSuccess: () => {
2253
+ recordActivity();
2254
+ CONFIG.queryClient.setQueryData(
2255
+ getPointsQueryOptions(username).queryKey,
2256
+ (data) => {
2257
+ if (!data) {
2258
+ return data;
2259
+ }
2260
+ return {
2261
+ points: (parseFloat(data.points) + parseFloat(data.uPoints)).toFixed(3),
2262
+ uPoints: "0"
2263
+ };
2264
+ }
2265
+ );
2266
+ onSuccess?.();
2267
+ }
2268
+ });
2269
+ }
2270
+ async function transferPoint({
2271
+ from,
2272
+ to,
2273
+ amount,
2274
+ memo,
2275
+ type,
2276
+ ...payload
2277
+ }) {
2278
+ const op = [
2279
+ "custom_json",
2280
+ {
2281
+ id: "ecency_point_transfer",
2282
+ json: JSON.stringify({
2283
+ sender: from,
2284
+ receiver: to,
2285
+ amount: amount.replace("POINTS", "POINT"),
2286
+ memo
2287
+ }),
2288
+ required_auths: [from],
2289
+ required_posting_auths: []
2290
+ }
2291
+ ];
2292
+ if (type === "key" && "key" in payload) {
2293
+ const { key } = payload;
2294
+ return CONFIG.hiveClient.broadcast.sendOperations([op], key);
2295
+ }
2296
+ if (type === "keychain") {
2297
+ return Keychain.broadcast(from, [op], "Active");
2298
+ }
2299
+ return hs.sendOperation(
2300
+ op,
2301
+ { callback: `https://ecency.com/@${from}/wallet` },
2302
+ () => {
2303
+ }
2304
+ );
2305
+ }
2306
+
2307
+ // src/modules/assets/points/types/point-transaction-type.ts
2308
+ var PointTransactionType = /* @__PURE__ */ ((PointTransactionType2) => {
2309
+ PointTransactionType2[PointTransactionType2["CHECKIN"] = 10] = "CHECKIN";
2310
+ PointTransactionType2[PointTransactionType2["LOGIN"] = 20] = "LOGIN";
2311
+ PointTransactionType2[PointTransactionType2["CHECKIN_EXTRA"] = 30] = "CHECKIN_EXTRA";
2312
+ PointTransactionType2[PointTransactionType2["POST"] = 100] = "POST";
2313
+ PointTransactionType2[PointTransactionType2["COMMENT"] = 110] = "COMMENT";
2314
+ PointTransactionType2[PointTransactionType2["VOTE"] = 120] = "VOTE";
2315
+ PointTransactionType2[PointTransactionType2["REBLOG"] = 130] = "REBLOG";
2316
+ PointTransactionType2[PointTransactionType2["DELEGATION"] = 150] = "DELEGATION";
2317
+ PointTransactionType2[PointTransactionType2["REFERRAL"] = 160] = "REFERRAL";
2318
+ PointTransactionType2[PointTransactionType2["COMMUNITY"] = 170] = "COMMUNITY";
2319
+ PointTransactionType2[PointTransactionType2["TRANSFER_SENT"] = 998] = "TRANSFER_SENT";
2320
+ PointTransactionType2[PointTransactionType2["TRANSFER_INCOMING"] = 999] = "TRANSFER_INCOMING";
2321
+ PointTransactionType2[PointTransactionType2["MINTED"] = 991] = "MINTED";
2322
+ return PointTransactionType2;
2323
+ })(PointTransactionType || {});
2324
+ function getAllTokensListQueryOptions(query) {
2325
+ return queryOptions({
2326
+ queryKey: ["ecency-wallets", "all-tokens-list", query],
2327
+ queryFn: async () => {
2328
+ await getQueryClient().prefetchQuery(
2329
+ getHiveEngineTokensMetadataQueryOptions(HiveEngineTokens)
2330
+ );
2331
+ const metadataList = getQueryClient().getQueryData(getHiveEngineTokensMetadataQueryOptions(HiveEngineTokens).queryKey);
2332
+ return {
2333
+ basic: [
2334
+ "POINTS" /* Points */,
2335
+ "HIVE" /* Hive */,
2336
+ "HP" /* HivePower */,
2337
+ "HBD" /* HiveDollar */
2338
+ ].filter((token) => token.toLowerCase().includes(query.toLowerCase())),
2339
+ external: Object.values(EcencyWalletCurrency).filter(
2340
+ (token) => token.toLowerCase().includes(query.toLowerCase())
2341
+ ),
2342
+ spk: ["SPK" /* Spk */, "LARYNX", "LP"],
2343
+ layer2: metadataList
2344
+ };
2345
+ }
2346
+ });
2347
+ }
2348
+ function getAccountWalletListQueryOptions(username) {
2349
+ return queryOptions({
2350
+ queryKey: ["ecency-wallets", "list", username],
2351
+ enabled: !!username,
2352
+ queryFn: async () => {
2353
+ const accountQuery = getAccountFullQueryOptions(username);
2354
+ await getQueryClient().fetchQuery({
2355
+ queryKey: accountQuery.queryKey
2356
+ });
2357
+ const account = getQueryClient().getQueryData(
2358
+ accountQuery.queryKey
2359
+ );
2360
+ if (account?.profile?.tokens instanceof Array) {
2361
+ const list = [
2362
+ "POINTS" /* Points */,
2363
+ "HIVE" /* Hive */,
2364
+ "HP" /* HivePower */,
2365
+ "HBD" /* HiveDollar */,
2366
+ ...account.profile.tokens.filter(({ meta }) => !!meta?.show).map((token) => token.symbol)
2367
+ ];
2368
+ return Array.from(new Set(list).values());
2369
+ }
2370
+ return [
2371
+ "POINTS" /* Points */,
2372
+ "HIVE" /* Hive */,
2373
+ "HP" /* HivePower */,
2374
+ "HBD" /* HiveDollar */,
2375
+ "SPK" /* Spk */
2376
+ ];
2377
+ }
2378
+ });
2379
+ }
2380
+
2381
+ // src/modules/assets/external/common/parse-private-api-balance.ts
2382
+ function normalizeBalance2(balance) {
2383
+ if (typeof balance === "number") {
2384
+ if (!Number.isFinite(balance)) {
2385
+ throw new Error("Private API returned a non-finite numeric balance");
2386
+ }
2387
+ return Math.trunc(balance).toString();
2388
+ }
2389
+ if (typeof balance === "string") {
2390
+ const trimmed = balance.trim();
2391
+ if (trimmed === "") {
2392
+ throw new Error("Private API returned an empty balance string");
2393
+ }
2394
+ return trimmed;
2395
+ }
2396
+ throw new Error("Private API returned balance in an unexpected format");
2397
+ }
2398
+ function parsePrivateApiBalance2(result, expectedChain) {
2399
+ if (!result || typeof result !== "object") {
2400
+ throw new Error("Private API returned an unexpected response");
2401
+ }
2402
+ const { chain, balance, unit, raw, nodeId } = result;
2403
+ if (typeof chain !== "string" || chain !== expectedChain) {
2404
+ throw new Error("Private API response chain did not match request");
2405
+ }
2406
+ if (typeof unit !== "string" || unit.length === 0) {
2407
+ throw new Error("Private API response is missing unit information");
2408
+ }
2409
+ if (balance === void 0 || balance === null) {
2410
+ throw new Error("Private API response is missing balance information");
2411
+ }
2412
+ const balanceString = normalizeBalance2(balance);
2413
+ let balanceBigInt;
2414
+ try {
2415
+ balanceBigInt = BigInt(balanceString);
2416
+ } catch (error) {
2417
+ throw new Error("Private API returned a balance that is not an integer");
2418
+ }
2419
+ return {
2420
+ chain,
2421
+ unit,
2422
+ raw,
2423
+ nodeId: typeof nodeId === "string" && nodeId.length > 0 ? nodeId : void 0,
2424
+ balanceBigInt,
2425
+ balanceString
2426
+ };
2427
+ }
2428
+
2429
+ // src/modules/assets/external/apt/get-apt-asset-balance-query-options.ts
2430
+ function getAptAssetBalanceQueryOptions(address) {
2431
+ return queryOptions({
2432
+ queryKey: ["assets", "apt", "balance", address],
2433
+ queryFn: async () => {
2434
+ const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/apt/${encodeURIComponent(
2435
+ address
2436
+ )}`;
2437
+ try {
2438
+ const response = await fetch(baseUrl);
2439
+ if (!response.ok) {
2440
+ throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
2441
+ }
2442
+ return +parsePrivateApiBalance2(await response.json(), "apt").balanceString;
2443
+ } catch (error) {
2444
+ console.error(error);
2445
+ const response = await fetch(`${baseUrl}?provider=chainz`);
2446
+ return +parsePrivateApiBalance2(await response.json(), "apt").balanceString;
2447
+ }
2448
+ }
2449
+ });
2450
+ }
2451
+ async function getAddressFromAccount(username, tokenName) {
2452
+ await CONFIG.queryClient.prefetchQuery(getAccountFullQueryOptions(username));
2453
+ const account = CONFIG.queryClient.getQueryData(
2454
+ getAccountFullQueryOptions(username).queryKey
2455
+ );
2456
+ const address = account?.profile?.tokens?.find((t) => t.symbol === tokenName)?.meta?.address;
2457
+ if (!address) {
2458
+ throw new Error(
2459
+ "[SDK][Wallets] \u2013\xA0cannot fetch APT balance with empty adrress"
2460
+ );
2461
+ }
2462
+ return address;
2463
+ }
2464
+
2465
+ // src/modules/assets/external/apt/get-apt-asset-general-info-query-options.ts
2466
+ function getAptAssetGeneralInfoQueryOptions(username) {
2467
+ return queryOptions({
2468
+ queryKey: ["assets", "apt", "general-info", username],
2469
+ staleTime: 6e4,
2470
+ refetchInterval: 9e4,
2471
+ queryFn: async () => {
2472
+ const address = await getAddressFromAccount(username, "APT");
2473
+ await CONFIG.queryClient.fetchQuery(
2474
+ getAptAssetBalanceQueryOptions(address)
2475
+ );
2476
+ const accountBalance = (CONFIG.queryClient.getQueryData(
2477
+ getAptAssetBalanceQueryOptions(address).queryKey
2478
+ ) ?? 0) / 1e8;
2479
+ await CONFIG.queryClient.prefetchQuery(
2480
+ getCoinGeckoPriceQueryOptions("APT")
2481
+ );
2482
+ const price = CONFIG.queryClient.getQueryData(
2483
+ getCoinGeckoPriceQueryOptions("APT").queryKey
2484
+ ) ?? 0;
2485
+ return {
2486
+ name: "APT",
2487
+ title: "Aptos",
2488
+ price,
2489
+ accountBalance
2490
+ };
2491
+ }
2492
+ });
2493
+ }
2494
+ function getBnbAssetBalanceQueryOptions(address) {
2495
+ return queryOptions({
2496
+ queryKey: ["assets", "bnb", "balance", address],
2497
+ queryFn: async () => {
2498
+ const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/bnb/${encodeURIComponent(
2499
+ address
2500
+ )}`;
2501
+ try {
2502
+ const response = await fetch(baseUrl);
2503
+ if (!response.ok) {
2504
+ throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
2505
+ }
2506
+ return +parsePrivateApiBalance2(await response.json(), "bnb").balanceString;
2507
+ } catch (error) {
2508
+ console.error(error);
2509
+ const response = await fetch(`${baseUrl}?provider=chainz`);
2510
+ return +parsePrivateApiBalance2(await response.json(), "bnb").balanceString;
2511
+ }
2512
+ }
2513
+ });
2514
+ }
2515
+
2516
+ // src/modules/assets/external/bnb/get-bnb-asset-general-info-query-options.ts
2517
+ function getBnbAssetGeneralInfoQueryOptions(username) {
2518
+ return queryOptions({
2519
+ queryKey: ["assets", "bnb", "general-info", username],
2520
+ staleTime: 6e4,
2521
+ refetchInterval: 9e4,
2522
+ queryFn: async () => {
2523
+ const address = await getAddressFromAccount(username, "BNB");
2524
+ await CONFIG.queryClient.fetchQuery(
2525
+ getBnbAssetBalanceQueryOptions(address)
2526
+ );
2527
+ const accountBalance = (CONFIG.queryClient.getQueryData(
2528
+ getBnbAssetBalanceQueryOptions(address).queryKey
2529
+ ) ?? 0) / 1e18;
2530
+ await CONFIG.queryClient.prefetchQuery(
2531
+ getCoinGeckoPriceQueryOptions("BNB")
2532
+ );
2533
+ const price = CONFIG.queryClient.getQueryData(
2534
+ getCoinGeckoPriceQueryOptions("BNB").queryKey
2535
+ ) ?? 0;
2536
+ return {
2537
+ name: "BNB",
2538
+ title: "Binance coin",
2539
+ price,
2540
+ accountBalance
2541
+ };
2542
+ }
2543
+ });
2544
+ }
2545
+ function getBtcAssetBalanceQueryOptions(address) {
2546
+ return queryOptions({
2547
+ queryKey: ["assets", "btc", "balance", address],
2548
+ queryFn: async () => {
2549
+ const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/btc/${encodeURIComponent(
2550
+ address
2551
+ )}`;
2552
+ try {
2553
+ const response = await fetch(baseUrl);
2554
+ if (!response.ok) {
2555
+ throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
2556
+ }
2557
+ return +parsePrivateApiBalance2(await response.json(), "btc").balanceString;
2558
+ } catch (error) {
2559
+ console.error(error);
2560
+ const response = await fetch(`${baseUrl}?provider=chainz`);
2561
+ return +parsePrivateApiBalance2(await response.json(), "btc").balanceString;
2562
+ }
2563
+ }
2564
+ });
2565
+ }
2566
+
2567
+ // src/modules/assets/external/btc/get-btc-asset-general-info-query-options.ts
2568
+ function getBtcAssetGeneralInfoQueryOptions(username) {
2569
+ return queryOptions({
2570
+ queryKey: ["assets", "btc", "general-info", username],
2571
+ staleTime: 6e4,
2572
+ refetchInterval: 9e4,
2573
+ queryFn: async () => {
2574
+ const address = await getAddressFromAccount(username, "BTC");
2575
+ await CONFIG.queryClient.fetchQuery(
2576
+ getBtcAssetBalanceQueryOptions(address)
2577
+ );
2578
+ const accountBalance = (CONFIG.queryClient.getQueryData(
2579
+ getBtcAssetBalanceQueryOptions(address).queryKey
2580
+ ) ?? 0) / 1e8;
2581
+ await CONFIG.queryClient.prefetchQuery(
2582
+ getCoinGeckoPriceQueryOptions("BTC")
2583
+ );
2584
+ const price = CONFIG.queryClient.getQueryData(
2585
+ getCoinGeckoPriceQueryOptions("BTC").queryKey
2586
+ ) ?? 0;
2587
+ return {
2588
+ name: "BTC",
2589
+ title: "Bitcoin",
2590
+ price,
2591
+ accountBalance
2592
+ };
2593
+ }
2594
+ });
2595
+ }
2596
+ function getEthAssetBalanceQueryOptions(address) {
2597
+ return queryOptions({
2598
+ queryKey: ["assets", "eth", "balance", address],
2599
+ queryFn: async () => {
2600
+ const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/eth/${encodeURIComponent(
2601
+ address
2602
+ )}`;
2603
+ try {
2604
+ const response = await fetch(baseUrl);
2605
+ if (!response.ok) {
2606
+ throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
2607
+ }
2608
+ return +parsePrivateApiBalance2(await response.json(), "eth").balanceString;
2609
+ } catch (error) {
2610
+ console.error(error);
2611
+ const response = await fetch(`${baseUrl}?provider=chainz`);
2612
+ return +parsePrivateApiBalance2(await response.json(), "eth").balanceString;
2613
+ }
2614
+ }
2615
+ });
2616
+ }
2617
+
2618
+ // src/modules/assets/external/eth/get-eth-asset-general-info-query-options.ts
2619
+ function getEthAssetGeneralInfoQueryOptions(username) {
2620
+ return queryOptions({
2621
+ queryKey: ["assets", "eth", "general-info", username],
2622
+ staleTime: 6e4,
2623
+ refetchInterval: 9e4,
2624
+ queryFn: async () => {
2625
+ const address = await getAddressFromAccount(username, "ETH");
2626
+ await CONFIG.queryClient.fetchQuery(
2627
+ getEthAssetBalanceQueryOptions(address)
2628
+ );
2629
+ const accountBalance = (CONFIG.queryClient.getQueryData(
2630
+ getEthAssetBalanceQueryOptions(address).queryKey
2631
+ ) ?? 0) / 1e18;
2632
+ await CONFIG.queryClient.prefetchQuery(
2633
+ getCoinGeckoPriceQueryOptions("ETH")
2634
+ );
2635
+ const price = CONFIG.queryClient.getQueryData(
2636
+ getCoinGeckoPriceQueryOptions("ETH").queryKey
2637
+ ) ?? 0;
2638
+ return {
2639
+ name: "ETH",
2640
+ title: "Ethereum",
2641
+ price,
2642
+ accountBalance
2643
+ };
2644
+ }
2645
+ });
2646
+ }
2647
+ function getSolAssetBalanceQueryOptions(address) {
2648
+ return queryOptions({
2649
+ queryKey: ["assets", "sol", "balance", address],
2650
+ queryFn: async () => {
2651
+ const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/sol/${encodeURIComponent(
2652
+ address
2653
+ )}`;
2654
+ try {
2655
+ const response = await fetch(baseUrl);
2656
+ if (!response.ok) {
2657
+ throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
2658
+ }
2659
+ return +parsePrivateApiBalance2(await response.json(), "sol").balanceString;
2660
+ } catch (error) {
2661
+ console.error(error);
2662
+ const response = await fetch(`${baseUrl}?provider=chainz`);
2663
+ return +parsePrivateApiBalance2(await response.json(), "sol").balanceString;
2664
+ }
2665
+ }
2666
+ });
2667
+ }
2668
+
2669
+ // src/modules/assets/external/sol/get-sol-asset-general-info-query-options.ts
2670
+ function getSolAssetGeneralInfoQueryOptions(username) {
2671
+ return queryOptions({
2672
+ queryKey: ["assets", "sol", "general-info", username],
2673
+ staleTime: 6e4,
2674
+ refetchInterval: 9e4,
2675
+ queryFn: async () => {
2676
+ const address = await getAddressFromAccount(username, "SOL");
2677
+ await CONFIG.queryClient.fetchQuery(
2678
+ getSolAssetBalanceQueryOptions(address)
2679
+ );
2680
+ const accountBalance = (CONFIG.queryClient.getQueryData(
2681
+ getSolAssetBalanceQueryOptions(address).queryKey
2682
+ ) ?? 0) / 1e9;
2683
+ await CONFIG.queryClient.prefetchQuery(
2684
+ getCoinGeckoPriceQueryOptions("SOL")
2685
+ );
2686
+ const price = CONFIG.queryClient.getQueryData(
2687
+ getCoinGeckoPriceQueryOptions("SOL").queryKey
2688
+ ) ?? 0;
2689
+ return {
2690
+ name: "SOL",
2691
+ title: "Solana",
2692
+ price,
2693
+ accountBalance
2694
+ };
2695
+ }
2696
+ });
2697
+ }
2698
+ function getTonAssetBalanceQueryOptions(address) {
2699
+ return queryOptions({
2700
+ queryKey: ["assets", "ton", "balance", address],
2701
+ queryFn: async () => {
2702
+ const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/ton/${encodeURIComponent(
2703
+ address
2704
+ )}`;
2705
+ try {
2706
+ const response = await fetch(baseUrl);
2707
+ if (!response.ok) {
2708
+ throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
2709
+ }
2710
+ return +parsePrivateApiBalance2(await response.json(), "ton").balanceString;
2711
+ } catch (error) {
2712
+ console.error(error);
2713
+ const response = await fetch(`${baseUrl}?provider=chainz`);
2714
+ return +parsePrivateApiBalance2(await response.json(), "ton").balanceString;
2715
+ }
2716
+ }
2717
+ });
2718
+ }
2719
+
2720
+ // src/modules/assets/external/ton/get-ton-asset-general-info-query-options.ts
2721
+ function getTonAssetGeneralInfoQueryOptions(username) {
2722
+ return queryOptions({
2723
+ queryKey: ["assets", "ton", "general-info", username],
2724
+ staleTime: 6e4,
2725
+ refetchInterval: 9e4,
2726
+ queryFn: async () => {
2727
+ const address = await getAddressFromAccount(username, "TON");
2728
+ await CONFIG.queryClient.fetchQuery(
2729
+ getTonAssetBalanceQueryOptions(address)
2730
+ );
2731
+ const accountBalance = (CONFIG.queryClient.getQueryData(
2732
+ getTonAssetBalanceQueryOptions(address).queryKey
2733
+ ) ?? 0) / 1e9;
2734
+ await CONFIG.queryClient.prefetchQuery(
2735
+ getCoinGeckoPriceQueryOptions("TON")
2736
+ );
2737
+ const price = CONFIG.queryClient.getQueryData(
2738
+ getCoinGeckoPriceQueryOptions("TON").queryKey
2739
+ ) ?? 0;
2740
+ return {
2741
+ name: "TON",
2742
+ title: "The open network",
2743
+ price,
2744
+ accountBalance
2745
+ };
2746
+ }
2747
+ });
2748
+ }
2749
+ function getTronAssetBalanceQueryOptions(address) {
2750
+ return queryOptions({
2751
+ queryKey: ["assets", "tron", "balance", address],
2752
+ queryFn: async () => {
2753
+ const baseUrl = `${CONFIG.privateApiHost}/private-api/balance/tron/${encodeURIComponent(
2754
+ address
2755
+ )}`;
2756
+ try {
2757
+ const response = await fetch(baseUrl);
2758
+ if (!response.ok) {
2759
+ throw new Error(`[SDK][Wallets] \u2013 request failed(${baseUrl})`);
2760
+ }
2761
+ return +parsePrivateApiBalance2(await response.json(), "tron").balanceString;
2762
+ } catch (error) {
2763
+ console.error(error);
2764
+ const response = await fetch(`${baseUrl}?provider=chainz`);
2765
+ return +parsePrivateApiBalance2(await response.json(), "tron").balanceString;
2766
+ }
2767
+ }
2768
+ });
2769
+ }
2770
+
2771
+ // src/modules/assets/external/tron/get-tron-asset-general-info-query-options.ts
2772
+ function getTronAssetGeneralInfoQueryOptions(username) {
2773
+ return queryOptions({
2774
+ queryKey: ["assets", "tron", "general-info", username],
2775
+ staleTime: 6e4,
2776
+ refetchInterval: 9e4,
2777
+ queryFn: async () => {
2778
+ const address = await getAddressFromAccount(username, "TRX");
2779
+ await CONFIG.queryClient.fetchQuery(
2780
+ getTronAssetBalanceQueryOptions(address)
2781
+ );
2782
+ const accountBalance = (CONFIG.queryClient.getQueryData(
2783
+ getTronAssetBalanceQueryOptions(address).queryKey
2784
+ ) ?? 0) / 1e6;
2785
+ await CONFIG.queryClient.prefetchQuery(
2786
+ getCoinGeckoPriceQueryOptions("TRX")
2787
+ );
2788
+ const price = CONFIG.queryClient.getQueryData(
2789
+ getCoinGeckoPriceQueryOptions("TRX").queryKey
2790
+ ) ?? 0;
2791
+ return {
2792
+ name: "TRX",
2793
+ title: "Tron",
2794
+ price,
2795
+ accountBalance
2796
+ };
2797
+ }
2798
+ });
2799
+ }
2800
+
2801
+ // src/modules/wallets/queries/get-account-wallet-asset-info-query-options.ts
2802
+ function getAccountWalletAssetInfoQueryOptions(username, asset, options2 = { refetch: false }) {
2803
+ const fetchQuery = async (queryOptions39) => {
2804
+ if (options2.refetch) {
2805
+ await getQueryClient().fetchQuery(queryOptions39);
2806
+ } else {
2807
+ await getQueryClient().prefetchQuery(queryOptions39);
2808
+ }
2809
+ return getQueryClient().getQueryData(
2810
+ queryOptions39.queryKey
2811
+ );
2812
+ };
2813
+ return queryOptions({
2814
+ queryKey: ["ecency-wallets", "asset-info", username, asset],
2815
+ queryFn: async () => {
2816
+ if (asset === "HIVE") {
2817
+ return fetchQuery(getHiveAssetGeneralInfoQueryOptions(username));
2818
+ } else if (asset === "HP") {
2819
+ return fetchQuery(getHivePowerAssetGeneralInfoQueryOptions(username));
2820
+ } else if (asset === "HBD") {
2821
+ return fetchQuery(getHbdAssetGeneralInfoQueryOptions(username));
2822
+ } else if (asset === "SPK") {
2823
+ return fetchQuery(getSpkAssetGeneralInfoQueryOptions(username));
2824
+ } else if (asset === "LARYNX") {
2825
+ return fetchQuery(getLarynxAssetGeneralInfoQueryOptions(username));
2826
+ } else if (asset === "LP") {
2827
+ return fetchQuery(getLarynxPowerAssetGeneralInfoQueryOptions(username));
2828
+ } else if (asset === "POINTS") {
2829
+ return fetchQuery(getPointsAssetGeneralInfoQueryOptions(username));
2830
+ } else if (asset === "APT") {
2831
+ return fetchQuery(getAptAssetGeneralInfoQueryOptions(username));
2832
+ } else if (asset === "BNB") {
2833
+ return fetchQuery(getBnbAssetGeneralInfoQueryOptions(username));
2834
+ } else if (asset === "BTC") {
2835
+ return fetchQuery(getBtcAssetGeneralInfoQueryOptions(username));
2836
+ } else if (asset === "ETH") {
2837
+ return fetchQuery(getEthAssetGeneralInfoQueryOptions(username));
2838
+ } else if (asset === "SOL") {
2839
+ return fetchQuery(getSolAssetGeneralInfoQueryOptions(username));
2840
+ } else if (asset === "TON") {
2841
+ return fetchQuery(getTonAssetGeneralInfoQueryOptions(username));
2842
+ } else if (asset === "TRX") {
2843
+ return fetchQuery(getTronAssetGeneralInfoQueryOptions(username));
2844
+ } else if (HiveEngineTokens.includes(asset)) {
2845
+ return await fetchQuery(
2846
+ getHiveEngineTokenGeneralInfoQueryOptions(username, asset)
2847
+ );
2848
+ } else {
2849
+ throw new Error(
2850
+ "[SDK][Wallets] \u2013 has requested unrecognized asset info"
2851
+ );
2852
+ }
2853
+ }
2854
+ });
2855
+ }
2856
+ function getTokenOperationsQueryOptions(token, username, isForOwner = false) {
2857
+ return queryOptions({
2858
+ queryKey: ["wallets", "token-operations", token, username, isForOwner],
2859
+ queryFn: async () => {
2860
+ switch (token) {
2861
+ case "HIVE" /* Hive */:
2862
+ return [
2863
+ "transfer" /* Transfer */,
2864
+ ...isForOwner ? [
2865
+ "transfer-saving" /* TransferToSavings */,
2866
+ "power-up" /* PowerUp */,
2867
+ "swap" /* Swap */
2868
+ ] : []
2869
+ ];
2870
+ case "HP" /* HivePower */:
2871
+ return [
2872
+ "delegate" /* Delegate */,
2873
+ ...isForOwner ? ["power-down" /* PowerDown */, "withdraw-saving" /* WithdrawRoutes */] : ["power-up" /* PowerUp */]
2874
+ ];
2875
+ case "HBD" /* HiveDollar */:
2876
+ return [
2877
+ "transfer" /* Transfer */,
2878
+ ...isForOwner ? ["transfer-saving" /* TransferToSavings */, "swap" /* Swap */] : []
2879
+ ];
2880
+ case "POINTS" /* Points */:
2881
+ return [
2882
+ "gift" /* Gift */,
2883
+ ...isForOwner ? [
2884
+ "promote" /* Promote */,
2885
+ "claim" /* Claim */,
2886
+ "buy" /* Buy */
2887
+ ] : []
2888
+ ];
2889
+ case "SPK" /* Spk */:
2890
+ return ["transfer" /* Transfer */];
2891
+ case "LARYNX":
2892
+ return [
2893
+ "transfer" /* Transfer */,
2894
+ ...isForOwner ? ["power-up" /* PowerUp */, "lock" /* LockLiquidity */] : []
2895
+ ];
2896
+ case "LP":
2897
+ return [
2898
+ "delegate" /* Delegate */,
2899
+ ...isForOwner ? ["power-down" /* PowerDown */] : []
2900
+ ];
2901
+ case "APT":
2902
+ case "BNB":
2903
+ case "BTC":
2904
+ case "ETH":
2905
+ case "SOL":
2906
+ case "TON":
2907
+ case "TRX":
2908
+ return [];
2909
+ }
2910
+ const balancesListQuery = getHiveEngineTokensBalancesQueryOptions(username);
2911
+ await getQueryClient().prefetchQuery(balancesListQuery);
2912
+ const balances = getQueryClient().getQueryData(
2913
+ balancesListQuery.queryKey
2914
+ );
2915
+ const tokensQuery = getHiveEngineTokensMetadataQueryOptions(
2916
+ balances?.map((b) => b.symbol) ?? []
2917
+ );
2918
+ await getQueryClient().prefetchQuery(tokensQuery);
2919
+ const tokens = getQueryClient().getQueryData(tokensQuery.queryKey);
2920
+ const balanceInfo = balances?.find((m) => m.symbol === token);
2921
+ const tokenInfo = tokens?.find((t) => t.symbol === token);
2922
+ const canDelegate = isForOwner && tokenInfo?.delegationEnabled && balanceInfo && parseFloat(balanceInfo.delegationsOut) !== parseFloat(balanceInfo.balance);
2923
+ const canUndelegate = isForOwner && parseFloat(balanceInfo?.delegationsOut ?? "0") > 0;
2924
+ const canStake = isForOwner && tokenInfo?.stakingEnabled;
2925
+ const canUnstake = isForOwner && parseFloat(balanceInfo?.stake ?? "0") > 0;
2926
+ return [
2927
+ "transfer" /* Transfer */,
2928
+ ...canDelegate ? ["delegate" /* Delegate */] : [],
2929
+ ...canUndelegate ? ["undelegate" /* Undelegate */] : [],
2930
+ ...canStake ? ["stake" /* Stake */] : [],
2931
+ ...canUnstake ? ["unstake" /* Unstake */] : []
2932
+ ];
2933
+ }
2934
+ });
2935
+ }
2936
+ function useWalletsCacheQuery(username) {
2937
+ const queryClient = useQueryClient();
2938
+ const queryKey = ["ecency-wallets", "wallets", username];
2939
+ const getCachedWallets = () => queryClient.getQueryData(queryKey);
2940
+ const createEmptyWalletMap = () => /* @__PURE__ */ new Map();
2941
+ return useQuery({
2942
+ queryKey,
2943
+ enabled: Boolean(username),
2944
+ initialData: () => getCachedWallets() ?? createEmptyWalletMap(),
2945
+ queryFn: async () => getCachedWallets() ?? createEmptyWalletMap(),
2946
+ staleTime: Infinity
2947
+ });
2948
+ }
2949
+ var PATHS = {
2950
+ ["BTC" /* BTC */]: "m/44'/0'/0'/0/0",
2951
+ // Bitcoin (BIP44)
2952
+ ["ETH" /* ETH */]: "m/44'/60'/0'/0/0",
2953
+ // Ethereum (BIP44)
2954
+ ["BNB" /* BNB */]: "m/44'/60'/0'/0/0",
2955
+ // BNB Smart Chain (BIP44)
2956
+ ["SOL" /* SOL */]: "m/44'/501'/0'/0'",
2957
+ // Solana (BIP44)
2958
+ ["TON" /* TON */]: "m/44'/607'/0'",
2959
+ // TON (BIP44)
2960
+ ["TRX" /* TRON */]: "m/44'/195'/0'/0/0",
2961
+ // Tron (BIP44)
2962
+ ["APT" /* APT */]: "m/44'/637'/0'/0'/0'"
2963
+ // Aptos (BIP44)
2964
+ };
2965
+ function useWalletCreate(username, currency) {
2966
+ const { data: mnemonic } = useSeedPhrase(username);
2967
+ const queryClient = useQueryClient();
2968
+ const createWallet = useMutation({
2969
+ mutationKey: ["ecency-wallets", "create-wallet", username, currency],
2970
+ mutationFn: async () => {
2971
+ if (!mnemonic) {
2972
+ throw new Error("[Ecency][Wallets] - No seed to create a wallet");
2973
+ }
2974
+ const wallet = getWallet(currency);
2975
+ const privateKey = await wallet?.getDerivedPrivateKey({
2976
+ mnemonic,
2977
+ hdPath: PATHS[currency]
2978
+ });
2979
+ await delay(1e3);
2980
+ const address = await wallet?.getNewAddress({
2981
+ privateKey
2982
+ });
2983
+ return {
2984
+ privateKey,
2985
+ address: address.address,
2986
+ publicKey: address.publicKey,
2987
+ username,
2988
+ currency
2989
+ };
2990
+ },
2991
+ onSuccess: (info) => {
2992
+ queryClient.setQueryData(
2993
+ ["ecency-wallets", "wallets", info.username],
2994
+ (data) => new Map(data ? Array.from(data.entries()) : []).set(
2995
+ info.currency,
2996
+ info
2997
+ )
2998
+ );
2999
+ }
3000
+ });
3001
+ const importWallet = () => {
3002
+ };
3003
+ return {
3004
+ createWallet,
3005
+ importWallet
3006
+ };
3007
+ }
3008
+
3009
+ // src/modules/wallets/mutations/private-api/index.ts
3010
+ var private_api_exports = {};
3011
+ __export(private_api_exports, {
3012
+ useCheckWalletExistence: () => useCheckWalletExistence,
3013
+ useCreateAccountWithWallets: () => useCreateAccountWithWallets,
3014
+ useUpdateAccountWithWallets: () => useUpdateAccountWithWallets
3015
+ });
3016
+ function useCreateAccountWithWallets(username) {
3017
+ const { data } = useWalletsCacheQuery(username);
3018
+ const { data: hiveKeys } = useHiveKeysQuery(username);
3019
+ const fetchApi = getBoundFetch();
3020
+ return useMutation({
3021
+ mutationKey: ["ecency-wallets", "create-account-with-wallets", username],
3022
+ mutationFn: ({ currency, address }) => fetchApi(CONFIG.privateApiHost + "/private-api/wallets-add", {
3023
+ method: "POST",
3024
+ headers: {
3025
+ "Content-Type": "application/json"
3026
+ },
3027
+ body: JSON.stringify({
3028
+ username,
3029
+ token: currency,
3030
+ address,
3031
+ meta: {
3032
+ ownerPublicKey: hiveKeys?.ownerPubkey,
3033
+ activePublicKey: hiveKeys?.activePubkey,
3034
+ postingPublicKey: hiveKeys?.postingPubkey,
3035
+ memoPublicKey: hiveKeys?.memoPubkey,
3036
+ ...Array.from(data?.entries() ?? []).reduce(
3037
+ (acc, [curr, info]) => ({
3038
+ ...acc,
3039
+ [curr]: info.address
3040
+ }),
3041
+ {}
3042
+ )
3043
+ }
3044
+ })
3045
+ })
3046
+ });
3047
+ }
3048
+ function useCheckWalletExistence() {
3049
+ return useMutation({
3050
+ mutationKey: ["ecency-wallets", "check-wallet-existence"],
3051
+ mutationFn: async ({ address, currency }) => {
3052
+ const response = await fetch(
3053
+ CONFIG.privateApiHost + "/private-api/wallets-exist",
3054
+ {
3055
+ method: "POST",
3056
+ headers: {
3057
+ "Content-Type": "application/json"
3058
+ },
3059
+ body: JSON.stringify({
3060
+ address,
3061
+ token: currency
3062
+ })
3063
+ }
3064
+ );
3065
+ const data = await response.json();
3066
+ return data.length === 0;
3067
+ }
3068
+ });
3069
+ }
3070
+ function useUpdateAccountWithWallets(username) {
3071
+ const fetchApi = getBoundFetch();
3072
+ return useMutation({
3073
+ mutationKey: ["ecency-wallets", "create-account-with-wallets", username],
3074
+ mutationFn: async ({ tokens, hiveKeys }) => {
3075
+ const entries = Object.entries(tokens).filter(([, address]) => Boolean(address));
3076
+ if (entries.length === 0) {
3077
+ return new Response(null, { status: 204 });
3078
+ }
3079
+ const [primaryToken, primaryAddress] = entries[0] ?? ["", ""];
3080
+ return fetchApi(CONFIG.privateApiHost + "/private-api/wallets-add", {
3081
+ method: "POST",
3082
+ headers: {
3083
+ "Content-Type": "application/json"
3084
+ },
3085
+ body: JSON.stringify({
3086
+ username,
3087
+ code: getAccessToken(username),
3088
+ token: primaryToken,
3089
+ address: primaryAddress,
3090
+ status: 3,
3091
+ meta: {
3092
+ ...Object.fromEntries(entries),
3093
+ ownerPublicKey: hiveKeys.ownerPublicKey,
3094
+ activePublicKey: hiveKeys.activePublicKey,
3095
+ postingPublicKey: hiveKeys.postingPublicKey,
3096
+ memoPublicKey: hiveKeys.memoPublicKey
3097
+ }
3098
+ })
3099
+ });
3100
+ }
3101
+ });
3102
+ }
3103
+
3104
+ // src/modules/wallets/functions/get-keys-from-seed.ts
3105
+ var HD_PATHS = {
3106
+ ["BTC" /* BTC */]: ["m/84'/0'/0'/0/0"],
3107
+ ["ETH" /* ETH */]: ["m/84'/60'/0'/0/0"],
3108
+ // its not working for Trust, Exodus, todo: check others below
3109
+ ["BNB" /* BNB */]: ["m/84'/60'/0'/0/0"],
3110
+ ["SOL" /* SOL */]: ["m/84'/501'/0'/0/0"],
3111
+ ["TRX" /* TRON */]: ["m/44'/195'/0'/0'/0'"],
3112
+ ["APT" /* APT */]: ["m/84'/637'/0'/0/0"],
3113
+ ["TON" /* TON */]: ["m/44'/607'/0'"]
3114
+ };
3115
+ async function getKeysFromSeed(mnemonic, wallet, currency) {
3116
+ for (const hdPath of HD_PATHS[currency] || []) {
3117
+ try {
3118
+ const derivedPrivateKey = await wallet.getDerivedPrivateKey({
3119
+ mnemonic,
3120
+ hdPath
3121
+ });
3122
+ const derivedPublicKey = await wallet.getNewAddress({
3123
+ privateKey: derivedPrivateKey,
3124
+ addressType: currency === "BTC" /* BTC */ ? "segwit_native" : void 0
3125
+ });
3126
+ return [derivedPrivateKey.toString(), derivedPublicKey.address];
3127
+ } catch (error) {
3128
+ return [];
3129
+ }
3130
+ }
3131
+ return [];
3132
+ }
3133
+ function useImportWallet(username, currency) {
3134
+ const queryClient = useQueryClient();
3135
+ const { mutateAsync: checkWalletExistence } = private_api_exports.useCheckWalletExistence();
3136
+ return useMutation({
3137
+ mutationKey: ["ecency-wallets", "import-wallet", username, currency],
3138
+ mutationFn: async ({ privateKeyOrSeed }) => {
3139
+ const wallet = getWallet(currency);
3140
+ if (!wallet) {
3141
+ throw new Error("Cannot find token for this currency");
3142
+ }
3143
+ const isSeed = privateKeyOrSeed.split(" ").length === 12;
3144
+ let address;
3145
+ let privateKey = privateKeyOrSeed;
3146
+ if (isSeed) {
3147
+ [privateKey, address] = await getKeysFromSeed(
3148
+ privateKeyOrSeed,
3149
+ wallet,
3150
+ currency
3151
+ );
3152
+ } else {
3153
+ address = (await wallet.getNewAddress({
3154
+ privateKey: privateKeyOrSeed
3155
+ })).address;
3156
+ }
3157
+ if (!address || !privateKeyOrSeed) {
3158
+ throw new Error(
3159
+ "Private key/seed phrase isn't matching with public key or token"
3160
+ );
3161
+ }
3162
+ const hasChecked = await checkWalletExistence({
3163
+ address,
3164
+ currency
3165
+ });
3166
+ if (!hasChecked) {
3167
+ throw new Error(
3168
+ "This wallet has already in use by Hive account. Please, try another one"
3169
+ );
3170
+ }
3171
+ return {
3172
+ privateKey,
3173
+ address,
3174
+ publicKey: ""
3175
+ };
3176
+ },
3177
+ onSuccess: ({ privateKey, publicKey, address }) => {
3178
+ queryClient.setQueryData(
3179
+ ["ecency-wallets", "wallets", username],
3180
+ (data) => new Map(data ? Array.from(data.entries()) : []).set(currency, {
3181
+ privateKey,
3182
+ publicKey,
3183
+ address,
3184
+ username,
3185
+ currency,
3186
+ type: "CHAIN",
3187
+ custom: true
3188
+ })
3189
+ );
3190
+ }
3191
+ });
3192
+ }
3193
+ function getGroupedChainTokens(tokens, show = false) {
3194
+ if (!tokens) {
3195
+ return {};
3196
+ }
3197
+ return R.pipe(
3198
+ tokens,
3199
+ R.filter(
3200
+ ({ type, symbol }) => type === "CHAIN" || Object.values(EcencyWalletCurrency).includes(symbol)
3201
+ ),
3202
+ R.map((item) => {
3203
+ item.meta.show = show;
3204
+ return item;
3205
+ }),
3206
+ // Chain tokens are unique by symbol, so indexing by symbol
3207
+ // gives a direct lookup map instead of an array-based grouping.
3208
+ R.indexBy(
3209
+ (item) => item.symbol
3210
+ )
3211
+ );
3212
+ }
3213
+ function useSaveWalletInformationToMetadata(username, options2) {
3214
+ const queryClient = useQueryClient();
3215
+ const { data: accountData } = useQuery(getAccountFullQueryOptions(username));
3216
+ const { mutateAsync: updateProfile } = useAccountUpdate(username);
3217
+ return useMutation({
3218
+ mutationKey: [
3219
+ "ecency-wallets",
3220
+ "save-wallet-to-metadata",
3221
+ accountData?.name
3222
+ ],
3223
+ mutationFn: async (tokens) => {
3224
+ if (!accountData) {
3225
+ throw new Error("[SDK][Wallets] \u2013 no account data to save wallets");
3226
+ }
3227
+ const profileChainTokens = getGroupedChainTokens(
3228
+ accountData.profile?.tokens
3229
+ );
3230
+ const payloadTokens = tokens.map(({ currency, type, privateKey, username: username2, ...meta }) => ({
3231
+ symbol: currency,
3232
+ type: type ?? (Object.values(EcencyWalletCurrency).includes(currency) ? "CHAIN" : void 0),
3233
+ meta
3234
+ })) ?? [];
3235
+ const payloadChainTokens = getGroupedChainTokens(payloadTokens, true);
3236
+ const payloadNonChainTokens = payloadTokens.filter(
3237
+ ({ type, symbol }) => type !== "CHAIN" && !Object.values(EcencyWalletCurrency).includes(symbol)
3238
+ );
3239
+ const mergedChainTokens = R.pipe(
3240
+ profileChainTokens,
3241
+ R.mergeDeep(payloadChainTokens),
3242
+ R.values()
3243
+ );
3244
+ return updateProfile({
3245
+ tokens: [
3246
+ ...payloadNonChainTokens,
3247
+ ...mergedChainTokens
3248
+ ]
3249
+ });
3250
+ },
3251
+ onError: options2?.onError,
3252
+ onSuccess: (response, vars, context) => {
3253
+ options2?.onSuccess?.(response, vars, context);
3254
+ queryClient.invalidateQueries({
3255
+ queryKey: getAccountWalletListQueryOptions(username).queryKey
3256
+ });
3257
+ }
3258
+ });
3259
+ }
3260
+ var operationToFunctionMap = {
3261
+ HIVE: {
3262
+ ["transfer" /* Transfer */]: transferHive,
3263
+ ["transfer-saving" /* TransferToSavings */]: transferToSavingsHive,
3264
+ ["power-up" /* PowerUp */]: powerUpHive
3265
+ },
3266
+ HBD: {
3267
+ ["transfer" /* Transfer */]: transferHive,
3268
+ ["transfer-saving" /* TransferToSavings */]: transferToSavingsHive
3269
+ },
3270
+ HP: {
3271
+ ["power-down" /* PowerDown */]: powerDownHive,
3272
+ ["delegate" /* Delegate */]: delegateHive,
3273
+ ["withdraw-saving" /* WithdrawRoutes */]: withdrawVestingRouteHive
3274
+ },
3275
+ POINTS: {
3276
+ ["gift" /* Gift */]: transferPoint
3277
+ },
3278
+ SPK: {
3279
+ ["transfer" /* Transfer */]: transferSpk
3280
+ },
3281
+ LARYNX: {
3282
+ ["lock" /* LockLiquidity */]: lockLarynx,
3283
+ ["power-up" /* PowerUp */]: powerUpLarynx
3284
+ }
3285
+ };
3286
+ var engineOperationToFunctionMap = {
3287
+ ["transfer" /* Transfer */]: transferEngineToken,
3288
+ ["stake" /* Stake */]: stakeEngineToken,
3289
+ ["unstake" /* Unstake */]: unstakeEngineToken,
3290
+ ["delegate" /* Delegate */]: delegateEngineToken,
3291
+ ["undelegate" /* Undelegate */]: undelegateEngineToken
3292
+ };
3293
+ function useWalletOperation(username, asset, operation) {
3294
+ const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(
3295
+ username,
3296
+ operation
3297
+ );
3298
+ return useMutation({
3299
+ mutationKey: ["ecency-wallets", asset, operation],
3300
+ mutationFn: async (payload) => {
3301
+ const operationFn = operationToFunctionMap[asset][operation];
3302
+ if (operationFn) {
3303
+ return operationFn(payload);
3304
+ }
3305
+ const balancesListQuery = getHiveEngineTokensBalancesQueryOptions(username);
3306
+ await getQueryClient().prefetchQuery(balancesListQuery);
3307
+ const balances = getQueryClient().getQueryData(
3308
+ balancesListQuery.queryKey
3309
+ );
3310
+ if (balances?.some((b) => b.symbol === asset)) {
3311
+ const operationFn2 = engineOperationToFunctionMap[operation];
3312
+ if (operationFn2) {
3313
+ return operationFn2({ ...payload, asset });
3314
+ }
3315
+ }
3316
+ throw new Error("[SDK][Wallets] \u2013 no operation for given asset");
3317
+ },
3318
+ onSuccess: () => {
3319
+ recordActivity();
3320
+ const query = getAccountWalletAssetInfoQueryOptions(username, asset, {
3321
+ refetch: true
3322
+ });
3323
+ setTimeout(
3324
+ () => getQueryClient().invalidateQueries({
3325
+ queryKey: query.queryKey
3326
+ }),
3327
+ 5e3
3328
+ );
3329
+ }
3330
+ });
3331
+ }
3332
+
3333
+ // src/index.ts
3334
+ rememberScryptBsvVersion();
3335
+
3336
+ export { AssetOperation, EcencyWalletBasicTokens, EcencyWalletCurrency, private_api_exports as EcencyWalletsPrivateApi, NaiMap, PointTransactionType, Symbol2 as Symbol, buildAptTx, buildEthTx, buildExternalTx, buildPsbt, buildSolTx, buildTonTx, buildTronTx, decryptMemoWithAccounts, decryptMemoWithKeys, delay, delegateEngineToken, delegateHive, deriveHiveKey, deriveHiveKeys, deriveHiveMasterPasswordKey, deriveHiveMasterPasswordKeys, detectHiveKeyDerivation, encryptMemoWithAccounts, encryptMemoWithKeys, getAccountWalletAssetInfoQueryOptions, getAccountWalletListQueryOptions, getAllTokensListQueryOptions, getBoundFetch, getCoinGeckoPriceQueryOptions, getHbdAssetGeneralInfoQueryOptions, getHbdAssetTransactionsQueryOptions, getHiveAssetGeneralInfoQueryOptions, getHiveAssetMetricQueryOptions, getHiveAssetTransactionsQueryOptions, getHiveAssetWithdrawalRoutesQueryOptions, getHiveEngineTokenGeneralInfoQueryOptions, getHiveEngineTokenTransactionsQueryOptions, getHiveEngineTokensBalancesQueryOptions, getHiveEngineTokensMarketQueryOptions, getHiveEngineTokensMetadataQueryOptions, getHiveEngineTokensMetricsQueryOptions, getHivePowerAssetGeneralInfoQueryOptions, getHivePowerAssetTransactionsQueryOptions, getHivePowerDelegatesInfiniteQueryOptions, getHivePowerDelegatingsQueryOptions, getLarynxAssetGeneralInfoQueryOptions, getLarynxPowerAssetGeneralInfoQueryOptions, getPointsAssetGeneralInfoQueryOptions, getPointsAssetTransactionsQueryOptions, getPointsQueryOptions, getSpkAssetGeneralInfoQueryOptions, getSpkMarketsQueryOptions, getTokenOperationsQueryOptions, getWallet, isEmptyDate, lockLarynx, mnemonicToSeedBip39, parseAsset, powerDownHive, powerUpHive, powerUpLarynx, rewardSpk, signDigest, signExternalTx, signExternalTxAndBroadcast, signTx, signTxAndBroadcast, stakeEngineToken, transferEngineToken, transferHive, transferPoint, transferSpk, transferToSavingsHive, undelegateEngineToken, unstakeEngineToken, useClaimPoints, useClaimRewards, useGetExternalWalletBalanceQuery, useHiveKeysQuery, useImportWallet, useSaveWalletInformationToMetadata, useSeedPhrase, useWalletCreate, useWalletOperation, useWalletsCacheQuery, vestsToHp, withdrawVestingRouteHive };
3337
+ //# sourceMappingURL=index.browser.mjs.map
3338
+ //# sourceMappingURL=index.browser.mjs.map