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