@ecency/wallets 1.4.1 → 1.4.2

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