@ecency/wallets 1.4.1 → 1.4.5

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