@ecency/wallets 1.4.2 → 1.4.5

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