@ecency/wallets 1.4.2 → 1.4.6

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