@ecency/sdk 1.2.0 → 1.3.0

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,1730 @@
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
+ const profile = JSON.parse(response[0].posting_json_metadata).profile;
431
+ let follow_stats;
432
+ try {
433
+ follow_stats = await CONFIG.hiveClient.database.call(
434
+ "get_follow_count",
435
+ [username]
436
+ );
437
+ } catch (e) {
438
+ }
439
+ const reputation = await CONFIG.hiveClient.call(
440
+ "condenser_api",
441
+ "get_account_reputations",
442
+ [username, 1]
443
+ );
444
+ return {
445
+ name: response[0].name,
446
+ owner: response[0].owner,
447
+ active: response[0].active,
448
+ posting: response[0].posting,
449
+ memo_key: response[0].memo_key,
450
+ post_count: response[0].post_count,
451
+ created: response[0].created,
452
+ posting_json_metadata: response[0].posting_json_metadata,
453
+ last_vote_time: response[0].last_vote_time,
454
+ last_post: response[0].last_post,
455
+ json_metadata: response[0].json_metadata,
456
+ reward_hive_balance: response[0].reward_hive_balance,
457
+ reward_hbd_balance: response[0].reward_hbd_balance,
458
+ reward_vesting_hive: response[0].reward_vesting_hive,
459
+ reward_vesting_balance: response[0].reward_vesting_balance,
460
+ balance: response[0].balance,
461
+ hbd_balance: response[0].hbd_balance,
462
+ savings_balance: response[0].savings_balance,
463
+ savings_hbd_balance: response[0].savings_hbd_balance,
464
+ savings_hbd_last_interest_payment: response[0].savings_hbd_last_interest_payment,
465
+ savings_hbd_seconds_last_update: response[0].savings_hbd_seconds_last_update,
466
+ savings_hbd_seconds: response[0].savings_hbd_seconds,
467
+ next_vesting_withdrawal: response[0].next_vesting_withdrawal,
468
+ pending_claimed_accounts: response[0].pending_claimed_accounts,
469
+ vesting_shares: response[0].vesting_shares,
470
+ delegated_vesting_shares: response[0].delegated_vesting_shares,
471
+ received_vesting_shares: response[0].received_vesting_shares,
472
+ vesting_withdraw_rate: response[0].vesting_withdraw_rate,
473
+ to_withdraw: response[0].to_withdraw,
474
+ withdrawn: response[0].withdrawn,
475
+ witness_votes: response[0].witness_votes,
476
+ proxy: response[0].proxy,
477
+ recovery_account: response[0].recovery_account,
478
+ proxied_vsf_votes: response[0].proxied_vsf_votes,
479
+ voting_manabar: response[0].voting_manabar,
480
+ voting_power: response[0].voting_power,
481
+ downvote_manabar: response[0].downvote_manabar,
482
+ follow_stats,
483
+ reputation: reputation[0].reputation,
484
+ profile: {
485
+ ...profile,
486
+ reputation: reputation[0].reputation
487
+ }
488
+ };
489
+ },
490
+ enabled: !!username,
491
+ staleTime: 6e4
492
+ });
493
+ }
494
+ function getSearchAccountsByUsernameQueryOptions(query, limit = 5, excludeList = []) {
495
+ return reactQuery.queryOptions({
496
+ queryKey: ["accounts", "search", query, excludeList],
497
+ enabled: !!query,
498
+ queryFn: async () => {
499
+ const response = await CONFIG.hiveClient.database.call(
500
+ "lookup_accounts",
501
+ [query, limit]
502
+ );
503
+ return response.filter(
504
+ (item) => excludeList.length > 0 ? !excludeList.includes(item) : true
505
+ );
506
+ }
507
+ });
508
+ }
509
+ function checkUsernameWalletsPendingQueryOptions(username) {
510
+ return reactQuery.queryOptions({
511
+ queryKey: ["accounts", "check-wallet-pending", username],
512
+ queryFn: async () => {
513
+ const fetchApi = getBoundFetch();
514
+ const response = await fetchApi(
515
+ CONFIG.privateApiHost + "/private-api/wallets-chkuser",
516
+ {
517
+ method: "POST",
518
+ headers: {
519
+ "Content-Type": "application/json"
520
+ },
521
+ body: JSON.stringify({
522
+ username
523
+ })
524
+ }
525
+ );
526
+ return await response.json();
527
+ },
528
+ enabled: !!username,
529
+ refetchOnMount: true
530
+ });
531
+ }
532
+ function getRelationshipBetweenAccountsQueryOptions(reference, target) {
533
+ return reactQuery.queryOptions({
534
+ queryKey: ["accounts", "relations", reference, target],
535
+ enabled: !!reference && !!target,
536
+ refetchOnMount: false,
537
+ refetchInterval: 36e5,
538
+ queryFn: async () => {
539
+ return await CONFIG.hiveClient.call(
540
+ "bridge",
541
+ "get_relationship_between_accounts",
542
+ [reference, target]
543
+ );
544
+ }
545
+ });
546
+ }
547
+ function getAccountSubscriptionsQueryOptions(username) {
548
+ return reactQuery.queryOptions({
549
+ queryKey: ["accounts", "subscriptions", username],
550
+ enabled: !!username,
551
+ queryFn: async () => {
552
+ const response = await CONFIG.hiveClient.call(
553
+ "bridge",
554
+ "list_all_subscriptions",
555
+ {
556
+ account: username
557
+ }
558
+ );
559
+ return response ?? [];
560
+ }
561
+ });
562
+ }
563
+ function getActiveAccountBookmarksQueryOptions(activeUsername) {
564
+ return reactQuery.queryOptions({
565
+ queryKey: ["accounts", "bookmarks", activeUsername],
566
+ enabled: !!activeUsername,
567
+ queryFn: async () => {
568
+ if (!activeUsername) {
569
+ throw new Error("[SDK][Accounts][Bookmarks] \u2013 no active user");
570
+ }
571
+ const fetchApi = getBoundFetch();
572
+ const response = await fetchApi(
573
+ CONFIG.privateApiHost + "/private-api/bookmarks",
574
+ {
575
+ method: "POST",
576
+ headers: {
577
+ "Content-Type": "application/json"
578
+ },
579
+ body: JSON.stringify({ code: getAccessToken(activeUsername) })
580
+ }
581
+ );
582
+ return await response.json();
583
+ }
584
+ });
585
+ }
586
+ function getActiveAccountFavouritesQueryOptions(activeUsername) {
587
+ return reactQuery.queryOptions({
588
+ queryKey: ["accounts", "favourites", activeUsername],
589
+ enabled: !!activeUsername,
590
+ queryFn: async () => {
591
+ if (!activeUsername) {
592
+ throw new Error("[SDK][Accounts][Favourites] \u2013 no active user");
593
+ }
594
+ const fetchApi = getBoundFetch();
595
+ const response = await fetchApi(
596
+ CONFIG.privateApiHost + "/private-api/favorites",
597
+ {
598
+ method: "POST",
599
+ headers: {
600
+ "Content-Type": "application/json"
601
+ },
602
+ body: JSON.stringify({ code: getAccessToken(activeUsername) })
603
+ }
604
+ );
605
+ return await response.json();
606
+ }
607
+ });
608
+ }
609
+ function getAccountRecoveriesQueryOptions(username) {
610
+ return reactQuery.queryOptions({
611
+ enabled: !!username,
612
+ queryKey: ["accounts", "recoveries", username],
613
+ queryFn: async () => {
614
+ const fetchApi = getBoundFetch();
615
+ const response = await fetchApi(
616
+ CONFIG.privateApiHost + "/private-api/recoveries",
617
+ {
618
+ method: "POST",
619
+ headers: {
620
+ "Content-Type": "application/json"
621
+ },
622
+ body: JSON.stringify({ code: getAccessToken(username) })
623
+ }
624
+ );
625
+ return response.json();
626
+ }
627
+ });
628
+ }
629
+ function getAccountPendingRecoveryQueryOptions(username) {
630
+ return reactQuery.queryOptions({
631
+ enabled: !!username,
632
+ queryKey: ["accounts", "recoveries", username, "pending-request"],
633
+ queryFn: () => CONFIG.hiveClient.call(
634
+ "database_api",
635
+ "find_change_recovery_account_requests",
636
+ { accounts: [username] }
637
+ )
638
+ });
639
+ }
640
+ function sanitizeTokens(tokens) {
641
+ return tokens?.map(({ meta, ...rest }) => {
642
+ if (!meta || typeof meta !== "object") {
643
+ return { ...rest, meta };
644
+ }
645
+ const { privateKey, username, ...safeMeta } = meta;
646
+ return { ...rest, meta: safeMeta };
647
+ });
648
+ }
649
+ function getBuiltProfile({
650
+ profile,
651
+ tokens,
652
+ data
653
+ }) {
654
+ const metadata = R__namespace.pipe(
655
+ JSON.parse(data?.posting_json_metadata || "{}").profile,
656
+ R__namespace.mergeDeep(profile ?? {})
657
+ );
658
+ if (tokens && tokens.length > 0) {
659
+ metadata.tokens = tokens;
660
+ }
661
+ metadata.tokens = sanitizeTokens(metadata.tokens);
662
+ return metadata;
663
+ }
664
+ function useAccountUpdate(username) {
665
+ const queryClient = reactQuery.useQueryClient();
666
+ const { data } = reactQuery.useQuery(getAccountFullQueryOptions(username));
667
+ return useBroadcastMutation(
668
+ ["accounts", "update"],
669
+ username,
670
+ (payload) => {
671
+ if (!data) {
672
+ throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");
673
+ }
674
+ return [
675
+ [
676
+ "account_update2",
677
+ {
678
+ account: username,
679
+ json_metadata: "",
680
+ extensions: [],
681
+ posting_json_metadata: JSON.stringify({
682
+ profile: getBuiltProfile({ ...payload, data })
683
+ })
684
+ }
685
+ ]
686
+ ];
687
+ },
688
+ (_, variables) => queryClient.setQueryData(
689
+ getAccountFullQueryOptions(username).queryKey,
690
+ (data2) => {
691
+ if (!data2) {
692
+ return data2;
693
+ }
694
+ const obj = R__namespace.clone(data2);
695
+ obj.profile = getBuiltProfile({ ...variables, data: data2 });
696
+ return obj;
697
+ }
698
+ )
699
+ );
700
+ }
701
+ function useAccountRelationsUpdate(reference, target, onSuccess, onError) {
702
+ return reactQuery.useMutation({
703
+ mutationKey: ["accounts", "relation", "update", reference, target],
704
+ mutationFn: async (kind) => {
705
+ const relationsQuery = getRelationshipBetweenAccountsQueryOptions(
706
+ reference,
707
+ target
708
+ );
709
+ await getQueryClient().prefetchQuery(relationsQuery);
710
+ const actualRelation = getQueryClient().getQueryData(
711
+ relationsQuery.queryKey
712
+ );
713
+ await broadcastJson(reference, "follow", [
714
+ "follow",
715
+ {
716
+ follower: reference,
717
+ following: target,
718
+ what: [
719
+ ...kind === "toggle-ignore" && !actualRelation?.ignores ? ["ignore"] : [],
720
+ ...kind === "toggle-follow" && !actualRelation?.follows ? ["blog"] : []
721
+ ]
722
+ }
723
+ ]);
724
+ return {
725
+ ...actualRelation,
726
+ ignores: kind === "toggle-ignore" ? !actualRelation?.ignores : actualRelation?.ignores,
727
+ follows: kind === "toggle-follow" ? !actualRelation?.follows : actualRelation?.follows
728
+ };
729
+ },
730
+ onError,
731
+ onSuccess(data) {
732
+ onSuccess(data);
733
+ getQueryClient().setQueryData(
734
+ ["accounts", "relations", reference, target],
735
+ data
736
+ );
737
+ }
738
+ });
739
+ }
740
+ function useBookmarkAdd(username, onSuccess, onError) {
741
+ return reactQuery.useMutation({
742
+ mutationKey: ["accounts", "bookmarks", "add", username],
743
+ mutationFn: async ({ author, permlink }) => {
744
+ if (!username) {
745
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
746
+ }
747
+ const fetchApi = getBoundFetch();
748
+ const response = await fetchApi(
749
+ CONFIG.privateApiHost + "/private-api/bookmarks-add",
750
+ {
751
+ method: "POST",
752
+ headers: {
753
+ "Content-Type": "application/json"
754
+ },
755
+ body: JSON.stringify({
756
+ author,
757
+ permlink,
758
+ code: getAccessToken(username)
759
+ })
760
+ }
761
+ );
762
+ return response.json();
763
+ },
764
+ onSuccess: () => {
765
+ onSuccess();
766
+ getQueryClient().invalidateQueries({
767
+ queryKey: ["accounts", "bookmarks", username]
768
+ });
769
+ },
770
+ onError
771
+ });
772
+ }
773
+ function useBookmarkDelete(username, onSuccess, onError) {
774
+ return reactQuery.useMutation({
775
+ mutationKey: ["accounts", "bookmarks", "delete", username],
776
+ mutationFn: async (bookmarkId) => {
777
+ if (!username) {
778
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
779
+ }
780
+ const fetchApi = getBoundFetch();
781
+ const response = await fetchApi(
782
+ CONFIG.privateApiHost + "/private-api/bookmarks-delete",
783
+ {
784
+ method: "POST",
785
+ headers: {
786
+ "Content-Type": "application/json"
787
+ },
788
+ body: JSON.stringify({
789
+ id: bookmarkId,
790
+ code: getAccessToken(username)
791
+ })
792
+ }
793
+ );
794
+ return response.json();
795
+ },
796
+ onSuccess: () => {
797
+ onSuccess();
798
+ getQueryClient().invalidateQueries({
799
+ queryKey: ["accounts", "bookmarks", username]
800
+ });
801
+ },
802
+ onError
803
+ });
804
+ }
805
+ function useAccountFavouriteAdd(username, onSuccess, onError) {
806
+ return reactQuery.useMutation({
807
+ mutationKey: ["accounts", "favourites", "add", username],
808
+ mutationFn: async (account) => {
809
+ if (!username) {
810
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
811
+ }
812
+ const fetchApi = getBoundFetch();
813
+ const response = await fetchApi(
814
+ CONFIG.privateApiHost + "/private-api/favorites-add",
815
+ {
816
+ method: "POST",
817
+ headers: {
818
+ "Content-Type": "application/json"
819
+ },
820
+ body: JSON.stringify({
821
+ account,
822
+ code: getAccessToken(username)
823
+ })
824
+ }
825
+ );
826
+ return response.json();
827
+ },
828
+ onSuccess: () => {
829
+ onSuccess();
830
+ getQueryClient().invalidateQueries({
831
+ queryKey: ["accounts", "favourites", username]
832
+ });
833
+ },
834
+ onError
835
+ });
836
+ }
837
+ function useAccountFavouriteDelete(username, onSuccess, onError) {
838
+ return reactQuery.useMutation({
839
+ mutationKey: ["accounts", "favourites", "add", username],
840
+ mutationFn: async (account) => {
841
+ if (!username) {
842
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
843
+ }
844
+ const fetchApi = getBoundFetch();
845
+ const response = await fetchApi(
846
+ CONFIG.privateApiHost + "/private-api/favorites-delete",
847
+ {
848
+ method: "POST",
849
+ headers: {
850
+ "Content-Type": "application/json"
851
+ },
852
+ body: JSON.stringify({
853
+ account,
854
+ code: getAccessToken(username)
855
+ })
856
+ }
857
+ );
858
+ return response.json();
859
+ },
860
+ onSuccess: () => {
861
+ onSuccess();
862
+ getQueryClient().invalidateQueries({
863
+ queryKey: ["accounts", "favourites", username]
864
+ });
865
+ },
866
+ onError
867
+ });
868
+ }
869
+ function dedupeAndSortKeyAuths(existing, additions) {
870
+ const merged = /* @__PURE__ */ new Map();
871
+ existing.forEach(([key, weight]) => {
872
+ merged.set(key.toString(), weight);
873
+ });
874
+ additions.forEach(([key, weight]) => {
875
+ merged.set(key.toString(), weight);
876
+ });
877
+ return Array.from(merged.entries()).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)).map(([key, weight]) => [key, weight]);
878
+ }
879
+ function useAccountUpdateKeyAuths(username, options) {
880
+ const { data: accountData } = reactQuery.useQuery(getAccountFullQueryOptions(username));
881
+ return reactQuery.useMutation({
882
+ mutationKey: ["accounts", "keys-update", username],
883
+ mutationFn: async ({ keys, keepCurrent = false, currentKey }) => {
884
+ if (!accountData) {
885
+ throw new Error(
886
+ "[SDK][Update password] \u2013 cannot update keys for anon user"
887
+ );
888
+ }
889
+ const prepareAuth = (keyName) => {
890
+ const auth = R__namespace.clone(accountData[keyName]);
891
+ auth.key_auths = dedupeAndSortKeyAuths(
892
+ keepCurrent ? auth.key_auths : [],
893
+ keys.map(
894
+ (values, i) => [values[keyName].createPublic().toString(), i + 1]
895
+ )
896
+ );
897
+ return auth;
898
+ };
899
+ return CONFIG.hiveClient.broadcast.updateAccount(
900
+ {
901
+ account: username,
902
+ json_metadata: accountData.json_metadata,
903
+ owner: prepareAuth("owner"),
904
+ active: prepareAuth("active"),
905
+ posting: prepareAuth("posting"),
906
+ memo_key: keepCurrent ? accountData.memo_key : keys[0].memo_key.createPublic().toString()
907
+ },
908
+ currentKey
909
+ );
910
+ },
911
+ ...options
912
+ });
913
+ }
914
+ function useAccountUpdatePassword(username, options) {
915
+ const { data: accountData } = reactQuery.useQuery(getAccountFullQueryOptions(username));
916
+ const { mutateAsync: updateKeys } = useAccountUpdateKeyAuths(username);
917
+ return reactQuery.useMutation({
918
+ mutationKey: ["accounts", "password-update", username],
919
+ mutationFn: async ({
920
+ newPassword,
921
+ currentPassword,
922
+ keepCurrent
923
+ }) => {
924
+ if (!accountData) {
925
+ throw new Error(
926
+ "[SDK][Update password] \u2013 cannot update password for anon user"
927
+ );
928
+ }
929
+ const currentKey = dhive.PrivateKey.fromLogin(
930
+ username,
931
+ currentPassword,
932
+ "owner"
933
+ );
934
+ return updateKeys({
935
+ currentKey,
936
+ keepCurrent,
937
+ keys: [
938
+ {
939
+ owner: dhive.PrivateKey.fromLogin(username, newPassword, "owner"),
940
+ active: dhive.PrivateKey.fromLogin(username, newPassword, "active"),
941
+ posting: dhive.PrivateKey.fromLogin(username, newPassword, "posting"),
942
+ memo_key: dhive.PrivateKey.fromLogin(username, newPassword, "memo")
943
+ }
944
+ ]
945
+ });
946
+ },
947
+ ...options
948
+ });
949
+ }
950
+ function useAccountRevokePosting(username, options) {
951
+ const queryClient = reactQuery.useQueryClient();
952
+ const { data } = reactQuery.useQuery(getAccountFullQueryOptions(username));
953
+ return reactQuery.useMutation({
954
+ mutationKey: ["accounts", "revoke-posting", data?.name],
955
+ mutationFn: async ({ accountName, type, key }) => {
956
+ if (!data) {
957
+ throw new Error(
958
+ "[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user"
959
+ );
960
+ }
961
+ const posting = R__namespace.pipe(
962
+ {},
963
+ R__namespace.mergeDeep(data.posting)
964
+ );
965
+ posting.account_auths = posting.account_auths.filter(
966
+ ([account]) => account !== accountName
967
+ );
968
+ const operationBody = {
969
+ account: data.name,
970
+ posting,
971
+ memo_key: data.memo_key,
972
+ json_metadata: data.json_metadata
973
+ };
974
+ if (type === "key" && key) {
975
+ return CONFIG.hiveClient.broadcast.updateAccount(operationBody, key);
976
+ } else if (type === "keychain") {
977
+ return keychain_exports.broadcast(
978
+ data.name,
979
+ [["account_update", operationBody]],
980
+ "Active"
981
+ );
982
+ } else {
983
+ const params = {
984
+ callback: `https://ecency.com/@${data.name}/permissions`
985
+ };
986
+ return hs__default.default.sendOperation(
987
+ ["account_update", operationBody],
988
+ params,
989
+ () => {
990
+ }
991
+ );
992
+ }
993
+ },
994
+ onError: options.onError,
995
+ onSuccess: (resp, payload, ctx) => {
996
+ options.onSuccess?.(resp, payload, ctx);
997
+ queryClient.setQueryData(
998
+ getAccountFullQueryOptions(username).queryKey,
999
+ (data2) => ({
1000
+ ...data2,
1001
+ posting: {
1002
+ ...data2?.posting,
1003
+ account_auths: data2?.posting?.account_auths?.filter(
1004
+ ([account]) => account !== payload.accountName
1005
+ ) ?? []
1006
+ }
1007
+ })
1008
+ );
1009
+ }
1010
+ });
1011
+ }
1012
+ function useAccountUpdateRecovery(username, options) {
1013
+ const { data } = reactQuery.useQuery(getAccountFullQueryOptions(username));
1014
+ return reactQuery.useMutation({
1015
+ mutationKey: ["accounts", "recovery", data?.name],
1016
+ mutationFn: async ({ accountName, type, key, email }) => {
1017
+ if (!data) {
1018
+ throw new Error(
1019
+ "[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user"
1020
+ );
1021
+ }
1022
+ const operationBody = {
1023
+ account_to_recover: data.name,
1024
+ new_recovery_account: accountName,
1025
+ extensions: []
1026
+ };
1027
+ if (type === "ecency") {
1028
+ const fetchApi = getBoundFetch();
1029
+ return fetchApi(CONFIG.privateApiHost + "/private-api/recoveries-add", {
1030
+ method: "POST",
1031
+ body: JSON.stringify({
1032
+ code: getAccessToken(data.name),
1033
+ email,
1034
+ publicKeys: [
1035
+ ...data.owner.key_auths,
1036
+ ...data.active.key_auths,
1037
+ ...data.posting.key_auths,
1038
+ data.memo_key
1039
+ ]
1040
+ })
1041
+ });
1042
+ } else if (type === "key" && key) {
1043
+ return CONFIG.hiveClient.broadcast.sendOperations(
1044
+ [["change_recovery_account", operationBody]],
1045
+ key
1046
+ );
1047
+ } else if (type === "keychain") {
1048
+ return keychain_exports.broadcast(
1049
+ data.name,
1050
+ [["change_recovery_account", operationBody]],
1051
+ "Active"
1052
+ );
1053
+ } else {
1054
+ const params = {
1055
+ callback: `https://ecency.com/@${data.name}/permissions`
1056
+ };
1057
+ return hs__default.default.sendOperation(
1058
+ ["change_recovery_account", operationBody],
1059
+ params,
1060
+ () => {
1061
+ }
1062
+ );
1063
+ }
1064
+ },
1065
+ onError: options.onError,
1066
+ onSuccess: options.onSuccess
1067
+ });
1068
+ }
1069
+ function useAccountRevokeKey(username, options) {
1070
+ const { data: accountData } = reactQuery.useQuery(getAccountFullQueryOptions(username));
1071
+ return reactQuery.useMutation({
1072
+ mutationKey: ["accounts", "revoke-key", accountData?.name],
1073
+ mutationFn: async ({ currentKey, revokingKey }) => {
1074
+ if (!accountData) {
1075
+ throw new Error(
1076
+ "[SDK][Update password] \u2013 cannot update keys for anon user"
1077
+ );
1078
+ }
1079
+ const prepareAuth = (keyName) => {
1080
+ const auth = R__namespace.clone(accountData[keyName]);
1081
+ auth.key_auths = auth.key_auths.filter(
1082
+ ([key]) => key !== revokingKey.toString()
1083
+ );
1084
+ return auth;
1085
+ };
1086
+ return CONFIG.hiveClient.broadcast.updateAccount(
1087
+ {
1088
+ account: accountData.name,
1089
+ json_metadata: accountData.json_metadata,
1090
+ owner: prepareAuth("owner"),
1091
+ active: prepareAuth("active"),
1092
+ posting: prepareAuth("posting"),
1093
+ memo_key: accountData.memo_key
1094
+ },
1095
+ currentKey
1096
+ );
1097
+ },
1098
+ ...options
1099
+ });
1100
+ }
1101
+ function useSignOperationByKey(username) {
1102
+ return reactQuery.useMutation({
1103
+ mutationKey: ["operations", "sign", username],
1104
+ mutationFn: ({
1105
+ operation,
1106
+ keyOrSeed
1107
+ }) => {
1108
+ if (!username) {
1109
+ throw new Error("[Operations][Sign] \u2013 cannot sign op with anon user");
1110
+ }
1111
+ let privateKey;
1112
+ if (keyOrSeed.split(" ").length === 12) {
1113
+ privateKey = dhive.PrivateKey.fromLogin(username, keyOrSeed, "active");
1114
+ } else if (dhive.cryptoUtils.isWif(keyOrSeed)) {
1115
+ privateKey = dhive.PrivateKey.fromString(keyOrSeed);
1116
+ } else {
1117
+ privateKey = dhive.PrivateKey.from(keyOrSeed);
1118
+ }
1119
+ return CONFIG.hiveClient.broadcast.sendOperations(
1120
+ [operation],
1121
+ privateKey
1122
+ );
1123
+ }
1124
+ });
1125
+ }
1126
+ function useSignOperationByKeychain(username, keyType = "Active") {
1127
+ return reactQuery.useMutation({
1128
+ mutationKey: ["operations", "sign-keychain", username],
1129
+ mutationFn: ({ operation }) => {
1130
+ if (!username) {
1131
+ throw new Error(
1132
+ "[SDK][Keychain] \u2013\xA0cannot sign operation with anon user"
1133
+ );
1134
+ }
1135
+ return keychain_exports.broadcast(username, [operation], keyType);
1136
+ }
1137
+ });
1138
+ }
1139
+ function useSignOperationByHivesigner(callbackUri = "/") {
1140
+ return reactQuery.useMutation({
1141
+ mutationKey: ["operations", "sign-hivesigner", callbackUri],
1142
+ mutationFn: async ({ operation }) => {
1143
+ return hs__default.default.sendOperation(operation, { callback: callbackUri }, () => {
1144
+ });
1145
+ }
1146
+ });
1147
+ }
1148
+ function getChainPropertiesQueryOptions() {
1149
+ return reactQuery.queryOptions({
1150
+ queryKey: ["operations", "chain-properties"],
1151
+ queryFn: async () => {
1152
+ return await CONFIG.hiveClient.database.getChainProperties();
1153
+ }
1154
+ });
1155
+ }
1156
+ function getTrendingTagsQueryOptions(limit = 20) {
1157
+ return reactQuery.infiniteQueryOptions({
1158
+ queryKey: ["posts", "trending-tags"],
1159
+ queryFn: async ({ pageParam: { afterTag } }) => CONFIG.hiveClient.database.call("get_trending_tags", [afterTag, limit]).then(
1160
+ (tags) => tags.filter((x) => x.name !== "").filter((x) => !x.name.startsWith("hive-")).map((x) => x.name)
1161
+ ),
1162
+ initialPageParam: { afterTag: "" },
1163
+ getNextPageParam: (lastPage) => ({
1164
+ afterTag: lastPage?.[lastPage?.length - 1]
1165
+ }),
1166
+ staleTime: Infinity,
1167
+ refetchOnMount: true
1168
+ });
1169
+ }
1170
+ function getFragmentsQueryOptions(username) {
1171
+ return reactQuery.queryOptions({
1172
+ queryKey: ["posts", "fragments", username],
1173
+ queryFn: async () => {
1174
+ const fetchApi = getBoundFetch();
1175
+ const response = await fetchApi(
1176
+ CONFIG.privateApiHost + "/private-api/fragments",
1177
+ {
1178
+ method: "POST",
1179
+ body: JSON.stringify({
1180
+ code: getAccessToken(username)
1181
+ }),
1182
+ headers: {
1183
+ "Content-Type": "application/json"
1184
+ }
1185
+ }
1186
+ );
1187
+ return response.json();
1188
+ },
1189
+ enabled: !!username
1190
+ });
1191
+ }
1192
+ function getPromotedPostsQuery(type = "feed") {
1193
+ return reactQuery.queryOptions({
1194
+ queryKey: ["posts", "promoted", type],
1195
+ queryFn: async () => {
1196
+ const url = new URL(
1197
+ CONFIG.privateApiHost + "/private-api/promoted-entries"
1198
+ );
1199
+ if (type === "waves") {
1200
+ url.searchParams.append("short_content", "1");
1201
+ }
1202
+ const fetchApi = getBoundFetch();
1203
+ const response = await fetchApi(url.toString(), {
1204
+ method: "GET",
1205
+ headers: {
1206
+ "Content-Type": "application/json"
1207
+ }
1208
+ });
1209
+ const data = await response.json();
1210
+ return data;
1211
+ }
1212
+ });
1213
+ }
1214
+ function useAddFragment(username) {
1215
+ return reactQuery.useMutation({
1216
+ mutationKey: ["posts", "add-fragment", username],
1217
+ mutationFn: async ({ title, body }) => {
1218
+ const fetchApi = getBoundFetch();
1219
+ const response = await fetchApi(
1220
+ CONFIG.privateApiHost + "/private-api/fragments-add",
1221
+ {
1222
+ method: "POST",
1223
+ body: JSON.stringify({
1224
+ code: getAccessToken(username),
1225
+ title,
1226
+ body
1227
+ }),
1228
+ headers: {
1229
+ "Content-Type": "application/json"
1230
+ }
1231
+ }
1232
+ );
1233
+ return response.json();
1234
+ },
1235
+ onSuccess(response) {
1236
+ getQueryClient().setQueryData(
1237
+ getFragmentsQueryOptions(username).queryKey,
1238
+ (data) => [response, ...data ?? []]
1239
+ );
1240
+ }
1241
+ });
1242
+ }
1243
+ function useEditFragment(username, fragmentId) {
1244
+ return reactQuery.useMutation({
1245
+ mutationKey: ["posts", "edit-fragment", username, fragmentId],
1246
+ mutationFn: async ({ title, body }) => {
1247
+ const fetchApi = getBoundFetch();
1248
+ const response = await fetchApi(
1249
+ CONFIG.privateApiHost + "/private-api/fragments-update",
1250
+ {
1251
+ method: "POST",
1252
+ body: JSON.stringify({
1253
+ code: getAccessToken(username),
1254
+ id: fragmentId,
1255
+ title,
1256
+ body
1257
+ }),
1258
+ headers: {
1259
+ "Content-Type": "application/json"
1260
+ }
1261
+ }
1262
+ );
1263
+ return response.json();
1264
+ },
1265
+ onSuccess(response) {
1266
+ getQueryClient().setQueryData(
1267
+ getFragmentsQueryOptions(username).queryKey,
1268
+ (data) => {
1269
+ if (!data) {
1270
+ return [];
1271
+ }
1272
+ const index = data.findIndex(({ id }) => id === fragmentId);
1273
+ if (index >= 0) {
1274
+ data[index] = response;
1275
+ }
1276
+ return [...data];
1277
+ }
1278
+ );
1279
+ }
1280
+ });
1281
+ }
1282
+ function useRemoveFragment(username, fragmentId) {
1283
+ return reactQuery.useMutation({
1284
+ mutationKey: ["posts", "remove-fragment", username],
1285
+ mutationFn: async () => {
1286
+ const fetchApi = getBoundFetch();
1287
+ return fetchApi(CONFIG.privateApiHost + "/private-api/fragments-delete", {
1288
+ method: "POST",
1289
+ body: JSON.stringify({
1290
+ code: getAccessToken(username),
1291
+ id: fragmentId
1292
+ }),
1293
+ headers: {
1294
+ "Content-Type": "application/json"
1295
+ }
1296
+ });
1297
+ },
1298
+ onSuccess() {
1299
+ getQueryClient().setQueryData(
1300
+ getFragmentsQueryOptions(username).queryKey,
1301
+ (data) => [...data ?? []].filter(({ id }) => id !== fragmentId)
1302
+ );
1303
+ }
1304
+ });
1305
+ }
1306
+
1307
+ // src/modules/analytics/mutations/index.ts
1308
+ var mutations_exports = {};
1309
+ __export(mutations_exports, {
1310
+ useRecordActivity: () => useRecordActivity
1311
+ });
1312
+ function useRecordActivity(username, activityType) {
1313
+ return reactQuery.useMutation({
1314
+ mutationKey: ["analytics", activityType],
1315
+ mutationFn: async () => {
1316
+ if (!activityType) {
1317
+ throw new Error("[SDK][Analytics] \u2013 no activity type provided");
1318
+ }
1319
+ const fetchApi = getBoundFetch();
1320
+ await fetchApi(CONFIG.plausibleHost + "/api/event", {
1321
+ method: "POST",
1322
+ headers: {
1323
+ "Content-Type": "application/json"
1324
+ },
1325
+ body: JSON.stringify({
1326
+ name: activityType,
1327
+ url: window.location.href,
1328
+ domain: window.location.host,
1329
+ props: {
1330
+ username
1331
+ }
1332
+ })
1333
+ });
1334
+ }
1335
+ });
1336
+ }
1337
+
1338
+ // src/modules/integrations/3speak/queries/index.ts
1339
+ var queries_exports2 = {};
1340
+ __export(queries_exports2, {
1341
+ getAccountTokenQueryOptions: () => getAccountTokenQueryOptions,
1342
+ getAccountVideosQueryOptions: () => getAccountVideosQueryOptions
1343
+ });
1344
+
1345
+ // src/modules/integrations/hivesigner/queries/index.ts
1346
+ var queries_exports = {};
1347
+ __export(queries_exports, {
1348
+ getDecodeMemoQueryOptions: () => getDecodeMemoQueryOptions
1349
+ });
1350
+ function getDecodeMemoQueryOptions(username, memo) {
1351
+ return reactQuery.queryOptions({
1352
+ queryKey: ["integrations", "hivesigner", "decode-memo", username],
1353
+ queryFn: async () => {
1354
+ const accessToken = getAccessToken(username);
1355
+ if (accessToken) {
1356
+ const hsClient = new hs__default.default.Client({
1357
+ accessToken
1358
+ });
1359
+ return hsClient.decode(memo);
1360
+ }
1361
+ }
1362
+ });
1363
+ }
1364
+
1365
+ // src/modules/integrations/hivesigner/index.ts
1366
+ var HiveSignerIntegration = {
1367
+ queries: queries_exports
1368
+ };
1369
+
1370
+ // src/modules/integrations/3speak/queries/get-account-token-query-options.ts
1371
+ function getAccountTokenQueryOptions(username) {
1372
+ return reactQuery.queryOptions({
1373
+ queryKey: ["integrations", "3speak", "authenticate", username],
1374
+ enabled: !!username,
1375
+ queryFn: async () => {
1376
+ if (!username) {
1377
+ throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");
1378
+ }
1379
+ const fetchApi = getBoundFetch();
1380
+ const response = await fetchApi(
1381
+ `https://studio.3speak.tv/mobile/login?username=${username}&hivesigner=true`,
1382
+ {
1383
+ headers: {
1384
+ "Content-Type": "application/json"
1385
+ }
1386
+ }
1387
+ );
1388
+ const memoQueryOptions = HiveSignerIntegration.queries.getDecodeMemoQueryOptions(
1389
+ username,
1390
+ (await response.json()).memo
1391
+ );
1392
+ await getQueryClient().prefetchQuery(memoQueryOptions);
1393
+ const { memoDecoded } = getQueryClient().getQueryData(
1394
+ memoQueryOptions.queryKey
1395
+ );
1396
+ return memoDecoded.replace("#", "");
1397
+ }
1398
+ });
1399
+ }
1400
+ function getAccountVideosQueryOptions(username) {
1401
+ return reactQuery.queryOptions({
1402
+ queryKey: ["integrations", "3speak", "videos", username],
1403
+ enabled: !!username,
1404
+ queryFn: async () => {
1405
+ await getQueryClient().prefetchQuery(
1406
+ getAccountTokenQueryOptions(username)
1407
+ );
1408
+ const token = getQueryClient().getQueryData(
1409
+ getAccountTokenQueryOptions(username).queryKey
1410
+ );
1411
+ const fetchApi = getBoundFetch();
1412
+ const response = await fetchApi(
1413
+ `https://studio.3speak.tv/mobile/api/my-videos`,
1414
+ {
1415
+ headers: {
1416
+ "Content-Type": "application/json",
1417
+ Authorization: `Bearer ${token}`
1418
+ }
1419
+ }
1420
+ );
1421
+ return await response.json();
1422
+ }
1423
+ });
1424
+ }
1425
+
1426
+ // src/modules/integrations/3speak/index.ts
1427
+ var ThreeSpeakIntegration = {
1428
+ queries: queries_exports2
1429
+ };
1430
+ function getHivePoshLinksQueryOptions(username) {
1431
+ return reactQuery.queryOptions({
1432
+ queryKey: ["integrations", "hiveposh", "links", username],
1433
+ queryFn: async () => {
1434
+ const fetchApi = getBoundFetch();
1435
+ const response = await fetchApi(
1436
+ `https://hiveposh.com/api/v0/linked-accounts/${username}`,
1437
+ {
1438
+ headers: {
1439
+ "Content-Type": "application/json"
1440
+ }
1441
+ }
1442
+ );
1443
+ const data = await response.json();
1444
+ return {
1445
+ twitter: {
1446
+ username: data.twitter_username,
1447
+ profile: data.twitter_profile
1448
+ },
1449
+ reddit: {
1450
+ username: data.reddit_username,
1451
+ profile: data.reddit_profile
1452
+ }
1453
+ };
1454
+ }
1455
+ });
1456
+ }
1457
+ function getStatsQueryOptions({
1458
+ url,
1459
+ dimensions = [],
1460
+ metrics = ["visitors", "pageviews", "visit_duration"],
1461
+ enabled = true
1462
+ }) {
1463
+ return reactQuery.queryOptions({
1464
+ queryKey: ["integrations", "plausible", url, dimensions, metrics],
1465
+ queryFn: async () => {
1466
+ const fetchApi = getBoundFetch();
1467
+ const response = await fetchApi(`https://ecency.com/api/stats`, {
1468
+ method: "POST",
1469
+ body: JSON.stringify({
1470
+ metrics,
1471
+ url: encodeURIComponent(url),
1472
+ dimensions
1473
+ }),
1474
+ headers: {
1475
+ "Content-Type": "application/json"
1476
+ }
1477
+ });
1478
+ return await response.json();
1479
+ },
1480
+ enabled: !!url && enabled
1481
+ });
1482
+ }
1483
+ function getRcStatsQueryOptions() {
1484
+ return reactQuery.queryOptions({
1485
+ queryKey: ["resource-credits", "stats"],
1486
+ queryFn: async () => {
1487
+ const response = await CONFIG.hiveClient.call(
1488
+ "rc_api",
1489
+ "get_rc_stats",
1490
+ {}
1491
+ );
1492
+ return response.rc_stats;
1493
+ }
1494
+ });
1495
+ }
1496
+ function getAccountRcQueryOptions(username) {
1497
+ return reactQuery.queryOptions({
1498
+ queryKey: ["resource-credits", "account", username],
1499
+ queryFn: async () => {
1500
+ const rcClient = new dhive.RCAPI(CONFIG.hiveClient);
1501
+ return rcClient.findRCAccounts([username]);
1502
+ },
1503
+ enabled: !!username
1504
+ });
1505
+ }
1506
+ function getGameStatusCheckQueryOptions(username, gameType) {
1507
+ return reactQuery.queryOptions({
1508
+ queryKey: ["games", "status-check", gameType, username],
1509
+ enabled: !!username,
1510
+ queryFn: async () => {
1511
+ if (!username) {
1512
+ throw new Error("[SDK][Games] \u2013 anon user in status check");
1513
+ }
1514
+ const fetchApi = getBoundFetch();
1515
+ const response = await fetchApi(
1516
+ CONFIG.privateApiHost + "/private-api/get-game",
1517
+ {
1518
+ method: "POST",
1519
+ body: JSON.stringify({
1520
+ game_type: gameType,
1521
+ code: getAccessToken(username)
1522
+ }),
1523
+ headers: {
1524
+ "Content-Type": "application/json"
1525
+ }
1526
+ }
1527
+ );
1528
+ return await response.json();
1529
+ }
1530
+ });
1531
+ }
1532
+ function useGameClaim(username, gameType, key) {
1533
+ const { mutateAsync: recordActivity } = useRecordActivity(
1534
+ username,
1535
+ "spin-rolled"
1536
+ );
1537
+ return reactQuery.useMutation({
1538
+ mutationKey: ["games", "post", gameType, username],
1539
+ mutationFn: async () => {
1540
+ if (!username) {
1541
+ throw new Error("[SDK][Games] \u2013 anon user in game post");
1542
+ }
1543
+ const fetchApi = getBoundFetch();
1544
+ const response = await fetchApi(
1545
+ CONFIG.privateApiHost + "/private-api/post-game",
1546
+ {
1547
+ method: "POST",
1548
+ body: JSON.stringify({
1549
+ game_type: gameType,
1550
+ code: getAccessToken(username),
1551
+ key
1552
+ }),
1553
+ headers: {
1554
+ "Content-Type": "application/json"
1555
+ }
1556
+ }
1557
+ );
1558
+ return await response.json();
1559
+ },
1560
+ onSuccess() {
1561
+ recordActivity();
1562
+ }
1563
+ });
1564
+ }
1565
+ function getCommunitiesQueryOptions(sort, query, limit = 100, observer = void 0, enabled = true) {
1566
+ return reactQuery.queryOptions({
1567
+ queryKey: ["communities", "list", sort, query, limit],
1568
+ enabled,
1569
+ queryFn: async () => {
1570
+ const response = await CONFIG.hiveClient.call(
1571
+ "bridge",
1572
+ "list_communities",
1573
+ {
1574
+ last: "",
1575
+ limit,
1576
+ sort: sort === "hot" ? "rank" : sort,
1577
+ query: query ? query : null,
1578
+ observer
1579
+ }
1580
+ );
1581
+ return response ? sort === "hot" ? response.sort(() => Math.random() - 0.5) : response : [];
1582
+ }
1583
+ });
1584
+ }
1585
+ function getCommunityContextQueryOptions(username, communityName) {
1586
+ return reactQuery.queryOptions({
1587
+ queryKey: ["community", "context", username, communityName],
1588
+ enabled: !!username && !!communityName,
1589
+ queryFn: async () => {
1590
+ const response = await CONFIG.hiveClient.call(
1591
+ "bridge",
1592
+ "get_community_context",
1593
+ {
1594
+ account: username,
1595
+ name: communityName
1596
+ }
1597
+ );
1598
+ return {
1599
+ role: response?.role ?? "guest",
1600
+ subscribed: response?.subscribed ?? false
1601
+ };
1602
+ }
1603
+ });
1604
+ }
1605
+
1606
+ // src/modules/communities/types/community.ts
1607
+ var ROLES = /* @__PURE__ */ ((ROLES2) => {
1608
+ ROLES2["OWNER"] = "owner";
1609
+ ROLES2["ADMIN"] = "admin";
1610
+ ROLES2["MOD"] = "mod";
1611
+ ROLES2["MEMBER"] = "member";
1612
+ ROLES2["GUEST"] = "guest";
1613
+ ROLES2["MUTED"] = "muted";
1614
+ return ROLES2;
1615
+ })(ROLES || {});
1616
+ var roleMap = {
1617
+ ["owner" /* OWNER */]: [
1618
+ "admin" /* ADMIN */,
1619
+ "mod" /* MOD */,
1620
+ "member" /* MEMBER */,
1621
+ "guest" /* GUEST */,
1622
+ "muted" /* MUTED */
1623
+ ],
1624
+ ["admin" /* ADMIN */]: ["mod" /* MOD */, "member" /* MEMBER */, "guest" /* GUEST */, "muted" /* MUTED */],
1625
+ ["mod" /* MOD */]: ["member" /* MEMBER */, "guest" /* GUEST */, "muted" /* MUTED */]
1626
+ };
1627
+
1628
+ // src/modules/communities/utils/index.ts
1629
+ function getCommunityType(name, type_id) {
1630
+ if (name.startsWith("hive-3") || type_id === 3) return "Council";
1631
+ if (name.startsWith("hive-2") || type_id === 2) return "Journal";
1632
+ return "Topic";
1633
+ }
1634
+ function getCommunityPermissions({
1635
+ communityType,
1636
+ userRole,
1637
+ subscribed
1638
+ }) {
1639
+ const canPost = (() => {
1640
+ if (userRole === "muted" /* MUTED */) return false;
1641
+ if (communityType === "Topic") return true;
1642
+ return ["owner" /* OWNER */, "admin" /* ADMIN */, "mod" /* MOD */, "member" /* MEMBER */].includes(
1643
+ userRole
1644
+ );
1645
+ })();
1646
+ const canComment = (() => {
1647
+ if (userRole === "muted" /* MUTED */) return false;
1648
+ switch (communityType) {
1649
+ case "Topic":
1650
+ return true;
1651
+ case "Journal":
1652
+ return userRole !== "guest" /* GUEST */ || subscribed;
1653
+ case "Council":
1654
+ return canPost;
1655
+ }
1656
+ })();
1657
+ const isModerator = ["owner" /* OWNER */, "admin" /* ADMIN */, "mod" /* MOD */].includes(userRole);
1658
+ return {
1659
+ canPost,
1660
+ canComment,
1661
+ isModerator
1662
+ };
1663
+ }
1664
+
1665
+ exports.CONFIG = CONFIG;
1666
+ exports.EcencyAnalytics = mutations_exports;
1667
+ exports.HiveSignerIntegration = HiveSignerIntegration;
1668
+ exports.Keychain = keychain_exports;
1669
+ exports.NaiMap = NaiMap;
1670
+ exports.ROLES = ROLES;
1671
+ exports.Symbol = Symbol2;
1672
+ exports.ThreeSpeakIntegration = ThreeSpeakIntegration;
1673
+ exports.broadcastJson = broadcastJson;
1674
+ exports.checkUsernameWalletsPendingQueryOptions = checkUsernameWalletsPendingQueryOptions;
1675
+ exports.decodeObj = decodeObj;
1676
+ exports.dedupeAndSortKeyAuths = dedupeAndSortKeyAuths;
1677
+ exports.encodeObj = encodeObj;
1678
+ exports.getAccessToken = getAccessToken;
1679
+ exports.getAccountFullQueryOptions = getAccountFullQueryOptions;
1680
+ exports.getAccountPendingRecoveryQueryOptions = getAccountPendingRecoveryQueryOptions;
1681
+ exports.getAccountRcQueryOptions = getAccountRcQueryOptions;
1682
+ exports.getAccountRecoveriesQueryOptions = getAccountRecoveriesQueryOptions;
1683
+ exports.getAccountSubscriptionsQueryOptions = getAccountSubscriptionsQueryOptions;
1684
+ exports.getActiveAccountBookmarksQueryOptions = getActiveAccountBookmarksQueryOptions;
1685
+ exports.getActiveAccountFavouritesQueryOptions = getActiveAccountFavouritesQueryOptions;
1686
+ exports.getBoundFetch = getBoundFetch;
1687
+ exports.getChainPropertiesQueryOptions = getChainPropertiesQueryOptions;
1688
+ exports.getCommunitiesQueryOptions = getCommunitiesQueryOptions;
1689
+ exports.getCommunityContextQueryOptions = getCommunityContextQueryOptions;
1690
+ exports.getCommunityPermissions = getCommunityPermissions;
1691
+ exports.getCommunityType = getCommunityType;
1692
+ exports.getDynamicPropsQueryOptions = getDynamicPropsQueryOptions;
1693
+ exports.getFragmentsQueryOptions = getFragmentsQueryOptions;
1694
+ exports.getGameStatusCheckQueryOptions = getGameStatusCheckQueryOptions;
1695
+ exports.getHivePoshLinksQueryOptions = getHivePoshLinksQueryOptions;
1696
+ exports.getLoginType = getLoginType;
1697
+ exports.getPostingKey = getPostingKey;
1698
+ exports.getPromotedPostsQuery = getPromotedPostsQuery;
1699
+ exports.getQueryClient = getQueryClient;
1700
+ exports.getRcStatsQueryOptions = getRcStatsQueryOptions;
1701
+ exports.getRefreshToken = getRefreshToken;
1702
+ exports.getRelationshipBetweenAccountsQueryOptions = getRelationshipBetweenAccountsQueryOptions;
1703
+ exports.getSearchAccountsByUsernameQueryOptions = getSearchAccountsByUsernameQueryOptions;
1704
+ exports.getStatsQueryOptions = getStatsQueryOptions;
1705
+ exports.getTrendingTagsQueryOptions = getTrendingTagsQueryOptions;
1706
+ exports.getUser = getUser;
1707
+ exports.makeQueryClient = makeQueryClient;
1708
+ exports.parseAsset = parseAsset;
1709
+ exports.roleMap = roleMap;
1710
+ exports.useAccountFavouriteAdd = useAccountFavouriteAdd;
1711
+ exports.useAccountFavouriteDelete = useAccountFavouriteDelete;
1712
+ exports.useAccountRelationsUpdate = useAccountRelationsUpdate;
1713
+ exports.useAccountRevokeKey = useAccountRevokeKey;
1714
+ exports.useAccountRevokePosting = useAccountRevokePosting;
1715
+ exports.useAccountUpdate = useAccountUpdate;
1716
+ exports.useAccountUpdateKeyAuths = useAccountUpdateKeyAuths;
1717
+ exports.useAccountUpdatePassword = useAccountUpdatePassword;
1718
+ exports.useAccountUpdateRecovery = useAccountUpdateRecovery;
1719
+ exports.useAddFragment = useAddFragment;
1720
+ exports.useBookmarkAdd = useBookmarkAdd;
1721
+ exports.useBookmarkDelete = useBookmarkDelete;
1722
+ exports.useBroadcastMutation = useBroadcastMutation;
1723
+ exports.useEditFragment = useEditFragment;
1724
+ exports.useGameClaim = useGameClaim;
1725
+ exports.useRemoveFragment = useRemoveFragment;
1726
+ exports.useSignOperationByHivesigner = useSignOperationByHivesigner;
1727
+ exports.useSignOperationByKey = useSignOperationByKey;
1728
+ exports.useSignOperationByKeychain = useSignOperationByKeychain;
1729
+ //# sourceMappingURL=index.cjs.map
1730
+ //# sourceMappingURL=index.cjs.map