@ecency/sdk 1.2.1 → 1.3.1

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,1736 @@
1
+ 'use strict';
2
+
3
+ var reactQuery = require('@tanstack/react-query');
4
+ var dhive = require('@hiveio/dhive');
5
+ var hs = require('hivesigner');
6
+ var R = require('remeda');
7
+
8
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
+
10
+ function _interopNamespace(e) {
11
+ if (e && e.__esModule) return e;
12
+ var n = Object.create(null);
13
+ if (e) {
14
+ Object.keys(e).forEach(function (k) {
15
+ if (k !== 'default') {
16
+ var d = Object.getOwnPropertyDescriptor(e, k);
17
+ Object.defineProperty(n, k, d.get ? d : {
18
+ enumerable: true,
19
+ get: function () { return e[k]; }
20
+ });
21
+ }
22
+ });
23
+ }
24
+ n.default = e;
25
+ return Object.freeze(n);
26
+ }
27
+
28
+ var hs__default = /*#__PURE__*/_interopDefault(hs);
29
+ var R__namespace = /*#__PURE__*/_interopNamespace(R);
30
+
31
+ var __defProp = Object.defineProperty;
32
+ var __export = (target, all) => {
33
+ for (var name in all)
34
+ __defProp(target, name, { get: all[name], enumerable: true });
35
+ };
36
+
37
+ // src/modules/core/mock-storage.ts
38
+ var MockStorage = class {
39
+ length = 0;
40
+ clear() {
41
+ throw new Error("Method not implemented.");
42
+ }
43
+ getItem(key) {
44
+ return this[key];
45
+ }
46
+ key(index) {
47
+ return Object.keys(this)[index];
48
+ }
49
+ removeItem(key) {
50
+ delete this[key];
51
+ }
52
+ setItem(key, value) {
53
+ this[key] = value;
54
+ }
55
+ };
56
+ var CONFIG = {
57
+ privateApiHost: "https://ecency.com",
58
+ storage: typeof window === "undefined" ? new MockStorage() : window.localStorage,
59
+ storagePrefix: "ecency",
60
+ hiveClient: new dhive.Client(
61
+ [
62
+ "https://api.hive.blog",
63
+ "https://api.deathwing.me",
64
+ "https://rpc.mahdiyari.info",
65
+ "https://api.openhive.network",
66
+ "https://techcoderx.com",
67
+ "https://hive-api.arcange.eu",
68
+ "https://api.syncad.com",
69
+ "https://anyx.io",
70
+ "https://api.c0ff33a.uk",
71
+ "https://hiveapi.actifit.io",
72
+ "https://hive-api.3speak.tv"
73
+ ],
74
+ {
75
+ timeout: 2e3,
76
+ failoverThreshold: 2,
77
+ consoleOnFailover: true
78
+ }
79
+ ),
80
+ heliusApiKey: process.env.VITE_HELIUS_API_KEY,
81
+ queryClient: new reactQuery.QueryClient(),
82
+ plausibleHost: "https://pl.ecency.com",
83
+ spkNode: "https://spk.good-karma.xyz"
84
+ };
85
+ exports.ConfigManager = void 0;
86
+ ((ConfigManager2) => {
87
+ function setQueryClient(client) {
88
+ CONFIG.queryClient = client;
89
+ }
90
+ ConfigManager2.setQueryClient = setQueryClient;
91
+ })(exports.ConfigManager || (exports.ConfigManager = {}));
92
+
93
+ // src/modules/core/utils/decoder-encoder.ts
94
+ function encodeObj(o) {
95
+ return btoa(JSON.stringify(o));
96
+ }
97
+ function decodeObj(o) {
98
+ let dataToParse = atob(o);
99
+ if (dataToParse[0] !== "{") {
100
+ return void 0;
101
+ }
102
+ return JSON.parse(dataToParse);
103
+ }
104
+
105
+ // src/modules/core/utils/parse-asset.ts
106
+ var Symbol2 = /* @__PURE__ */ ((Symbol3) => {
107
+ Symbol3["HIVE"] = "HIVE";
108
+ Symbol3["HBD"] = "HBD";
109
+ Symbol3["VESTS"] = "VESTS";
110
+ Symbol3["SPK"] = "SPK";
111
+ return Symbol3;
112
+ })(Symbol2 || {});
113
+ var NaiMap = /* @__PURE__ */ ((NaiMap2) => {
114
+ NaiMap2["@@000000021"] = "HIVE";
115
+ NaiMap2["@@000000013"] = "HBD";
116
+ NaiMap2["@@000000037"] = "VESTS";
117
+ return NaiMap2;
118
+ })(NaiMap || {});
119
+ function parseAsset(sval) {
120
+ if (typeof sval === "string") {
121
+ const sp = sval.split(" ");
122
+ return {
123
+ amount: parseFloat(sp[0]),
124
+ // @ts-ignore
125
+ symbol: Symbol2[sp[1]]
126
+ };
127
+ } else {
128
+ return {
129
+ amount: parseFloat(sval.amount.toString()) / Math.pow(10, sval.precision),
130
+ // @ts-ignore
131
+ symbol: NaiMap[sval.nai]
132
+ };
133
+ }
134
+ }
135
+
136
+ // src/modules/core/utils/get-bound-fetch.ts
137
+ var cachedFetch;
138
+ function getBoundFetch() {
139
+ if (!cachedFetch) {
140
+ if (typeof globalThis.fetch !== "function") {
141
+ throw new Error("[Ecency][SDK] - global fetch is not available");
142
+ }
143
+ cachedFetch = globalThis.fetch.bind(globalThis);
144
+ }
145
+ return cachedFetch;
146
+ }
147
+
148
+ // src/modules/core/storage.ts
149
+ var getUser = (username) => {
150
+ try {
151
+ const raw = CONFIG.storage.getItem(
152
+ CONFIG.storagePrefix + "_user_" + username
153
+ );
154
+ return decodeObj(JSON.parse(raw));
155
+ } catch (e) {
156
+ console.error(e);
157
+ return void 0;
158
+ }
159
+ };
160
+ var getAccessToken = (username) => getUser(username) && getUser(username).accessToken;
161
+ var getPostingKey = (username) => getUser(username) && getUser(username).postingKey;
162
+ var getLoginType = (username) => getUser(username) && getUser(username).loginType;
163
+ var getRefreshToken = (username) => getUser(username) && getUser(username).refreshToken;
164
+
165
+ // src/modules/keychain/keychain.ts
166
+ var keychain_exports = {};
167
+ __export(keychain_exports, {
168
+ broadcast: () => broadcast,
169
+ customJson: () => customJson,
170
+ handshake: () => handshake
171
+ });
172
+ function handshake() {
173
+ return new Promise((resolve) => {
174
+ window.hive_keychain?.requestHandshake(() => {
175
+ resolve();
176
+ });
177
+ });
178
+ }
179
+ var broadcast = (account, operations, key, rpc = null) => new Promise((resolve, reject) => {
180
+ window.hive_keychain?.requestBroadcast(
181
+ account,
182
+ operations,
183
+ key,
184
+ (resp) => {
185
+ if (!resp.success) {
186
+ reject({ message: "Operation cancelled" });
187
+ }
188
+ resolve(resp);
189
+ },
190
+ rpc
191
+ );
192
+ });
193
+ var customJson = (account, id, key, json, display_msg, rpc = null) => new Promise((resolve, reject) => {
194
+ window.hive_keychain?.requestCustomJson(
195
+ account,
196
+ id,
197
+ key,
198
+ json,
199
+ display_msg,
200
+ (resp) => {
201
+ if (!resp.success) {
202
+ reject({ message: "Operation cancelled" });
203
+ }
204
+ resolve(resp);
205
+ },
206
+ rpc
207
+ );
208
+ });
209
+
210
+ // src/modules/core/mutations/use-broadcast-mutation.ts
211
+ function useBroadcastMutation(mutationKey = [], username, operations, onSuccess = () => {
212
+ }) {
213
+ return reactQuery.useMutation({
214
+ onSuccess,
215
+ mutationKey: [...mutationKey, username],
216
+ mutationFn: async (payload) => {
217
+ if (!username) {
218
+ throw new Error(
219
+ "[Core][Broadcast] Attempted to call broadcast API with anon user"
220
+ );
221
+ }
222
+ const postingKey = getPostingKey(username);
223
+ if (postingKey) {
224
+ const privateKey = dhive.PrivateKey.fromString(postingKey);
225
+ return CONFIG.hiveClient.broadcast.sendOperations(
226
+ operations(payload),
227
+ privateKey
228
+ );
229
+ }
230
+ const loginType = getLoginType(username);
231
+ if (loginType && loginType == "keychain") {
232
+ return keychain_exports.broadcast(
233
+ username,
234
+ operations(payload),
235
+ "Posting"
236
+ ).then((r) => r.result);
237
+ }
238
+ let token = getAccessToken(username);
239
+ if (token) {
240
+ const f = getBoundFetch();
241
+ const res = await f("https://hivesigner.com/api/broadcast", {
242
+ method: "POST",
243
+ headers: {
244
+ Authorization: token,
245
+ "Content-Type": "application/json",
246
+ Accept: "application/json"
247
+ },
248
+ body: JSON.stringify({ operations: operations(payload) })
249
+ });
250
+ if (!res.ok) {
251
+ const txt = await res.text().catch(() => "");
252
+ throw new Error(`[Hivesigner] ${res.status} ${res.statusText} ${txt}`);
253
+ }
254
+ const json = await res.json();
255
+ if (json?.errors) {
256
+ throw new Error(`[Hivesigner] ${JSON.stringify(json.errors)}`);
257
+ }
258
+ return json.result;
259
+ }
260
+ throw new Error(
261
+ "[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token"
262
+ );
263
+ }
264
+ });
265
+ }
266
+ async function broadcastJson(username, id, payload) {
267
+ if (!username) {
268
+ throw new Error(
269
+ "[Core][Broadcast] Attempted to call broadcast API with anon user"
270
+ );
271
+ }
272
+ const jjson = {
273
+ id,
274
+ required_auths: [],
275
+ required_posting_auths: [username],
276
+ json: JSON.stringify(payload)
277
+ };
278
+ const postingKey = getPostingKey(username);
279
+ if (postingKey) {
280
+ const privateKey = dhive.PrivateKey.fromString(postingKey);
281
+ return CONFIG.hiveClient.broadcast.json(
282
+ jjson,
283
+ privateKey
284
+ );
285
+ }
286
+ const loginType = getLoginType(username);
287
+ if (loginType && loginType == "keychain") {
288
+ return keychain_exports.broadcast(username, [["custom_json", jjson]], "Posting").then((r) => r.result);
289
+ }
290
+ let token = getAccessToken(username);
291
+ if (token) {
292
+ const response = await new hs__default.default.Client({
293
+ accessToken: token
294
+ }).customJson([], [username], id, JSON.stringify(payload));
295
+ return response.result;
296
+ }
297
+ throw new Error(
298
+ "[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token"
299
+ );
300
+ }
301
+ function makeQueryClient() {
302
+ return new reactQuery.QueryClient({
303
+ defaultOptions: {
304
+ queries: {
305
+ // With SSR, we usually want to set some default staleTime
306
+ // above 0 to avoid refetching immediately on the client
307
+ // staleTime: 60 * 1000,
308
+ refetchOnWindowFocus: false,
309
+ refetchOnMount: false
310
+ }
311
+ }
312
+ });
313
+ }
314
+ var getQueryClient = () => CONFIG.queryClient;
315
+ exports.EcencyQueriesManager = void 0;
316
+ ((EcencyQueriesManager2) => {
317
+ function getQueryData(queryKey) {
318
+ const queryClient = getQueryClient();
319
+ return queryClient.getQueryData(queryKey);
320
+ }
321
+ EcencyQueriesManager2.getQueryData = getQueryData;
322
+ function getInfiniteQueryData(queryKey) {
323
+ const queryClient = getQueryClient();
324
+ return queryClient.getQueryData(queryKey);
325
+ }
326
+ EcencyQueriesManager2.getInfiniteQueryData = getInfiniteQueryData;
327
+ async function prefetchQuery(options) {
328
+ const queryClient = getQueryClient();
329
+ await queryClient.prefetchQuery(options);
330
+ return getQueryData(options.queryKey);
331
+ }
332
+ EcencyQueriesManager2.prefetchQuery = prefetchQuery;
333
+ async function prefetchInfiniteQuery(options) {
334
+ const queryClient = getQueryClient();
335
+ await queryClient.prefetchInfiniteQuery(options);
336
+ return getInfiniteQueryData(options.queryKey);
337
+ }
338
+ EcencyQueriesManager2.prefetchInfiniteQuery = prefetchInfiniteQuery;
339
+ function generateClientServerQuery(options) {
340
+ return {
341
+ prefetch: () => prefetchQuery(options),
342
+ getData: () => getQueryData(options.queryKey),
343
+ useClientQuery: () => reactQuery.useQuery(options),
344
+ fetchAndGet: () => getQueryClient().fetchQuery(options)
345
+ };
346
+ }
347
+ EcencyQueriesManager2.generateClientServerQuery = generateClientServerQuery;
348
+ function generateClientServerInfiniteQuery(options) {
349
+ return {
350
+ prefetch: () => prefetchInfiniteQuery(options),
351
+ getData: () => getInfiniteQueryData(options.queryKey),
352
+ useClientQuery: () => reactQuery.useInfiniteQuery(options),
353
+ fetchAndGet: () => getQueryClient().fetchInfiniteQuery(options)
354
+ };
355
+ }
356
+ EcencyQueriesManager2.generateClientServerInfiniteQuery = generateClientServerInfiniteQuery;
357
+ })(exports.EcencyQueriesManager || (exports.EcencyQueriesManager = {}));
358
+ function getDynamicPropsQueryOptions() {
359
+ return reactQuery.queryOptions({
360
+ queryKey: ["core", "dynamic-props"],
361
+ refetchInterval: 6e4,
362
+ staleTime: 6e4,
363
+ refetchOnMount: true,
364
+ queryFn: async () => {
365
+ const globalDynamic = await CONFIG.hiveClient.database.getDynamicGlobalProperties().then((r) => ({
366
+ total_vesting_fund_hive: r.total_vesting_fund_hive || r.total_vesting_fund_steem,
367
+ total_vesting_shares: r.total_vesting_shares,
368
+ hbd_print_rate: r.hbd_print_rate || r.sbd_print_rate,
369
+ hbd_interest_rate: r.hbd_interest_rate,
370
+ head_block_number: r.head_block_number,
371
+ vesting_reward_percent: r.vesting_reward_percent,
372
+ virtual_supply: r.virtual_supply
373
+ }));
374
+ const feedHistory = await CONFIG.hiveClient.database.call("get_feed_history");
375
+ const chainProps = await CONFIG.hiveClient.database.call(
376
+ "get_chain_properties"
377
+ );
378
+ const rewardFund = await CONFIG.hiveClient.database.call(
379
+ "get_reward_fund",
380
+ ["post"]
381
+ );
382
+ const hivePerMVests = parseAsset(globalDynamic.total_vesting_fund_hive).amount / parseAsset(globalDynamic.total_vesting_shares).amount * 1e6;
383
+ const base = parseAsset(feedHistory.current_median_history.base).amount;
384
+ const quote = parseAsset(feedHistory.current_median_history.quote).amount;
385
+ const fundRecentClaims = parseFloat(rewardFund.recent_claims);
386
+ const fundRewardBalance = parseAsset(rewardFund.reward_balance).amount;
387
+ const hbdPrintRate = globalDynamic.hbd_print_rate;
388
+ const hbdInterestRate = globalDynamic.hbd_interest_rate;
389
+ const headBlock = globalDynamic.head_block_number;
390
+ const totalVestingFund = parseAsset(
391
+ globalDynamic.total_vesting_fund_hive
392
+ ).amount;
393
+ const totalVestingShares = parseAsset(
394
+ globalDynamic.total_vesting_shares
395
+ ).amount;
396
+ const virtualSupply = parseAsset(globalDynamic.virtual_supply).amount;
397
+ const vestingRewardPercent = globalDynamic.vesting_reward_percent;
398
+ const accountCreationFee = chainProps.account_creation_fee;
399
+ return {
400
+ hivePerMVests,
401
+ base,
402
+ quote,
403
+ fundRecentClaims,
404
+ fundRewardBalance,
405
+ hbdPrintRate,
406
+ hbdInterestRate,
407
+ headBlock,
408
+ totalVestingFund,
409
+ totalVestingShares,
410
+ virtualSupply,
411
+ vestingRewardPercent,
412
+ accountCreationFee
413
+ };
414
+ }
415
+ });
416
+ }
417
+ function getAccountFullQueryOptions(username) {
418
+ return reactQuery.queryOptions({
419
+ queryKey: ["get-account-full", username],
420
+ queryFn: async () => {
421
+ if (!username) {
422
+ throw new Error("[SDK] Username is empty");
423
+ }
424
+ const response = await CONFIG.hiveClient.database.getAccounts([
425
+ username
426
+ ]);
427
+ if (!response[0]) {
428
+ throw new Error("[SDK] No account with given username");
429
+ }
430
+ let profile = {};
431
+ try {
432
+ profile = JSON.parse(response[0].posting_json_metadata).profile;
433
+ } catch (e) {
434
+ }
435
+ let follow_stats;
436
+ try {
437
+ follow_stats = await CONFIG.hiveClient.database.call(
438
+ "get_follow_count",
439
+ [username]
440
+ );
441
+ } catch (e) {
442
+ }
443
+ let reputationValue = 0;
444
+ try {
445
+ const reputation = await CONFIG.hiveClient.call(
446
+ "condenser_api",
447
+ "get_account_reputations",
448
+ [username, 1]
449
+ );
450
+ reputationValue = reputation[0]?.reputation ?? 0;
451
+ } catch (e) {
452
+ }
453
+ return {
454
+ name: response[0].name,
455
+ owner: response[0].owner,
456
+ active: response[0].active,
457
+ posting: response[0].posting,
458
+ memo_key: response[0].memo_key,
459
+ post_count: response[0].post_count,
460
+ created: response[0].created,
461
+ posting_json_metadata: response[0].posting_json_metadata,
462
+ last_vote_time: response[0].last_vote_time,
463
+ last_post: response[0].last_post,
464
+ json_metadata: response[0].json_metadata,
465
+ reward_hive_balance: response[0].reward_hive_balance,
466
+ reward_hbd_balance: response[0].reward_hbd_balance,
467
+ reward_vesting_hive: response[0].reward_vesting_hive,
468
+ reward_vesting_balance: response[0].reward_vesting_balance,
469
+ balance: response[0].balance,
470
+ hbd_balance: response[0].hbd_balance,
471
+ savings_balance: response[0].savings_balance,
472
+ savings_hbd_balance: response[0].savings_hbd_balance,
473
+ savings_hbd_last_interest_payment: response[0].savings_hbd_last_interest_payment,
474
+ savings_hbd_seconds_last_update: response[0].savings_hbd_seconds_last_update,
475
+ savings_hbd_seconds: response[0].savings_hbd_seconds,
476
+ next_vesting_withdrawal: response[0].next_vesting_withdrawal,
477
+ pending_claimed_accounts: response[0].pending_claimed_accounts,
478
+ vesting_shares: response[0].vesting_shares,
479
+ delegated_vesting_shares: response[0].delegated_vesting_shares,
480
+ received_vesting_shares: response[0].received_vesting_shares,
481
+ vesting_withdraw_rate: response[0].vesting_withdraw_rate,
482
+ to_withdraw: response[0].to_withdraw,
483
+ withdrawn: response[0].withdrawn,
484
+ witness_votes: response[0].witness_votes,
485
+ proxy: response[0].proxy,
486
+ recovery_account: response[0].recovery_account,
487
+ proxied_vsf_votes: response[0].proxied_vsf_votes,
488
+ voting_manabar: response[0].voting_manabar,
489
+ voting_power: response[0].voting_power,
490
+ downvote_manabar: response[0].downvote_manabar,
491
+ follow_stats,
492
+ reputation: reputationValue,
493
+ profile
494
+ };
495
+ },
496
+ enabled: !!username,
497
+ staleTime: 6e4
498
+ });
499
+ }
500
+ function getSearchAccountsByUsernameQueryOptions(query, limit = 5, excludeList = []) {
501
+ return reactQuery.queryOptions({
502
+ queryKey: ["accounts", "search", query, excludeList],
503
+ enabled: !!query,
504
+ queryFn: async () => {
505
+ const response = await CONFIG.hiveClient.database.call(
506
+ "lookup_accounts",
507
+ [query, limit]
508
+ );
509
+ return response.filter(
510
+ (item) => excludeList.length > 0 ? !excludeList.includes(item) : true
511
+ );
512
+ }
513
+ });
514
+ }
515
+ function checkUsernameWalletsPendingQueryOptions(username) {
516
+ return reactQuery.queryOptions({
517
+ queryKey: ["accounts", "check-wallet-pending", username],
518
+ queryFn: async () => {
519
+ const fetchApi = getBoundFetch();
520
+ const response = await fetchApi(
521
+ CONFIG.privateApiHost + "/private-api/wallets-chkuser",
522
+ {
523
+ method: "POST",
524
+ headers: {
525
+ "Content-Type": "application/json"
526
+ },
527
+ body: JSON.stringify({
528
+ username
529
+ })
530
+ }
531
+ );
532
+ return await response.json();
533
+ },
534
+ enabled: !!username,
535
+ refetchOnMount: true
536
+ });
537
+ }
538
+ function getRelationshipBetweenAccountsQueryOptions(reference, target) {
539
+ return reactQuery.queryOptions({
540
+ queryKey: ["accounts", "relations", reference, target],
541
+ enabled: !!reference && !!target,
542
+ refetchOnMount: false,
543
+ refetchInterval: 36e5,
544
+ queryFn: async () => {
545
+ return await CONFIG.hiveClient.call(
546
+ "bridge",
547
+ "get_relationship_between_accounts",
548
+ [reference, target]
549
+ );
550
+ }
551
+ });
552
+ }
553
+ function getAccountSubscriptionsQueryOptions(username) {
554
+ return reactQuery.queryOptions({
555
+ queryKey: ["accounts", "subscriptions", username],
556
+ enabled: !!username,
557
+ queryFn: async () => {
558
+ const response = await CONFIG.hiveClient.call(
559
+ "bridge",
560
+ "list_all_subscriptions",
561
+ {
562
+ account: username
563
+ }
564
+ );
565
+ return response ?? [];
566
+ }
567
+ });
568
+ }
569
+ function getActiveAccountBookmarksQueryOptions(activeUsername) {
570
+ return reactQuery.queryOptions({
571
+ queryKey: ["accounts", "bookmarks", activeUsername],
572
+ enabled: !!activeUsername,
573
+ queryFn: async () => {
574
+ if (!activeUsername) {
575
+ throw new Error("[SDK][Accounts][Bookmarks] \u2013 no active user");
576
+ }
577
+ const fetchApi = getBoundFetch();
578
+ const response = await fetchApi(
579
+ CONFIG.privateApiHost + "/private-api/bookmarks",
580
+ {
581
+ method: "POST",
582
+ headers: {
583
+ "Content-Type": "application/json"
584
+ },
585
+ body: JSON.stringify({ code: getAccessToken(activeUsername) })
586
+ }
587
+ );
588
+ return await response.json();
589
+ }
590
+ });
591
+ }
592
+ function getActiveAccountFavouritesQueryOptions(activeUsername) {
593
+ return reactQuery.queryOptions({
594
+ queryKey: ["accounts", "favourites", activeUsername],
595
+ enabled: !!activeUsername,
596
+ queryFn: async () => {
597
+ if (!activeUsername) {
598
+ throw new Error("[SDK][Accounts][Favourites] \u2013 no active user");
599
+ }
600
+ const fetchApi = getBoundFetch();
601
+ const response = await fetchApi(
602
+ CONFIG.privateApiHost + "/private-api/favorites",
603
+ {
604
+ method: "POST",
605
+ headers: {
606
+ "Content-Type": "application/json"
607
+ },
608
+ body: JSON.stringify({ code: getAccessToken(activeUsername) })
609
+ }
610
+ );
611
+ return await response.json();
612
+ }
613
+ });
614
+ }
615
+ function getAccountRecoveriesQueryOptions(username) {
616
+ return reactQuery.queryOptions({
617
+ enabled: !!username,
618
+ queryKey: ["accounts", "recoveries", username],
619
+ queryFn: async () => {
620
+ const fetchApi = getBoundFetch();
621
+ const response = await fetchApi(
622
+ CONFIG.privateApiHost + "/private-api/recoveries",
623
+ {
624
+ method: "POST",
625
+ headers: {
626
+ "Content-Type": "application/json"
627
+ },
628
+ body: JSON.stringify({ code: getAccessToken(username) })
629
+ }
630
+ );
631
+ return response.json();
632
+ }
633
+ });
634
+ }
635
+ function getAccountPendingRecoveryQueryOptions(username) {
636
+ return reactQuery.queryOptions({
637
+ enabled: !!username,
638
+ queryKey: ["accounts", "recoveries", username, "pending-request"],
639
+ queryFn: () => CONFIG.hiveClient.call(
640
+ "database_api",
641
+ "find_change_recovery_account_requests",
642
+ { accounts: [username] }
643
+ )
644
+ });
645
+ }
646
+ function sanitizeTokens(tokens) {
647
+ return tokens?.map(({ meta, ...rest }) => {
648
+ if (!meta || typeof meta !== "object") {
649
+ return { ...rest, meta };
650
+ }
651
+ const { privateKey, username, ...safeMeta } = meta;
652
+ return { ...rest, meta: safeMeta };
653
+ });
654
+ }
655
+ function getBuiltProfile({
656
+ profile,
657
+ tokens,
658
+ data
659
+ }) {
660
+ const metadata = R__namespace.pipe(
661
+ JSON.parse(data?.posting_json_metadata || "{}").profile,
662
+ R__namespace.mergeDeep(profile ?? {})
663
+ );
664
+ if (tokens && tokens.length > 0) {
665
+ metadata.tokens = tokens;
666
+ }
667
+ metadata.tokens = sanitizeTokens(metadata.tokens);
668
+ return metadata;
669
+ }
670
+ function useAccountUpdate(username) {
671
+ const queryClient = reactQuery.useQueryClient();
672
+ const { data } = reactQuery.useQuery(getAccountFullQueryOptions(username));
673
+ return useBroadcastMutation(
674
+ ["accounts", "update"],
675
+ username,
676
+ (payload) => {
677
+ if (!data) {
678
+ throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");
679
+ }
680
+ return [
681
+ [
682
+ "account_update2",
683
+ {
684
+ account: username,
685
+ json_metadata: "",
686
+ extensions: [],
687
+ posting_json_metadata: JSON.stringify({
688
+ profile: getBuiltProfile({ ...payload, data })
689
+ })
690
+ }
691
+ ]
692
+ ];
693
+ },
694
+ (_, variables) => queryClient.setQueryData(
695
+ getAccountFullQueryOptions(username).queryKey,
696
+ (data2) => {
697
+ if (!data2) {
698
+ return data2;
699
+ }
700
+ const obj = R__namespace.clone(data2);
701
+ obj.profile = getBuiltProfile({ ...variables, data: data2 });
702
+ return obj;
703
+ }
704
+ )
705
+ );
706
+ }
707
+ function useAccountRelationsUpdate(reference, target, onSuccess, onError) {
708
+ return reactQuery.useMutation({
709
+ mutationKey: ["accounts", "relation", "update", reference, target],
710
+ mutationFn: async (kind) => {
711
+ const relationsQuery = getRelationshipBetweenAccountsQueryOptions(
712
+ reference,
713
+ target
714
+ );
715
+ await getQueryClient().prefetchQuery(relationsQuery);
716
+ const actualRelation = getQueryClient().getQueryData(
717
+ relationsQuery.queryKey
718
+ );
719
+ await broadcastJson(reference, "follow", [
720
+ "follow",
721
+ {
722
+ follower: reference,
723
+ following: target,
724
+ what: [
725
+ ...kind === "toggle-ignore" && !actualRelation?.ignores ? ["ignore"] : [],
726
+ ...kind === "toggle-follow" && !actualRelation?.follows ? ["blog"] : []
727
+ ]
728
+ }
729
+ ]);
730
+ return {
731
+ ...actualRelation,
732
+ ignores: kind === "toggle-ignore" ? !actualRelation?.ignores : actualRelation?.ignores,
733
+ follows: kind === "toggle-follow" ? !actualRelation?.follows : actualRelation?.follows
734
+ };
735
+ },
736
+ onError,
737
+ onSuccess(data) {
738
+ onSuccess(data);
739
+ getQueryClient().setQueryData(
740
+ ["accounts", "relations", reference, target],
741
+ data
742
+ );
743
+ }
744
+ });
745
+ }
746
+ function useBookmarkAdd(username, onSuccess, onError) {
747
+ return reactQuery.useMutation({
748
+ mutationKey: ["accounts", "bookmarks", "add", username],
749
+ mutationFn: async ({ author, permlink }) => {
750
+ if (!username) {
751
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
752
+ }
753
+ const fetchApi = getBoundFetch();
754
+ const response = await fetchApi(
755
+ CONFIG.privateApiHost + "/private-api/bookmarks-add",
756
+ {
757
+ method: "POST",
758
+ headers: {
759
+ "Content-Type": "application/json"
760
+ },
761
+ body: JSON.stringify({
762
+ author,
763
+ permlink,
764
+ code: getAccessToken(username)
765
+ })
766
+ }
767
+ );
768
+ return response.json();
769
+ },
770
+ onSuccess: () => {
771
+ onSuccess();
772
+ getQueryClient().invalidateQueries({
773
+ queryKey: ["accounts", "bookmarks", username]
774
+ });
775
+ },
776
+ onError
777
+ });
778
+ }
779
+ function useBookmarkDelete(username, onSuccess, onError) {
780
+ return reactQuery.useMutation({
781
+ mutationKey: ["accounts", "bookmarks", "delete", username],
782
+ mutationFn: async (bookmarkId) => {
783
+ if (!username) {
784
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
785
+ }
786
+ const fetchApi = getBoundFetch();
787
+ const response = await fetchApi(
788
+ CONFIG.privateApiHost + "/private-api/bookmarks-delete",
789
+ {
790
+ method: "POST",
791
+ headers: {
792
+ "Content-Type": "application/json"
793
+ },
794
+ body: JSON.stringify({
795
+ id: bookmarkId,
796
+ code: getAccessToken(username)
797
+ })
798
+ }
799
+ );
800
+ return response.json();
801
+ },
802
+ onSuccess: () => {
803
+ onSuccess();
804
+ getQueryClient().invalidateQueries({
805
+ queryKey: ["accounts", "bookmarks", username]
806
+ });
807
+ },
808
+ onError
809
+ });
810
+ }
811
+ function useAccountFavouriteAdd(username, onSuccess, onError) {
812
+ return reactQuery.useMutation({
813
+ mutationKey: ["accounts", "favourites", "add", username],
814
+ mutationFn: async (account) => {
815
+ if (!username) {
816
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
817
+ }
818
+ const fetchApi = getBoundFetch();
819
+ const response = await fetchApi(
820
+ CONFIG.privateApiHost + "/private-api/favorites-add",
821
+ {
822
+ method: "POST",
823
+ headers: {
824
+ "Content-Type": "application/json"
825
+ },
826
+ body: JSON.stringify({
827
+ account,
828
+ code: getAccessToken(username)
829
+ })
830
+ }
831
+ );
832
+ return response.json();
833
+ },
834
+ onSuccess: () => {
835
+ onSuccess();
836
+ getQueryClient().invalidateQueries({
837
+ queryKey: ["accounts", "favourites", username]
838
+ });
839
+ },
840
+ onError
841
+ });
842
+ }
843
+ function useAccountFavouriteDelete(username, onSuccess, onError) {
844
+ return reactQuery.useMutation({
845
+ mutationKey: ["accounts", "favourites", "add", username],
846
+ mutationFn: async (account) => {
847
+ if (!username) {
848
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
849
+ }
850
+ const fetchApi = getBoundFetch();
851
+ const response = await fetchApi(
852
+ CONFIG.privateApiHost + "/private-api/favorites-delete",
853
+ {
854
+ method: "POST",
855
+ headers: {
856
+ "Content-Type": "application/json"
857
+ },
858
+ body: JSON.stringify({
859
+ account,
860
+ code: getAccessToken(username)
861
+ })
862
+ }
863
+ );
864
+ return response.json();
865
+ },
866
+ onSuccess: () => {
867
+ onSuccess();
868
+ getQueryClient().invalidateQueries({
869
+ queryKey: ["accounts", "favourites", username]
870
+ });
871
+ },
872
+ onError
873
+ });
874
+ }
875
+ function dedupeAndSortKeyAuths(existing, additions) {
876
+ const merged = /* @__PURE__ */ new Map();
877
+ existing.forEach(([key, weight]) => {
878
+ merged.set(key.toString(), weight);
879
+ });
880
+ additions.forEach(([key, weight]) => {
881
+ merged.set(key.toString(), weight);
882
+ });
883
+ return Array.from(merged.entries()).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)).map(([key, weight]) => [key, weight]);
884
+ }
885
+ function useAccountUpdateKeyAuths(username, options) {
886
+ const { data: accountData } = reactQuery.useQuery(getAccountFullQueryOptions(username));
887
+ return reactQuery.useMutation({
888
+ mutationKey: ["accounts", "keys-update", username],
889
+ mutationFn: async ({ keys, keepCurrent = false, currentKey }) => {
890
+ if (!accountData) {
891
+ throw new Error(
892
+ "[SDK][Update password] \u2013 cannot update keys for anon user"
893
+ );
894
+ }
895
+ const prepareAuth = (keyName) => {
896
+ const auth = R__namespace.clone(accountData[keyName]);
897
+ auth.key_auths = dedupeAndSortKeyAuths(
898
+ keepCurrent ? auth.key_auths : [],
899
+ keys.map(
900
+ (values, i) => [values[keyName].createPublic().toString(), i + 1]
901
+ )
902
+ );
903
+ return auth;
904
+ };
905
+ return CONFIG.hiveClient.broadcast.updateAccount(
906
+ {
907
+ account: username,
908
+ json_metadata: accountData.json_metadata,
909
+ owner: prepareAuth("owner"),
910
+ active: prepareAuth("active"),
911
+ posting: prepareAuth("posting"),
912
+ memo_key: keepCurrent ? accountData.memo_key : keys[0].memo_key.createPublic().toString()
913
+ },
914
+ currentKey
915
+ );
916
+ },
917
+ ...options
918
+ });
919
+ }
920
+ function useAccountUpdatePassword(username, options) {
921
+ const { data: accountData } = reactQuery.useQuery(getAccountFullQueryOptions(username));
922
+ const { mutateAsync: updateKeys } = useAccountUpdateKeyAuths(username);
923
+ return reactQuery.useMutation({
924
+ mutationKey: ["accounts", "password-update", username],
925
+ mutationFn: async ({
926
+ newPassword,
927
+ currentPassword,
928
+ keepCurrent
929
+ }) => {
930
+ if (!accountData) {
931
+ throw new Error(
932
+ "[SDK][Update password] \u2013 cannot update password for anon user"
933
+ );
934
+ }
935
+ const currentKey = dhive.PrivateKey.fromLogin(
936
+ username,
937
+ currentPassword,
938
+ "owner"
939
+ );
940
+ return updateKeys({
941
+ currentKey,
942
+ keepCurrent,
943
+ keys: [
944
+ {
945
+ owner: dhive.PrivateKey.fromLogin(username, newPassword, "owner"),
946
+ active: dhive.PrivateKey.fromLogin(username, newPassword, "active"),
947
+ posting: dhive.PrivateKey.fromLogin(username, newPassword, "posting"),
948
+ memo_key: dhive.PrivateKey.fromLogin(username, newPassword, "memo")
949
+ }
950
+ ]
951
+ });
952
+ },
953
+ ...options
954
+ });
955
+ }
956
+ function useAccountRevokePosting(username, options) {
957
+ const queryClient = reactQuery.useQueryClient();
958
+ const { data } = reactQuery.useQuery(getAccountFullQueryOptions(username));
959
+ return reactQuery.useMutation({
960
+ mutationKey: ["accounts", "revoke-posting", data?.name],
961
+ mutationFn: async ({ accountName, type, key }) => {
962
+ if (!data) {
963
+ throw new Error(
964
+ "[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user"
965
+ );
966
+ }
967
+ const posting = R__namespace.pipe(
968
+ {},
969
+ R__namespace.mergeDeep(data.posting)
970
+ );
971
+ posting.account_auths = posting.account_auths.filter(
972
+ ([account]) => account !== accountName
973
+ );
974
+ const operationBody = {
975
+ account: data.name,
976
+ posting,
977
+ memo_key: data.memo_key,
978
+ json_metadata: data.json_metadata
979
+ };
980
+ if (type === "key" && key) {
981
+ return CONFIG.hiveClient.broadcast.updateAccount(operationBody, key);
982
+ } else if (type === "keychain") {
983
+ return keychain_exports.broadcast(
984
+ data.name,
985
+ [["account_update", operationBody]],
986
+ "Active"
987
+ );
988
+ } else {
989
+ const params = {
990
+ callback: `https://ecency.com/@${data.name}/permissions`
991
+ };
992
+ return hs__default.default.sendOperation(
993
+ ["account_update", operationBody],
994
+ params,
995
+ () => {
996
+ }
997
+ );
998
+ }
999
+ },
1000
+ onError: options.onError,
1001
+ onSuccess: (resp, payload, ctx) => {
1002
+ options.onSuccess?.(resp, payload, ctx);
1003
+ queryClient.setQueryData(
1004
+ getAccountFullQueryOptions(username).queryKey,
1005
+ (data2) => ({
1006
+ ...data2,
1007
+ posting: {
1008
+ ...data2?.posting,
1009
+ account_auths: data2?.posting?.account_auths?.filter(
1010
+ ([account]) => account !== payload.accountName
1011
+ ) ?? []
1012
+ }
1013
+ })
1014
+ );
1015
+ }
1016
+ });
1017
+ }
1018
+ function useAccountUpdateRecovery(username, options) {
1019
+ const { data } = reactQuery.useQuery(getAccountFullQueryOptions(username));
1020
+ return reactQuery.useMutation({
1021
+ mutationKey: ["accounts", "recovery", data?.name],
1022
+ mutationFn: async ({ accountName, type, key, email }) => {
1023
+ if (!data) {
1024
+ throw new Error(
1025
+ "[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user"
1026
+ );
1027
+ }
1028
+ const operationBody = {
1029
+ account_to_recover: data.name,
1030
+ new_recovery_account: accountName,
1031
+ extensions: []
1032
+ };
1033
+ if (type === "ecency") {
1034
+ const fetchApi = getBoundFetch();
1035
+ return fetchApi(CONFIG.privateApiHost + "/private-api/recoveries-add", {
1036
+ method: "POST",
1037
+ body: JSON.stringify({
1038
+ code: getAccessToken(data.name),
1039
+ email,
1040
+ publicKeys: [
1041
+ ...data.owner.key_auths,
1042
+ ...data.active.key_auths,
1043
+ ...data.posting.key_auths,
1044
+ data.memo_key
1045
+ ]
1046
+ })
1047
+ });
1048
+ } else if (type === "key" && key) {
1049
+ return CONFIG.hiveClient.broadcast.sendOperations(
1050
+ [["change_recovery_account", operationBody]],
1051
+ key
1052
+ );
1053
+ } else if (type === "keychain") {
1054
+ return keychain_exports.broadcast(
1055
+ data.name,
1056
+ [["change_recovery_account", operationBody]],
1057
+ "Active"
1058
+ );
1059
+ } else {
1060
+ const params = {
1061
+ callback: `https://ecency.com/@${data.name}/permissions`
1062
+ };
1063
+ return hs__default.default.sendOperation(
1064
+ ["change_recovery_account", operationBody],
1065
+ params,
1066
+ () => {
1067
+ }
1068
+ );
1069
+ }
1070
+ },
1071
+ onError: options.onError,
1072
+ onSuccess: options.onSuccess
1073
+ });
1074
+ }
1075
+ function useAccountRevokeKey(username, options) {
1076
+ const { data: accountData } = reactQuery.useQuery(getAccountFullQueryOptions(username));
1077
+ return reactQuery.useMutation({
1078
+ mutationKey: ["accounts", "revoke-key", accountData?.name],
1079
+ mutationFn: async ({ currentKey, revokingKey }) => {
1080
+ if (!accountData) {
1081
+ throw new Error(
1082
+ "[SDK][Update password] \u2013 cannot update keys for anon user"
1083
+ );
1084
+ }
1085
+ const prepareAuth = (keyName) => {
1086
+ const auth = R__namespace.clone(accountData[keyName]);
1087
+ auth.key_auths = auth.key_auths.filter(
1088
+ ([key]) => key !== revokingKey.toString()
1089
+ );
1090
+ return auth;
1091
+ };
1092
+ return CONFIG.hiveClient.broadcast.updateAccount(
1093
+ {
1094
+ account: accountData.name,
1095
+ json_metadata: accountData.json_metadata,
1096
+ owner: prepareAuth("owner"),
1097
+ active: prepareAuth("active"),
1098
+ posting: prepareAuth("posting"),
1099
+ memo_key: accountData.memo_key
1100
+ },
1101
+ currentKey
1102
+ );
1103
+ },
1104
+ ...options
1105
+ });
1106
+ }
1107
+ function useSignOperationByKey(username) {
1108
+ return reactQuery.useMutation({
1109
+ mutationKey: ["operations", "sign", username],
1110
+ mutationFn: ({
1111
+ operation,
1112
+ keyOrSeed
1113
+ }) => {
1114
+ if (!username) {
1115
+ throw new Error("[Operations][Sign] \u2013 cannot sign op with anon user");
1116
+ }
1117
+ let privateKey;
1118
+ if (keyOrSeed.split(" ").length === 12) {
1119
+ privateKey = dhive.PrivateKey.fromLogin(username, keyOrSeed, "active");
1120
+ } else if (dhive.cryptoUtils.isWif(keyOrSeed)) {
1121
+ privateKey = dhive.PrivateKey.fromString(keyOrSeed);
1122
+ } else {
1123
+ privateKey = dhive.PrivateKey.from(keyOrSeed);
1124
+ }
1125
+ return CONFIG.hiveClient.broadcast.sendOperations(
1126
+ [operation],
1127
+ privateKey
1128
+ );
1129
+ }
1130
+ });
1131
+ }
1132
+ function useSignOperationByKeychain(username, keyType = "Active") {
1133
+ return reactQuery.useMutation({
1134
+ mutationKey: ["operations", "sign-keychain", username],
1135
+ mutationFn: ({ operation }) => {
1136
+ if (!username) {
1137
+ throw new Error(
1138
+ "[SDK][Keychain] \u2013\xA0cannot sign operation with anon user"
1139
+ );
1140
+ }
1141
+ return keychain_exports.broadcast(username, [operation], keyType);
1142
+ }
1143
+ });
1144
+ }
1145
+ function useSignOperationByHivesigner(callbackUri = "/") {
1146
+ return reactQuery.useMutation({
1147
+ mutationKey: ["operations", "sign-hivesigner", callbackUri],
1148
+ mutationFn: async ({ operation }) => {
1149
+ return hs__default.default.sendOperation(operation, { callback: callbackUri }, () => {
1150
+ });
1151
+ }
1152
+ });
1153
+ }
1154
+ function getChainPropertiesQueryOptions() {
1155
+ return reactQuery.queryOptions({
1156
+ queryKey: ["operations", "chain-properties"],
1157
+ queryFn: async () => {
1158
+ return await CONFIG.hiveClient.database.getChainProperties();
1159
+ }
1160
+ });
1161
+ }
1162
+ function getTrendingTagsQueryOptions(limit = 20) {
1163
+ return reactQuery.infiniteQueryOptions({
1164
+ queryKey: ["posts", "trending-tags"],
1165
+ queryFn: async ({ pageParam: { afterTag } }) => CONFIG.hiveClient.database.call("get_trending_tags", [afterTag, limit]).then(
1166
+ (tags) => tags.filter((x) => x.name !== "").filter((x) => !x.name.startsWith("hive-")).map((x) => x.name)
1167
+ ),
1168
+ initialPageParam: { afterTag: "" },
1169
+ getNextPageParam: (lastPage) => ({
1170
+ afterTag: lastPage?.[lastPage?.length - 1]
1171
+ }),
1172
+ staleTime: Infinity,
1173
+ refetchOnMount: true
1174
+ });
1175
+ }
1176
+ function getFragmentsQueryOptions(username) {
1177
+ return reactQuery.queryOptions({
1178
+ queryKey: ["posts", "fragments", username],
1179
+ queryFn: async () => {
1180
+ const fetchApi = getBoundFetch();
1181
+ const response = await fetchApi(
1182
+ CONFIG.privateApiHost + "/private-api/fragments",
1183
+ {
1184
+ method: "POST",
1185
+ body: JSON.stringify({
1186
+ code: getAccessToken(username)
1187
+ }),
1188
+ headers: {
1189
+ "Content-Type": "application/json"
1190
+ }
1191
+ }
1192
+ );
1193
+ return response.json();
1194
+ },
1195
+ enabled: !!username
1196
+ });
1197
+ }
1198
+ function getPromotedPostsQuery(type = "feed") {
1199
+ return reactQuery.queryOptions({
1200
+ queryKey: ["posts", "promoted", type],
1201
+ queryFn: async () => {
1202
+ const url = new URL(
1203
+ CONFIG.privateApiHost + "/private-api/promoted-entries"
1204
+ );
1205
+ if (type === "waves") {
1206
+ url.searchParams.append("short_content", "1");
1207
+ }
1208
+ const fetchApi = getBoundFetch();
1209
+ const response = await fetchApi(url.toString(), {
1210
+ method: "GET",
1211
+ headers: {
1212
+ "Content-Type": "application/json"
1213
+ }
1214
+ });
1215
+ const data = await response.json();
1216
+ return data;
1217
+ }
1218
+ });
1219
+ }
1220
+ function useAddFragment(username) {
1221
+ return reactQuery.useMutation({
1222
+ mutationKey: ["posts", "add-fragment", username],
1223
+ mutationFn: async ({ title, body }) => {
1224
+ const fetchApi = getBoundFetch();
1225
+ const response = await fetchApi(
1226
+ CONFIG.privateApiHost + "/private-api/fragments-add",
1227
+ {
1228
+ method: "POST",
1229
+ body: JSON.stringify({
1230
+ code: getAccessToken(username),
1231
+ title,
1232
+ body
1233
+ }),
1234
+ headers: {
1235
+ "Content-Type": "application/json"
1236
+ }
1237
+ }
1238
+ );
1239
+ return response.json();
1240
+ },
1241
+ onSuccess(response) {
1242
+ getQueryClient().setQueryData(
1243
+ getFragmentsQueryOptions(username).queryKey,
1244
+ (data) => [response, ...data ?? []]
1245
+ );
1246
+ }
1247
+ });
1248
+ }
1249
+ function useEditFragment(username, fragmentId) {
1250
+ return reactQuery.useMutation({
1251
+ mutationKey: ["posts", "edit-fragment", username, fragmentId],
1252
+ mutationFn: async ({ title, body }) => {
1253
+ const fetchApi = getBoundFetch();
1254
+ const response = await fetchApi(
1255
+ CONFIG.privateApiHost + "/private-api/fragments-update",
1256
+ {
1257
+ method: "POST",
1258
+ body: JSON.stringify({
1259
+ code: getAccessToken(username),
1260
+ id: fragmentId,
1261
+ title,
1262
+ body
1263
+ }),
1264
+ headers: {
1265
+ "Content-Type": "application/json"
1266
+ }
1267
+ }
1268
+ );
1269
+ return response.json();
1270
+ },
1271
+ onSuccess(response) {
1272
+ getQueryClient().setQueryData(
1273
+ getFragmentsQueryOptions(username).queryKey,
1274
+ (data) => {
1275
+ if (!data) {
1276
+ return [];
1277
+ }
1278
+ const index = data.findIndex(({ id }) => id === fragmentId);
1279
+ if (index >= 0) {
1280
+ data[index] = response;
1281
+ }
1282
+ return [...data];
1283
+ }
1284
+ );
1285
+ }
1286
+ });
1287
+ }
1288
+ function useRemoveFragment(username, fragmentId) {
1289
+ return reactQuery.useMutation({
1290
+ mutationKey: ["posts", "remove-fragment", username],
1291
+ mutationFn: async () => {
1292
+ const fetchApi = getBoundFetch();
1293
+ return fetchApi(CONFIG.privateApiHost + "/private-api/fragments-delete", {
1294
+ method: "POST",
1295
+ body: JSON.stringify({
1296
+ code: getAccessToken(username),
1297
+ id: fragmentId
1298
+ }),
1299
+ headers: {
1300
+ "Content-Type": "application/json"
1301
+ }
1302
+ });
1303
+ },
1304
+ onSuccess() {
1305
+ getQueryClient().setQueryData(
1306
+ getFragmentsQueryOptions(username).queryKey,
1307
+ (data) => [...data ?? []].filter(({ id }) => id !== fragmentId)
1308
+ );
1309
+ }
1310
+ });
1311
+ }
1312
+
1313
+ // src/modules/analytics/mutations/index.ts
1314
+ var mutations_exports = {};
1315
+ __export(mutations_exports, {
1316
+ useRecordActivity: () => useRecordActivity
1317
+ });
1318
+ function useRecordActivity(username, activityType) {
1319
+ return reactQuery.useMutation({
1320
+ mutationKey: ["analytics", activityType],
1321
+ mutationFn: async () => {
1322
+ if (!activityType) {
1323
+ throw new Error("[SDK][Analytics] \u2013 no activity type provided");
1324
+ }
1325
+ const fetchApi = getBoundFetch();
1326
+ await fetchApi(CONFIG.plausibleHost + "/api/event", {
1327
+ method: "POST",
1328
+ headers: {
1329
+ "Content-Type": "application/json"
1330
+ },
1331
+ body: JSON.stringify({
1332
+ name: activityType,
1333
+ url: window.location.href,
1334
+ domain: window.location.host,
1335
+ props: {
1336
+ username
1337
+ }
1338
+ })
1339
+ });
1340
+ }
1341
+ });
1342
+ }
1343
+
1344
+ // src/modules/integrations/3speak/queries/index.ts
1345
+ var queries_exports2 = {};
1346
+ __export(queries_exports2, {
1347
+ getAccountTokenQueryOptions: () => getAccountTokenQueryOptions,
1348
+ getAccountVideosQueryOptions: () => getAccountVideosQueryOptions
1349
+ });
1350
+
1351
+ // src/modules/integrations/hivesigner/queries/index.ts
1352
+ var queries_exports = {};
1353
+ __export(queries_exports, {
1354
+ getDecodeMemoQueryOptions: () => getDecodeMemoQueryOptions
1355
+ });
1356
+ function getDecodeMemoQueryOptions(username, memo) {
1357
+ return reactQuery.queryOptions({
1358
+ queryKey: ["integrations", "hivesigner", "decode-memo", username],
1359
+ queryFn: async () => {
1360
+ const accessToken = getAccessToken(username);
1361
+ if (accessToken) {
1362
+ const hsClient = new hs__default.default.Client({
1363
+ accessToken
1364
+ });
1365
+ return hsClient.decode(memo);
1366
+ }
1367
+ }
1368
+ });
1369
+ }
1370
+
1371
+ // src/modules/integrations/hivesigner/index.ts
1372
+ var HiveSignerIntegration = {
1373
+ queries: queries_exports
1374
+ };
1375
+
1376
+ // src/modules/integrations/3speak/queries/get-account-token-query-options.ts
1377
+ function getAccountTokenQueryOptions(username) {
1378
+ return reactQuery.queryOptions({
1379
+ queryKey: ["integrations", "3speak", "authenticate", username],
1380
+ enabled: !!username,
1381
+ queryFn: async () => {
1382
+ if (!username) {
1383
+ throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");
1384
+ }
1385
+ const fetchApi = getBoundFetch();
1386
+ const response = await fetchApi(
1387
+ `https://studio.3speak.tv/mobile/login?username=${username}&hivesigner=true`,
1388
+ {
1389
+ headers: {
1390
+ "Content-Type": "application/json"
1391
+ }
1392
+ }
1393
+ );
1394
+ const memoQueryOptions = HiveSignerIntegration.queries.getDecodeMemoQueryOptions(
1395
+ username,
1396
+ (await response.json()).memo
1397
+ );
1398
+ await getQueryClient().prefetchQuery(memoQueryOptions);
1399
+ const { memoDecoded } = getQueryClient().getQueryData(
1400
+ memoQueryOptions.queryKey
1401
+ );
1402
+ return memoDecoded.replace("#", "");
1403
+ }
1404
+ });
1405
+ }
1406
+ function getAccountVideosQueryOptions(username) {
1407
+ return reactQuery.queryOptions({
1408
+ queryKey: ["integrations", "3speak", "videos", username],
1409
+ enabled: !!username,
1410
+ queryFn: async () => {
1411
+ await getQueryClient().prefetchQuery(
1412
+ getAccountTokenQueryOptions(username)
1413
+ );
1414
+ const token = getQueryClient().getQueryData(
1415
+ getAccountTokenQueryOptions(username).queryKey
1416
+ );
1417
+ const fetchApi = getBoundFetch();
1418
+ const response = await fetchApi(
1419
+ `https://studio.3speak.tv/mobile/api/my-videos`,
1420
+ {
1421
+ headers: {
1422
+ "Content-Type": "application/json",
1423
+ Authorization: `Bearer ${token}`
1424
+ }
1425
+ }
1426
+ );
1427
+ return await response.json();
1428
+ }
1429
+ });
1430
+ }
1431
+
1432
+ // src/modules/integrations/3speak/index.ts
1433
+ var ThreeSpeakIntegration = {
1434
+ queries: queries_exports2
1435
+ };
1436
+ function getHivePoshLinksQueryOptions(username) {
1437
+ return reactQuery.queryOptions({
1438
+ queryKey: ["integrations", "hiveposh", "links", username],
1439
+ queryFn: async () => {
1440
+ const fetchApi = getBoundFetch();
1441
+ const response = await fetchApi(
1442
+ `https://hiveposh.com/api/v0/linked-accounts/${username}`,
1443
+ {
1444
+ headers: {
1445
+ "Content-Type": "application/json"
1446
+ }
1447
+ }
1448
+ );
1449
+ const data = await response.json();
1450
+ return {
1451
+ twitter: {
1452
+ username: data.twitter_username,
1453
+ profile: data.twitter_profile
1454
+ },
1455
+ reddit: {
1456
+ username: data.reddit_username,
1457
+ profile: data.reddit_profile
1458
+ }
1459
+ };
1460
+ }
1461
+ });
1462
+ }
1463
+ function getStatsQueryOptions({
1464
+ url,
1465
+ dimensions = [],
1466
+ metrics = ["visitors", "pageviews", "visit_duration"],
1467
+ enabled = true
1468
+ }) {
1469
+ return reactQuery.queryOptions({
1470
+ queryKey: ["integrations", "plausible", url, dimensions, metrics],
1471
+ queryFn: async () => {
1472
+ const fetchApi = getBoundFetch();
1473
+ const response = await fetchApi(`https://ecency.com/api/stats`, {
1474
+ method: "POST",
1475
+ body: JSON.stringify({
1476
+ metrics,
1477
+ url: encodeURIComponent(url),
1478
+ dimensions
1479
+ }),
1480
+ headers: {
1481
+ "Content-Type": "application/json"
1482
+ }
1483
+ });
1484
+ return await response.json();
1485
+ },
1486
+ enabled: !!url && enabled
1487
+ });
1488
+ }
1489
+ function getRcStatsQueryOptions() {
1490
+ return reactQuery.queryOptions({
1491
+ queryKey: ["resource-credits", "stats"],
1492
+ queryFn: async () => {
1493
+ const response = await CONFIG.hiveClient.call(
1494
+ "rc_api",
1495
+ "get_rc_stats",
1496
+ {}
1497
+ );
1498
+ return response.rc_stats;
1499
+ }
1500
+ });
1501
+ }
1502
+ function getAccountRcQueryOptions(username) {
1503
+ return reactQuery.queryOptions({
1504
+ queryKey: ["resource-credits", "account", username],
1505
+ queryFn: async () => {
1506
+ const rcClient = new dhive.RCAPI(CONFIG.hiveClient);
1507
+ return rcClient.findRCAccounts([username]);
1508
+ },
1509
+ enabled: !!username
1510
+ });
1511
+ }
1512
+ function getGameStatusCheckQueryOptions(username, gameType) {
1513
+ return reactQuery.queryOptions({
1514
+ queryKey: ["games", "status-check", gameType, username],
1515
+ enabled: !!username,
1516
+ queryFn: async () => {
1517
+ if (!username) {
1518
+ throw new Error("[SDK][Games] \u2013 anon user in status check");
1519
+ }
1520
+ const fetchApi = getBoundFetch();
1521
+ const response = await fetchApi(
1522
+ CONFIG.privateApiHost + "/private-api/get-game",
1523
+ {
1524
+ method: "POST",
1525
+ body: JSON.stringify({
1526
+ game_type: gameType,
1527
+ code: getAccessToken(username)
1528
+ }),
1529
+ headers: {
1530
+ "Content-Type": "application/json"
1531
+ }
1532
+ }
1533
+ );
1534
+ return await response.json();
1535
+ }
1536
+ });
1537
+ }
1538
+ function useGameClaim(username, gameType, key) {
1539
+ const { mutateAsync: recordActivity } = useRecordActivity(
1540
+ username,
1541
+ "spin-rolled"
1542
+ );
1543
+ return reactQuery.useMutation({
1544
+ mutationKey: ["games", "post", gameType, username],
1545
+ mutationFn: async () => {
1546
+ if (!username) {
1547
+ throw new Error("[SDK][Games] \u2013 anon user in game post");
1548
+ }
1549
+ const fetchApi = getBoundFetch();
1550
+ const response = await fetchApi(
1551
+ CONFIG.privateApiHost + "/private-api/post-game",
1552
+ {
1553
+ method: "POST",
1554
+ body: JSON.stringify({
1555
+ game_type: gameType,
1556
+ code: getAccessToken(username),
1557
+ key
1558
+ }),
1559
+ headers: {
1560
+ "Content-Type": "application/json"
1561
+ }
1562
+ }
1563
+ );
1564
+ return await response.json();
1565
+ },
1566
+ onSuccess() {
1567
+ recordActivity();
1568
+ }
1569
+ });
1570
+ }
1571
+ function getCommunitiesQueryOptions(sort, query, limit = 100, observer = void 0, enabled = true) {
1572
+ return reactQuery.queryOptions({
1573
+ queryKey: ["communities", "list", sort, query, limit],
1574
+ enabled,
1575
+ queryFn: async () => {
1576
+ const response = await CONFIG.hiveClient.call(
1577
+ "bridge",
1578
+ "list_communities",
1579
+ {
1580
+ last: "",
1581
+ limit,
1582
+ sort: sort === "hot" ? "rank" : sort,
1583
+ query: query ? query : null,
1584
+ observer
1585
+ }
1586
+ );
1587
+ return response ? sort === "hot" ? response.sort(() => Math.random() - 0.5) : response : [];
1588
+ }
1589
+ });
1590
+ }
1591
+ function getCommunityContextQueryOptions(username, communityName) {
1592
+ return reactQuery.queryOptions({
1593
+ queryKey: ["community", "context", username, communityName],
1594
+ enabled: !!username && !!communityName,
1595
+ queryFn: async () => {
1596
+ const response = await CONFIG.hiveClient.call(
1597
+ "bridge",
1598
+ "get_community_context",
1599
+ {
1600
+ account: username,
1601
+ name: communityName
1602
+ }
1603
+ );
1604
+ return {
1605
+ role: response?.role ?? "guest",
1606
+ subscribed: response?.subscribed ?? false
1607
+ };
1608
+ }
1609
+ });
1610
+ }
1611
+
1612
+ // src/modules/communities/types/community.ts
1613
+ var ROLES = /* @__PURE__ */ ((ROLES2) => {
1614
+ ROLES2["OWNER"] = "owner";
1615
+ ROLES2["ADMIN"] = "admin";
1616
+ ROLES2["MOD"] = "mod";
1617
+ ROLES2["MEMBER"] = "member";
1618
+ ROLES2["GUEST"] = "guest";
1619
+ ROLES2["MUTED"] = "muted";
1620
+ return ROLES2;
1621
+ })(ROLES || {});
1622
+ var roleMap = {
1623
+ ["owner" /* OWNER */]: [
1624
+ "admin" /* ADMIN */,
1625
+ "mod" /* MOD */,
1626
+ "member" /* MEMBER */,
1627
+ "guest" /* GUEST */,
1628
+ "muted" /* MUTED */
1629
+ ],
1630
+ ["admin" /* ADMIN */]: ["mod" /* MOD */, "member" /* MEMBER */, "guest" /* GUEST */, "muted" /* MUTED */],
1631
+ ["mod" /* MOD */]: ["member" /* MEMBER */, "guest" /* GUEST */, "muted" /* MUTED */]
1632
+ };
1633
+
1634
+ // src/modules/communities/utils/index.ts
1635
+ function getCommunityType(name, type_id) {
1636
+ if (name.startsWith("hive-3") || type_id === 3) return "Council";
1637
+ if (name.startsWith("hive-2") || type_id === 2) return "Journal";
1638
+ return "Topic";
1639
+ }
1640
+ function getCommunityPermissions({
1641
+ communityType,
1642
+ userRole,
1643
+ subscribed
1644
+ }) {
1645
+ const canPost = (() => {
1646
+ if (userRole === "muted" /* MUTED */) return false;
1647
+ if (communityType === "Topic") return true;
1648
+ return ["owner" /* OWNER */, "admin" /* ADMIN */, "mod" /* MOD */, "member" /* MEMBER */].includes(
1649
+ userRole
1650
+ );
1651
+ })();
1652
+ const canComment = (() => {
1653
+ if (userRole === "muted" /* MUTED */) return false;
1654
+ switch (communityType) {
1655
+ case "Topic":
1656
+ return true;
1657
+ case "Journal":
1658
+ return userRole !== "guest" /* GUEST */ || subscribed;
1659
+ case "Council":
1660
+ return canPost;
1661
+ }
1662
+ })();
1663
+ const isModerator = ["owner" /* OWNER */, "admin" /* ADMIN */, "mod" /* MOD */].includes(userRole);
1664
+ return {
1665
+ canPost,
1666
+ canComment,
1667
+ isModerator
1668
+ };
1669
+ }
1670
+
1671
+ exports.CONFIG = CONFIG;
1672
+ exports.EcencyAnalytics = mutations_exports;
1673
+ exports.HiveSignerIntegration = HiveSignerIntegration;
1674
+ exports.Keychain = keychain_exports;
1675
+ exports.NaiMap = NaiMap;
1676
+ exports.ROLES = ROLES;
1677
+ exports.Symbol = Symbol2;
1678
+ exports.ThreeSpeakIntegration = ThreeSpeakIntegration;
1679
+ exports.broadcastJson = broadcastJson;
1680
+ exports.checkUsernameWalletsPendingQueryOptions = checkUsernameWalletsPendingQueryOptions;
1681
+ exports.decodeObj = decodeObj;
1682
+ exports.dedupeAndSortKeyAuths = dedupeAndSortKeyAuths;
1683
+ exports.encodeObj = encodeObj;
1684
+ exports.getAccessToken = getAccessToken;
1685
+ exports.getAccountFullQueryOptions = getAccountFullQueryOptions;
1686
+ exports.getAccountPendingRecoveryQueryOptions = getAccountPendingRecoveryQueryOptions;
1687
+ exports.getAccountRcQueryOptions = getAccountRcQueryOptions;
1688
+ exports.getAccountRecoveriesQueryOptions = getAccountRecoveriesQueryOptions;
1689
+ exports.getAccountSubscriptionsQueryOptions = getAccountSubscriptionsQueryOptions;
1690
+ exports.getActiveAccountBookmarksQueryOptions = getActiveAccountBookmarksQueryOptions;
1691
+ exports.getActiveAccountFavouritesQueryOptions = getActiveAccountFavouritesQueryOptions;
1692
+ exports.getBoundFetch = getBoundFetch;
1693
+ exports.getChainPropertiesQueryOptions = getChainPropertiesQueryOptions;
1694
+ exports.getCommunitiesQueryOptions = getCommunitiesQueryOptions;
1695
+ exports.getCommunityContextQueryOptions = getCommunityContextQueryOptions;
1696
+ exports.getCommunityPermissions = getCommunityPermissions;
1697
+ exports.getCommunityType = getCommunityType;
1698
+ exports.getDynamicPropsQueryOptions = getDynamicPropsQueryOptions;
1699
+ exports.getFragmentsQueryOptions = getFragmentsQueryOptions;
1700
+ exports.getGameStatusCheckQueryOptions = getGameStatusCheckQueryOptions;
1701
+ exports.getHivePoshLinksQueryOptions = getHivePoshLinksQueryOptions;
1702
+ exports.getLoginType = getLoginType;
1703
+ exports.getPostingKey = getPostingKey;
1704
+ exports.getPromotedPostsQuery = getPromotedPostsQuery;
1705
+ exports.getQueryClient = getQueryClient;
1706
+ exports.getRcStatsQueryOptions = getRcStatsQueryOptions;
1707
+ exports.getRefreshToken = getRefreshToken;
1708
+ exports.getRelationshipBetweenAccountsQueryOptions = getRelationshipBetweenAccountsQueryOptions;
1709
+ exports.getSearchAccountsByUsernameQueryOptions = getSearchAccountsByUsernameQueryOptions;
1710
+ exports.getStatsQueryOptions = getStatsQueryOptions;
1711
+ exports.getTrendingTagsQueryOptions = getTrendingTagsQueryOptions;
1712
+ exports.getUser = getUser;
1713
+ exports.makeQueryClient = makeQueryClient;
1714
+ exports.parseAsset = parseAsset;
1715
+ exports.roleMap = roleMap;
1716
+ exports.useAccountFavouriteAdd = useAccountFavouriteAdd;
1717
+ exports.useAccountFavouriteDelete = useAccountFavouriteDelete;
1718
+ exports.useAccountRelationsUpdate = useAccountRelationsUpdate;
1719
+ exports.useAccountRevokeKey = useAccountRevokeKey;
1720
+ exports.useAccountRevokePosting = useAccountRevokePosting;
1721
+ exports.useAccountUpdate = useAccountUpdate;
1722
+ exports.useAccountUpdateKeyAuths = useAccountUpdateKeyAuths;
1723
+ exports.useAccountUpdatePassword = useAccountUpdatePassword;
1724
+ exports.useAccountUpdateRecovery = useAccountUpdateRecovery;
1725
+ exports.useAddFragment = useAddFragment;
1726
+ exports.useBookmarkAdd = useBookmarkAdd;
1727
+ exports.useBookmarkDelete = useBookmarkDelete;
1728
+ exports.useBroadcastMutation = useBroadcastMutation;
1729
+ exports.useEditFragment = useEditFragment;
1730
+ exports.useGameClaim = useGameClaim;
1731
+ exports.useRemoveFragment = useRemoveFragment;
1732
+ exports.useSignOperationByHivesigner = useSignOperationByHivesigner;
1733
+ exports.useSignOperationByKey = useSignOperationByKey;
1734
+ exports.useSignOperationByKeychain = useSignOperationByKeychain;
1735
+ //# sourceMappingURL=index.cjs.map
1736
+ //# sourceMappingURL=index.cjs.map