@ecency/wallets 1.4.2 → 1.4.6

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