@akita-protocol/algomd-rn 0.0.0-stage → 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/README.md +137 -2
  2. package/package.json +118 -3
  3. package/src/adapters/index.ts +4 -0
  4. package/src/adapters/txn-graph.ts +138 -0
  5. package/src/components/ASA.tsx +38 -0
  6. package/src/components/ASASearch.tsx +79 -0
  7. package/src/components/Account.tsx +42 -0
  8. package/src/components/AccountSearch.tsx +75 -0
  9. package/src/components/AuctionListing.tsx +40 -0
  10. package/src/components/Collection.tsx +42 -0
  11. package/src/components/DualStakePool.tsx +244 -0
  12. package/src/components/NFDProfile.tsx +45 -0
  13. package/src/components/NFDSearch.tsx +81 -0
  14. package/src/components/NFTListing.tsx +73 -0
  15. package/src/components/NFTSearch.tsx +68 -0
  16. package/src/components/Poll.tsx +39 -0
  17. package/src/components/PollSearch.tsx +79 -0
  18. package/src/components/PrizeBoxBundle.tsx +1 -0
  19. package/src/components/RaffleListing.tsx +40 -0
  20. package/src/components/SelfFetching.tsx +1048 -0
  21. package/src/components/StakingPool.tsx +134 -0
  22. package/src/components/TradeOffer.tsx +47 -0
  23. package/src/components/TradeSearch.tsx +103 -0
  24. package/src/components/TransactionDetails.tsx +37 -0
  25. package/src/components/TransactionSearch.tsx +102 -0
  26. package/src/components/TransactionsGraph.tsx +60 -0
  27. package/src/components/index.ts +41 -0
  28. package/src/fonts/OFL.txt +93 -0
  29. package/src/fonts/SpaceGrotesk_300Light.ttf +0 -0
  30. package/src/fonts/SpaceGrotesk_400Regular.ttf +0 -0
  31. package/src/fonts/SpaceGrotesk_500Medium.ttf +0 -0
  32. package/src/fonts/SpaceGrotesk_600SemiBold.ttf +0 -0
  33. package/src/fonts/SpaceGrotesk_700Bold.ttf +0 -0
  34. package/src/fonts/app.css +5 -0
  35. package/src/graph.ts +3 -0
  36. package/src/hooks/index.ts +17 -0
  37. package/src/hooks/useAlgomdData.ts +1539 -0
  38. package/src/hooks/useAlgorandClient.ts +54 -0
  39. package/src/index.ts +147 -0
  40. package/src/presentation/ASADisplay.tsx +380 -0
  41. package/src/presentation/AccountDisplay.tsx +132 -0
  42. package/src/presentation/AccountMentionInline.tsx +38 -0
  43. package/src/presentation/AccountMentionText.tsx +80 -0
  44. package/src/presentation/AdaptiveImage.tsx +314 -0
  45. package/src/presentation/AssetMention.tsx +87 -0
  46. package/src/presentation/AuctionListingDisplay.tsx +428 -0
  47. package/src/presentation/BundleContents.tsx +228 -0
  48. package/src/presentation/CardContainer.tsx +61 -0
  49. package/src/presentation/CardEntrance.tsx +21 -0
  50. package/src/presentation/CollectionDisplay.tsx +168 -0
  51. package/src/presentation/ContractMenu.tsx +243 -0
  52. package/src/presentation/DualStakePoolDisplay.tsx +335 -0
  53. package/src/presentation/Embeds.tsx +300 -0
  54. package/src/presentation/GateRequirements.tsx +334 -0
  55. package/src/presentation/HEROICONS-LICENSE.txt +21 -0
  56. package/src/presentation/NFDProfileDisplay.tsx +194 -0
  57. package/src/presentation/NFTListingDisplay.tsx +284 -0
  58. package/src/presentation/OnChainActionCard.tsx +557 -0
  59. package/src/presentation/PollDisplay.tsx +222 -0
  60. package/src/presentation/PrizeBoxBundleDisplay.tsx +103 -0
  61. package/src/presentation/PrizeBoxMedia.tsx +46 -0
  62. package/src/presentation/PrizePreview.tsx +296 -0
  63. package/src/presentation/ProgressBar.tsx +50 -0
  64. package/src/presentation/RaffleListingDisplay.tsx +399 -0
  65. package/src/presentation/References.tsx +310 -0
  66. package/src/presentation/ReservedNotice.tsx +73 -0
  67. package/src/presentation/ResultsPanel.tsx +241 -0
  68. package/src/presentation/Sparkline.tsx +70 -0
  69. package/src/presentation/SquishyPressable.tsx +145 -0
  70. package/src/presentation/StakingPoolDisplay.tsx +419 -0
  71. package/src/presentation/StatusBadge.tsx +56 -0
  72. package/src/presentation/TradeOfferDisplay.tsx +275 -0
  73. package/src/presentation/TransactionDisplay.tsx +262 -0
  74. package/src/presentation/WinnerBadge.tsx +58 -0
  75. package/src/presentation/assetHelpers.ts +36 -0
  76. package/src/presentation/assets.ts +7 -0
  77. package/src/presentation/explorer.ts +95 -0
  78. package/src/presentation/format.ts +90 -0
  79. package/src/presentation/gates.ts +100 -0
  80. package/src/presentation/icons.tsx +1178 -0
  81. package/src/presentation/identity.tsx +175 -0
  82. package/src/presentation/index.ts +88 -0
  83. package/src/presentation/media.ts +70 -0
  84. package/src/presentation/pluginColors.ts +8 -0
  85. package/src/presentation/runtime.tsx +280 -0
  86. package/src/presentation/sheets.tsx +7 -0
  87. package/src/presentation/subject.tsx +31 -0
  88. package/src/presentation/textTheme.ts +17 -0
  89. package/src/presentation/themes.json +158 -0
  90. package/src/presentation/variants.ts +14 -0
  91. package/src/provider/AlgomdProvider.tsx +45 -0
  92. package/src/provider/context.ts +18 -0
  93. package/src/provider/imageResolver.ts +12 -0
  94. package/src/provider/index.ts +5 -0
  95. package/src/provider/networks.ts +23 -0
  96. package/src/provider/types.ts +29 -0
  97. package/src/refs/AccountRef.tsx +226 -0
  98. package/src/refs/ApplicationRef.tsx +72 -0
  99. package/src/refs/AssetRef.tsx +142 -0
  100. package/src/refs/AuctionRef.tsx +108 -0
  101. package/src/refs/CollectionRef.tsx +70 -0
  102. package/src/refs/DualStakeRef.tsx +88 -0
  103. package/src/refs/GuildProposalRef.tsx +285 -0
  104. package/src/refs/HostRefs.tsx +82 -0
  105. package/src/refs/ListingRef.tsx +90 -0
  106. package/src/refs/NfdRef.tsx +96 -0
  107. package/src/refs/PollRef.tsx +120 -0
  108. package/src/refs/RaffleRef.tsx +101 -0
  109. package/src/refs/RewardRef.tsx +78 -0
  110. package/src/refs/StakingPoolRef.tsx +136 -0
  111. package/src/refs/SubscriptionRef.tsx +200 -0
  112. package/src/refs/TradeRef.tsx +100 -0
  113. package/src/refs/TransactionRef.tsx +156 -0
  114. package/src/refs/assetInfo.ts +49 -0
  115. package/src/refs/contractParts.tsx +159 -0
  116. package/src/refs/index.tsx +140 -0
  117. package/src/refs/primitives.tsx +588 -0
  118. package/src/refs/types.ts +13 -0
  119. package/src/types/algorand.ts +496 -0
  120. package/src/types/index.ts +1 -0
  121. package/src/ui/CopyButton.tsx +44 -0
  122. package/src/ui/DataStates.tsx +45 -0
  123. package/src/ui/ProgressBar.tsx +64 -0
  124. package/src/ui/SearchSheet.tsx +141 -0
  125. package/src/ui/SizeContainer.tsx +25 -0
  126. package/src/ui/StatusBadge.tsx +51 -0
  127. package/src/ui/index.ts +6 -0
  128. package/src/utils/algomdImageUrl.ts +20 -0
  129. package/src/utils/arc19.ts +120 -0
  130. package/src/utils/arc62.ts +246 -0
  131. package/src/utils/capacity.ts +26 -0
  132. package/src/utils/format.ts +181 -0
  133. package/src/utils/ids.ts +31 -0
  134. package/src/utils/index.ts +6 -0
  135. package/src/utils/nfdDisplay.ts +45 -0
  136. package/src/utils/search.ts +87 -0
  137. package/src/utils/stakingPool.ts +174 -0
  138. package/src/utils/stakingSnapshot.ts +132 -0
@@ -0,0 +1,1539 @@
1
+ /**
2
+ * AlgoMD self-fetching data hooks.
3
+ *
4
+ * Each hook reads directly from algod/indexer (via @akita-protocol/sdk typed clients
5
+ * where available) and maps to the algomd-rn display types.
6
+ */
7
+
8
+ // These web APIs are available in Hermes / all modern JS engines but not in TS "esnext" lib
9
+ declare const TextDecoder: {
10
+ new (): { decode(input?: ArrayBuffer | Uint8Array): string };
11
+ };
12
+ declare function btoa(data: string): string;
13
+
14
+ import { useQuery } from "@tanstack/react-query";
15
+ import {
16
+ PollSDK,
17
+ RaffleSDK,
18
+ AuctionSDK,
19
+ StakingPoolSDK,
20
+ ListingSDK,
21
+ HyperSwapSDK,
22
+ GateSDK,
23
+ getNetworkAppIds,
24
+ } from "@akita-protocol/sdk";
25
+ import { useAlgorandClient, useIndexerClient } from "./useAlgorandClient";
26
+ import { useAlgomd } from "../provider/context";
27
+ import { resolveAssetUrl } from "../utils/arc19";
28
+ import { assetMetadataUrl, fetchCirculatingSupply, restArc62Clients } from "../utils/arc62";
29
+ import { NETWORK_DEFAULTS } from "../provider/networks";
30
+ import { normalizeAppId, normalizeAssetId } from "../utils/ids";
31
+ import {
32
+ decodeStakingPoolRewardBox,
33
+ decodeStakingPoolBudgetBox,
34
+ decodeStakingPoolRewardBoxId,
35
+ deriveStakingPoolStatus,
36
+ isStakingPoolBudgetBoxName,
37
+ isStakingPoolRewardBoxName,
38
+ type DecodedStakingPoolReward,
39
+ } from "../utils/stakingPool";
40
+ import type { AlgorandClient } from "@algorandfoundation/algokit-utils";
41
+ import { getApplicationAddress } from "@algorandfoundation/algokit-utils/common";
42
+ import type {
43
+ AlgorandAccount,
44
+ ASA as ASAType,
45
+ Collection as CollectionType,
46
+ TransactionDetails as TransactionDetailsType,
47
+ NFDProfile as NFDProfileType,
48
+ Poll as PollType,
49
+ PollOption,
50
+ RaffleListing as RaffleListingType,
51
+ AuctionListing as AuctionListingType,
52
+ StakingPool as StakingPoolType,
53
+ StakingPoolDistributionType,
54
+ StakingPoolStakingType,
55
+ PrizeBoxBundle,
56
+ TradeOffer as TradeOfferType,
57
+ NFTListing as NFTListingType,
58
+ GateOperator,
59
+ GateRule,
60
+ GatingInfo,
61
+ } from "../types/algorand";
62
+ import type { AlgomdNetwork } from "../provider/types";
63
+
64
+ type BackendCollection = {
65
+ id?: string | number;
66
+ collection_id?: string | number;
67
+ nfd_id?: number;
68
+ name?: string | null;
69
+ description?: string | null;
70
+ avatar?: string | number | null;
71
+ avatar_url?: string | null;
72
+ avatar_mime?: string | null;
73
+ banner?: string | number | null;
74
+ network?: string | null;
75
+ explicit?: boolean;
76
+ prefixes?: string[];
77
+ artists?: string[];
78
+ };
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // Default reader account for SDK read-only calls that require a sender
82
+ // (e.g. RaffleSDK.state() which uses client.send.getState).
83
+ // ---------------------------------------------------------------------------
84
+
85
+ const DEFAULT_READER =
86
+ "Y76M3MSY6DKBRHBL7C3NNDXGS5IIMQVQVUAB6MP4XEMMGVF2QWNPL226CA";
87
+
88
+ const ACTIVE_LIFECYCLE_REFETCH_MS = 15_000;
89
+ const SETTLEMENT_REFETCH_MS = 60_000;
90
+
91
+ function requireStateFields<T extends object, K extends keyof T>(
92
+ state: T,
93
+ keys: readonly K[],
94
+ ): asserts state is T & Required<Pick<T, K>> {
95
+ for (const key of keys) {
96
+ if (state[key] == null) throw new Error(`Missing contract state: ${String(key)}`);
97
+ }
98
+ }
99
+
100
+ // ---------------------------------------------------------------------------
101
+ // Shared helper: fetch ASA details from algod
102
+ // ---------------------------------------------------------------------------
103
+
104
+ async function fetchASADetails(
105
+ algorand: AlgorandClient,
106
+ assetId: number | bigint,
107
+ ): Promise<ASAType> {
108
+ // Native ALGO (asset ID 0) isn't a real ASA — return known properties directly
109
+ if (Number(assetId) === 0) {
110
+ return {
111
+ id: 0,
112
+ name: "Algo",
113
+ unitName: "ALGO",
114
+ total: 10_000_000_000_000_000,
115
+ totalRaw: "10000000000000000",
116
+ decimals: 6,
117
+ defaultFrozen: false,
118
+ creator: "",
119
+ createdAt: new Date(0),
120
+ verified: true,
121
+ };
122
+ }
123
+
124
+ // Asset precision is transaction-critical. Let the owning query surface a
125
+ // lookup error instead of fabricating a zero-decimal ASA that could turn a
126
+ // human amount into the wrong number of base units.
127
+ const info = await algorand.client.algod.assetById(BigInt(assetId));
128
+ const params = info.params;
129
+ return {
130
+ id: Number(assetId),
131
+ name: params.name ?? `Asset #${assetId}`,
132
+ unitName: params.unitName ?? "",
133
+ total: Number(params.total),
134
+ totalRaw: params.total.toString(),
135
+ decimals: Number(params.decimals),
136
+ defaultFrozen: params.defaultFrozen ?? false,
137
+ url: params.url,
138
+ reserve: params.reserve,
139
+ manager: params.manager,
140
+ freeze: params.freeze,
141
+ clawback: params.clawback,
142
+ creator: params.creator ?? "",
143
+ createdAt: new Date(),
144
+ verified: false,
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Resolves image URLs for an ASA using ARC-19 resolution and CDN proxy.
150
+ * Mutates the asset in place for convenience.
151
+ */
152
+ function resolveAssetImage(
153
+ asset: ASAType,
154
+ resolveImageUrl: (src: string, width: number) => string,
155
+ width = 300,
156
+ ): void {
157
+ const resolved = resolveAssetUrl(asset.url, asset.reserve);
158
+ if (resolved) {
159
+ asset.imageUrl = resolveImageUrl(resolved, width);
160
+ }
161
+ }
162
+
163
+ const GATE_OPERATORS: Record<number, GateOperator> = {
164
+ 10: "=",
165
+ 20: "!=",
166
+ 30: "<",
167
+ 40: "<=",
168
+ 50: ">",
169
+ 60: ">=",
170
+ 70: "in",
171
+ 90: "not in",
172
+ };
173
+
174
+ function gateText(value: unknown): string {
175
+ if (value instanceof Uint8Array) return new TextDecoder().decode(value).replace(/\0+$/, "");
176
+ return value == null ? "" : String(value);
177
+ }
178
+
179
+ /** One decoded gate registry entry as a display rule; unknown shapes are skipped. */
180
+ async function toGateRule(
181
+ algorand: AlgorandClient,
182
+ entry: Record<string, unknown>,
183
+ resolveImageUrl: (src: string, width: number) => string,
184
+ ): Promise<GateRule | undefined> {
185
+ const op = GATE_OPERATORS[Number(entry.op)] ?? ">=";
186
+ const asset = async (id: unknown) => {
187
+ const details = await fetchASADetails(algorand, BigInt(String(id ?? 0))).catch(() => undefined);
188
+ if (details) resolveAssetImage(details, resolveImageUrl);
189
+ return details;
190
+ };
191
+ switch (entry.type) {
192
+ case "asset":
193
+ return { type: "asset", assetId: Number(entry.asset), op, amountRaw: gateText(entry.value), asset: await asset(entry.asset) };
194
+ case "staking_amount":
195
+ return { type: "staking_amount", assetId: Number(entry.asset), op, amountRaw: gateText(entry.amount), stakingType: gateText(entry.stakingType), asset: await asset(entry.asset) };
196
+ case "staking_power":
197
+ return { type: "staking_power", assetId: Number(entry.asset), op, power: gateText(entry.power), asset: await asset(entry.asset) };
198
+ case "nfd":
199
+ return { type: "nfd" };
200
+ case "nfd_root":
201
+ return { type: "nfd_root", root: gateText(entry.root) };
202
+ case "akita_referrer":
203
+ return { type: "akita_referrer", referrer: gateText(entry.referrer) };
204
+ case "merkle_address":
205
+ case "merkle_asset":
206
+ return { type: entry.type, creator: gateText(entry.creator), name: gateText(entry.name) };
207
+ case "poll":
208
+ return { type: "poll", pollId: gateText(entry.poll) };
209
+ case "social_activity":
210
+ case "social_follower_count":
211
+ case "social_impact":
212
+ case "social_moderator":
213
+ return { type: entry.type, op, value: gateText(entry.value) };
214
+ case "social_follower_index":
215
+ return { type: "social_follower_index", user: gateText(entry.user), op, value: gateText(entry.value) };
216
+ case "subscription":
217
+ return { type: "subscription", merchant: gateText(entry.merchant), serviceId: gateText(entry.id) };
218
+ case "subscription_streak":
219
+ return { type: "subscription_streak", merchant: gateText(entry.merchant), serviceId: gateText(entry.id), op, streak: gateText(entry.streak) };
220
+ default:
221
+ return undefined;
222
+ }
223
+ }
224
+
225
+ /**
226
+ * A contract's gate with its rules read from the gate registry. If the registry
227
+ * can't be read, the gate is still reported so the card says the action is gated.
228
+ */
229
+ async function fetchGatingInfo(
230
+ algorand: AlgorandClient,
231
+ network: AlgomdNetwork,
232
+ gateId: bigint,
233
+ resolveImageUrl: (src: string, width: number) => string,
234
+ ): Promise<GatingInfo | undefined> {
235
+ if (gateId <= BigInt(0)) return undefined;
236
+ const gating: GatingInfo = {
237
+ type: "custom",
238
+ requirements: { custom: { gateAppId: Number(gateId) } },
239
+ gateId: gateId.toString(),
240
+ };
241
+ try {
242
+ const ids = getNetworkAppIds(network);
243
+ if (!ids.gate) return gating;
244
+ const sdk = new GateSDK({
245
+ algorand,
246
+ readerAccount: DEFAULT_READER,
247
+ gateRegistry: {
248
+ akita_referrer: ids.akitaReferrerGate,
249
+ asset: ids.assetGate,
250
+ merkle_address: ids.merkleAddressGate,
251
+ merkle_asset: ids.merkleAssetGate,
252
+ nfd: ids.nfdGate,
253
+ nfd_root: ids.nfdRootGate,
254
+ poll: ids.pollGate,
255
+ social_activity: ids.socialActivityGate,
256
+ social_follower_count: ids.socialFollowerCountGate,
257
+ social_follower_index: ids.socialFollowerIndexGate,
258
+ social_impact: ids.socialImpactGate,
259
+ social_moderator: ids.socialModeratorGate,
260
+ staking_amount: ids.stakingAmountGate,
261
+ staking_power: ids.stakingPowerGate,
262
+ subscription: ids.subscriptionGate,
263
+ subscription_streak: ids.subscriptionStreakGate,
264
+ },
265
+ factoryParams: { appId: ids.gate, defaultSender: DEFAULT_READER },
266
+ } as ConstructorParameters<typeof GateSDK>[0]);
267
+ const decoded: unknown = await sdk.getGate({ gateId });
268
+ if (!Array.isArray(decoded)) return gating;
269
+ const rules = await Promise.all(
270
+ decoded.map((entry) =>
271
+ toGateRule(algorand, entry as Record<string, unknown>, resolveImageUrl),
272
+ ),
273
+ );
274
+ return { ...gating, rules: rules.filter((rule): rule is GateRule => !!rule) };
275
+ } catch {
276
+ return gating;
277
+ }
278
+ }
279
+
280
+ async function fetchPrizeBoxBundle(
281
+ algorand: AlgorandClient,
282
+ prizeBoxAppId: bigint,
283
+ resolveImageUrl: (src: string, width: number) => string,
284
+ ): Promise<PrizeBoxBundle> {
285
+ const appId = prizeBoxAppId.toString();
286
+ const address = getApplicationAddress(prizeBoxAppId).toString();
287
+ const fallback: PrizeBoxBundle = { appId, address, holdings: [] };
288
+
289
+ try {
290
+ const info = await algorand.client.algod.accountInformation(address);
291
+ const assetBalances = (info.assets ?? []).filter(
292
+ (holding: { amount: bigint }) => holding.amount > BigInt(0),
293
+ );
294
+ const asaHoldings = await Promise.all(
295
+ assetBalances.map(
296
+ async (holding: { assetId: bigint; amount: bigint }) => {
297
+ const asset = await fetchASADetails(algorand, holding.assetId);
298
+ resolveAssetImage(asset, resolveImageUrl);
299
+ return { asset, amountRaw: holding.amount.toString() };
300
+ },
301
+ ),
302
+ );
303
+ const spendableAlgo =
304
+ info.amount > info.minBalance ? info.amount - info.minBalance : BigInt(0);
305
+ const holdings =
306
+ spendableAlgo > BigInt(0)
307
+ ? [
308
+ {
309
+ asset: await fetchASADetails(algorand, BigInt(0)),
310
+ amountRaw: spendableAlgo.toString(),
311
+ },
312
+ ...asaHoldings,
313
+ ]
314
+ : asaHoldings;
315
+
316
+ return {
317
+ appId,
318
+ address,
319
+ holdings,
320
+ accountAlgoBalanceRaw: info.amount.toString(),
321
+ };
322
+ } catch {
323
+ // Prize Box metadata is still valuable when an archival node cannot
324
+ // resolve the application account or the box was already withdrawn.
325
+ return fallback;
326
+ }
327
+ }
328
+
329
+ function raffleAuctionRefetchInterval(
330
+ status:
331
+ | RaffleListingType["status"]
332
+ | AuctionListingType["status"]
333
+ | undefined,
334
+ ): number | false {
335
+ if (status === "claimed") return false;
336
+ return status === "ended"
337
+ ? SETTLEMENT_REFETCH_MS
338
+ : ACTIVE_LIFECYCLE_REFETCH_MS;
339
+ }
340
+
341
+ function stakingRefetchInterval(
342
+ status: StakingPoolType["status"] | undefined,
343
+ ): number | false {
344
+ if (status === "ended") return false;
345
+ return status === "draft"
346
+ ? SETTLEMENT_REFETCH_MS
347
+ : ACTIVE_LIFECYCLE_REFETCH_MS;
348
+ }
349
+
350
+ // ---------------------------------------------------------------------------
351
+ // On-chain hooks (algod / indexer)
352
+ // ---------------------------------------------------------------------------
353
+
354
+ export function useAccountData(address: string | undefined) {
355
+ const algorand = useAlgorandClient();
356
+ const { config } = useAlgomd();
357
+ return useQuery({
358
+ queryKey: ["algomd", config.network, "account", address],
359
+ queryFn: async (): Promise<AlgorandAccount> => {
360
+ if (!address) throw new Error("No address provided");
361
+ const info = await algorand.client.algod.accountInformation(address);
362
+ const assets: ASAType[] = (info.assets ?? []).map(
363
+ (a: { assetId: bigint; amount: bigint }) => ({
364
+ id: Number(a.assetId),
365
+ name: `Asset #${a.assetId}`,
366
+ unitName: "",
367
+ total: Number(a.amount),
368
+ decimals: 0,
369
+ defaultFrozen: false,
370
+ creator: "",
371
+ createdAt: new Date(),
372
+ verified: false,
373
+ }),
374
+ );
375
+ const held = (info.assets ?? []).filter(
376
+ (a: { amount: bigint }) => a.amount > BigInt(0),
377
+ );
378
+ return {
379
+ id: address,
380
+ address,
381
+ balance: Number(info.amount),
382
+ assets,
383
+ heldAssetCount: held.length,
384
+ apps: (info.appsLocalState ?? []).map((a: { id: bigint }) => ({
385
+ id: Number(a.id),
386
+ creator: "",
387
+ globalState: {},
388
+ localState: {},
389
+ params: {
390
+ globalNumUint: 0,
391
+ globalNumByteSlice: 0,
392
+ localNumUint: 0,
393
+ localNumByteSlice: 0,
394
+ },
395
+ createdAt: new Date(),
396
+ })),
397
+ createdAt: new Date(),
398
+ isOnline: info.status === "Online",
399
+ round: Number(info.round ?? 0),
400
+ };
401
+ },
402
+ enabled: !!address,
403
+ staleTime: 60_000,
404
+ });
405
+ }
406
+
407
+ export function useASAData(assetId: number | string | undefined) {
408
+ const algorand = useAlgorandClient();
409
+ const { config, resolveImageUrl } = useAlgomd();
410
+ const normalizedAssetId = normalizeAssetId(assetId);
411
+ return useQuery({
412
+ queryKey: ["algomd", config.network, "asa", normalizedAssetId],
413
+ queryFn: async (): Promise<ASAType> => {
414
+ if (normalizedAssetId == null) throw new Error("No asset ID provided");
415
+ const asa = await fetchASADetails(algorand, normalizedAssetId);
416
+ resolveAssetImage(asa, resolveImageUrl);
417
+ return asa;
418
+ },
419
+ enabled: normalizedAssetId != null,
420
+ staleTime: 60_000,
421
+ });
422
+ }
423
+
424
+ /**
425
+ * The collection an asset belongs to, from the Akita backend's
426
+ * `/assets/collections` index. Resolves to null when the asset is in none, and
427
+ * stays idle without a backend URL.
428
+ */
429
+ export function useAssetCollection(
430
+ assetId: number | string | undefined,
431
+ enabled = true,
432
+ ) {
433
+ const { config, resolveImageUrl } = useAlgomd();
434
+ const backendUrl = config.backendUrl?.replace(/\/+$/, "");
435
+ const id = normalizeAssetId(assetId);
436
+ return useQuery({
437
+ queryKey: ["algomd", config.network, "asset-collection", backendUrl, id],
438
+ queryFn: async (): Promise<ASAType["collection"] | null> => {
439
+ const data = await fetchBackendData<{
440
+ assets?: Record<string, string>;
441
+ collections?: Record<string, BackendCollection>;
442
+ }>(backendUrl!, `/assets/collections?ids=${id}`);
443
+ const collectionId = data?.assets?.[String(id)];
444
+ const collection = collectionId ? data.collections?.[collectionId] : undefined;
445
+ if (!collectionId || !collection) return null;
446
+ const mapped = mapCollection(collection, resolveImageUrl, collectionId);
447
+ return { id: mapped.id, name: mapped.name, avatarUrl: mapped.avatarUrl };
448
+ },
449
+ enabled: enabled && !!backendUrl && id != null && Number(id) !== 0,
450
+ staleTime: 10 * 60_000,
451
+ });
452
+ }
453
+
454
+ /**
455
+ * A token's circulating supply (ARC-62, else `total - reserve_balance`), in
456
+ * base units. Stays idle until `enabled`.
457
+ */
458
+ export function useAssetCirculatingSupply(
459
+ asset: ASAType | undefined,
460
+ enabled = true,
461
+ ) {
462
+ const { config } = useAlgomd();
463
+ return useQuery({
464
+ queryKey: ["algomd", config.network, "asset-circulating-supply", asset?.id],
465
+ queryFn: async () => {
466
+ const defaults = NETWORK_DEFAULTS[config.network];
467
+ const algodServer = config.algodServer ?? defaults.algodServer;
468
+ const port = config.algodPort ?? defaults.algodPort;
469
+ const clients = restArc62Clients({
470
+ algodServer: port ? `${algodServer.replace(/\/+$/, "")}:${port}` : algodServer,
471
+ algodToken: config.algodToken ?? defaults.algodToken,
472
+ indexerServer: config.indexerServer ?? defaults.indexerServer,
473
+ indexerToken: config.indexerToken ?? defaults.indexerToken,
474
+ headers: config.headers,
475
+ metadataUrl: assetMetadataUrl(asset!.url, resolveAssetUrl(asset!.url, asset!.reserve)),
476
+ });
477
+ const supply = await fetchCirculatingSupply(
478
+ clients,
479
+ { id: asset!.id, totalRaw: asset!.totalRaw ?? BigInt(Math.trunc(asset!.total)).toString(), reserve: asset!.reserve },
480
+ { network: config.network, sender: asset!.creator || DEFAULT_READER },
481
+ );
482
+ return supply.raw;
483
+ },
484
+ enabled: enabled && !!asset && asset.id !== 0,
485
+ staleTime: 10 * 60_000,
486
+ });
487
+ }
488
+
489
+ /**
490
+ * Recent USD prices for a token's sparkline, from the host's
491
+ * `fetchAssetPriceHistory`. Stays idle when the host supplies none.
492
+ */
493
+ export function useAssetPriceHistory(
494
+ assetId: number | string | undefined,
495
+ enabled = true,
496
+ ) {
497
+ const { config } = useAlgomd();
498
+ const fetchHistory = config.fetchAssetPriceHistory;
499
+ const id = normalizeAssetId(assetId);
500
+ return useQuery({
501
+ queryKey: ["algomd", config.network, "asset-price-history", id],
502
+ queryFn: async () => {
503
+ const points = await fetchHistory!(Number(id));
504
+ return points
505
+ .filter((point) => Number.isFinite(point.time) && Number.isFinite(point.price))
506
+ .sort((a, b) => a.time - b.time);
507
+ },
508
+ enabled: enabled && !!fetchHistory && id != null,
509
+ staleTime: 5 * 60_000,
510
+ });
511
+ }
512
+
513
+ export function useCollectionData(collectionId: number | string | undefined) {
514
+ const { config, resolveImageUrl } = useAlgomd();
515
+ const backendUrl = config.backendUrl?.replace(/\/$/, "");
516
+ const id = collectionId == null ? undefined : String(collectionId);
517
+
518
+ return useQuery({
519
+ queryKey: ["algomd", config.network, "collection", backendUrl, id],
520
+ queryFn: async (): Promise<CollectionType> => {
521
+ if (!backendUrl)
522
+ throw new Error("backendUrl is required to fetch collections");
523
+ if (!id) throw new Error("No collection ID provided");
524
+ const collection = await fetchBackendData<BackendCollection>(
525
+ backendUrl,
526
+ `/collections/${encodeURIComponent(id)}`,
527
+ );
528
+ return mapCollection(collection, resolveImageUrl, id);
529
+ },
530
+ enabled: !!backendUrl && !!id,
531
+ staleTime: 60_000,
532
+ });
533
+ }
534
+
535
+ export function useTransactionData(txId: string | undefined) {
536
+ const indexer = useIndexerClient();
537
+ const { config } = useAlgomd();
538
+ return useQuery({
539
+ queryKey: ["algomd", config.network, "transaction", txId],
540
+ queryFn: async (): Promise<TransactionDetailsType> => {
541
+ if (!txId) throw new Error("No transaction ID provided");
542
+ if (!indexer) throw new Error("Indexer not configured");
543
+ const result = await indexer.lookupTransactionByID(txId).do();
544
+ const txn = result.transaction;
545
+
546
+ const typeMap: Record<string, TransactionDetailsType["type"]> = {
547
+ pay: "payment",
548
+ axfer: "asset-transfer",
549
+ appl: "application-call",
550
+ acfg: "asset-config",
551
+ keyreg: "key-registration",
552
+ afrz: "asset-freeze",
553
+ };
554
+
555
+ // algosdk v3 indexer returns note as Uint8Array, not base64 string
556
+ let note: string | undefined;
557
+ if (txn.note) {
558
+ try {
559
+ note = new TextDecoder().decode(txn.note);
560
+ } catch {
561
+ note = undefined;
562
+ }
563
+ }
564
+
565
+ return {
566
+ id: txId,
567
+ type: typeMap[txn.txType ?? ""] ?? "payment",
568
+ from: txn.sender,
569
+ to:
570
+ txn.paymentTransaction?.receiver ??
571
+ txn.assetTransferTransaction?.receiver,
572
+ amount: Number(
573
+ txn.paymentTransaction?.amount ??
574
+ txn.assetTransferTransaction?.amount ??
575
+ 0,
576
+ ),
577
+ fee: Number(txn.fee),
578
+ round: Number(txn.confirmedRound),
579
+ timestamp: new Date((txn.roundTime ?? 0) * 1000),
580
+ confirmed: !!txn.confirmedRound,
581
+ signature: (() => {
582
+ const sig = txn.signature?.sig;
583
+ if (!sig) return "";
584
+ if (typeof sig === "string") return sig;
585
+ // Convert Uint8Array to base64 without Node Buffer
586
+ return btoa(
587
+ Array.from(sig as Uint8Array, (b: number) =>
588
+ String.fromCharCode(b),
589
+ ).join(""),
590
+ );
591
+ })(),
592
+ note,
593
+ };
594
+ },
595
+ enabled: !!txId && !!indexer,
596
+ staleTime: 120_000,
597
+ });
598
+ }
599
+
600
+ type UnknownRecord = Record<string, unknown>;
601
+
602
+ function asRecord(value: unknown): UnknownRecord {
603
+ return value != null && typeof value === "object" && !Array.isArray(value)
604
+ ? (value as UnknownRecord)
605
+ : {};
606
+ }
607
+
608
+ function scalarString(value: unknown): string | undefined {
609
+ if (typeof value === "string") {
610
+ const trimmed = value.trim();
611
+ return trimmed || undefined;
612
+ }
613
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
614
+ return undefined;
615
+ }
616
+
617
+ function stringList(value: unknown): string[] {
618
+ if (Array.isArray(value)) return value.flatMap(stringList);
619
+ const scalar = scalarString(value);
620
+ return scalar
621
+ ? scalar
622
+ .split(",")
623
+ .map((item) => item.trim())
624
+ .filter(Boolean)
625
+ : [];
626
+ }
627
+
628
+ function normalizeNfdPropertyKey(key: string): string {
629
+ return key.replace(/^[uv]\./, "").replace(/_id$/, "");
630
+ }
631
+
632
+ function nfdField(
633
+ verified: UnknownRecord,
634
+ userDefined: UnknownRecord,
635
+ key: string,
636
+ ): string | undefined {
637
+ const normalized = normalizeNfdPropertyKey(key);
638
+ const candidates = [
639
+ normalized,
640
+ `${normalized}_id`,
641
+ `v.${normalized}`,
642
+ `u.${normalized}`,
643
+ ];
644
+ for (const candidate of candidates) {
645
+ const value = scalarString(verified[candidate]);
646
+ if (value != null) return value;
647
+ }
648
+ for (const candidate of candidates) {
649
+ const value = scalarString(userDefined[candidate]);
650
+ if (value != null) return value;
651
+ }
652
+ return undefined;
653
+ }
654
+
655
+ function mapNfdProperties(
656
+ verified: UnknownRecord,
657
+ userDefined: UnknownRecord,
658
+ ): Record<string, string> {
659
+ const result: Record<string, string> = {};
660
+ for (const source of [userDefined, verified]) {
661
+ for (const [rawKey, rawValue] of Object.entries(source)) {
662
+ const key = normalizeNfdPropertyKey(rawKey);
663
+ if (["avatar", "banner", "bio", "name", "caAlgo"].includes(key)) continue;
664
+ const value = scalarString(rawValue);
665
+ if (value != null) result[key] = value;
666
+ }
667
+ }
668
+ return result;
669
+ }
670
+
671
+ function nfdAvatarUrl(
672
+ value: string | undefined,
673
+ resolveImageUrl: (src: string, width: number) => string,
674
+ ): string | undefined {
675
+ if (!value || !/^(?:https?:\/\/|ipfs:\/\/|data:image\/)/i.test(value))
676
+ return undefined;
677
+ return resolveImageUrl(value, 160);
678
+ }
679
+
680
+ export function useNFDProfileData(name: string | undefined) {
681
+ const { config, resolveImageUrl } = useAlgomd();
682
+ const nfdApiUrl = (config.nfdApiUrl ?? "https://api.nf.domains").replace(
683
+ /\/$/,
684
+ "",
685
+ );
686
+ return useQuery({
687
+ queryKey: ["algomd", config.network, "nfd", nfdApiUrl, name],
688
+ queryFn: async (): Promise<NFDProfileType> => {
689
+ if (!name) throw new Error("No NFD name provided");
690
+ const response = await fetch(
691
+ `${nfdApiUrl}/nfd/${encodeURIComponent(name)}?view=full`,
692
+ );
693
+ if (!response.ok)
694
+ throw new Error(`NFD lookup failed: ${response.status}`);
695
+ const nfd = asRecord(await response.json());
696
+ const properties = asRecord(nfd.properties);
697
+ const verifiedProperties = asRecord(properties.verified);
698
+ const userDefinedProperties = asRecord(properties.userDefined);
699
+ const verifiedAddresses = stringList(verifiedProperties.caAlgo);
700
+ const configuredAddresses = stringList(nfd.caAlgo);
701
+ const canonicalConfiguredAddress = configuredAddresses[0];
702
+ const address =
703
+ canonicalConfiguredAddress ??
704
+ verifiedAddresses[0] ??
705
+ scalarString(nfd.owner) ??
706
+ scalarString(nfd.depositAccount) ??
707
+ "";
708
+ const timeCreated = scalarString(nfd.timeCreated);
709
+ const createdAt = timeCreated ? new Date(timeCreated) : new Date(0);
710
+ const validCreatedAt = Number.isNaN(createdAt.getTime())
711
+ ? new Date(0)
712
+ : createdAt;
713
+ const avatar = nfdAvatarUrl(
714
+ nfdField(verifiedProperties, userDefinedProperties, "avatar"),
715
+ resolveImageUrl,
716
+ );
717
+ return {
718
+ id: scalarString(nfd.appID) ?? scalarString(nfd.appId) ?? name,
719
+ name: scalarString(nfd.name) ?? name,
720
+ address,
721
+ avatar,
722
+ bio: nfdField(verifiedProperties, userDefinedProperties, "bio"),
723
+ properties: mapNfdProperties(verifiedProperties, userDefinedProperties),
724
+ verified:
725
+ canonicalConfiguredAddress != null &&
726
+ verifiedAddresses.includes(canonicalConfiguredAddress),
727
+ createdAt: validCreatedAt,
728
+ };
729
+ },
730
+ enabled: !!name,
731
+ staleTime: 120_000,
732
+ });
733
+ }
734
+
735
+ // ---------------------------------------------------------------------------
736
+ // On-chain contract hooks (via @akita-protocol/sdk typed clients)
737
+ // ---------------------------------------------------------------------------
738
+
739
+ export function usePollData(appIdInput: number | string | undefined) {
740
+ const algorand = useAlgorandClient();
741
+ const { config } = useAlgomd();
742
+ const appId = normalizeAppId(appIdInput);
743
+ return useQuery({
744
+ queryKey: ["algomd", config.network, "poll", appId],
745
+ queryFn: async (): Promise<PollType> => {
746
+ if (!appId) throw new Error("No poll app ID provided");
747
+
748
+ const sdk = new PollSDK({
749
+ algorand,
750
+ factoryParams: { appId: BigInt(appId) },
751
+ });
752
+ const state = await sdk.state();
753
+
754
+ const optionTexts = [
755
+ state.question,
756
+ state.optionOne,
757
+ state.optionTwo,
758
+ state.optionThree,
759
+ state.optionFour,
760
+ state.optionFive,
761
+ ];
762
+ const optionVotes = [
763
+ state.votesOne,
764
+ state.votesTwo,
765
+ state.votesThree,
766
+ state.votesFour,
767
+ state.votesFive,
768
+ ];
769
+ const options: PollOption[] = [];
770
+ const count = Number(state.optionCount);
771
+ for (let i = 0; i < count && i < 5; i++) {
772
+ options.push({
773
+ id: `${i + 1}`,
774
+ text: optionTexts[i + 1] || `Option ${i + 1}`,
775
+ votes: Number(optionVotes[i]),
776
+ votingPower: Number(optionVotes[i]),
777
+ });
778
+ }
779
+
780
+ const endTime = Number(state.endTime);
781
+ const now = Date.now() / 1000;
782
+ const isExpired = endTime > 0 && endTime < now;
783
+ const totalVotes = optionVotes
784
+ .slice(0, count)
785
+ .reduce((sum, v) => sum + Number(v), 0);
786
+
787
+ return {
788
+ id: appId.toString(),
789
+ question: state.question,
790
+ options,
791
+ creator: "",
792
+ createdAt: new Date(),
793
+ expiresAt: endTime > 0 ? new Date(endTime * 1000) : undefined,
794
+ totalVotes,
795
+ status: isExpired ? "ended" : "active",
796
+ gating:
797
+ Number(state.gateId) > 0
798
+ ? {
799
+ type: "asset-holding" as const,
800
+ requirements: {
801
+ assets: [
802
+ { assetId: Number(state.gateId), minimumBalance: 1 },
803
+ ],
804
+ },
805
+ }
806
+ : undefined,
807
+ };
808
+ },
809
+ enabled: appId != null,
810
+ staleTime: 30_000,
811
+ });
812
+ }
813
+
814
+ export function useRaffleData(appIdInput: number | string | undefined) {
815
+ const algorand = useAlgorandClient();
816
+ const { config, resolveImageUrl } = useAlgomd();
817
+ const appId = normalizeAppId(appIdInput);
818
+ return useQuery({
819
+ queryKey: ["algomd", config.network, "raffle", appId],
820
+ queryFn: async (): Promise<RaffleListingType> => {
821
+ if (!appId) throw new Error("No raffle app ID provided");
822
+
823
+ const sdk = new RaffleSDK({
824
+ algorand,
825
+ factoryParams: { appId: BigInt(appId), defaultSender: DEFAULT_READER },
826
+ });
827
+ // SDK 1.4's state() calls send.getState(), which submits a transaction.
828
+ // The display fields all live in global state; read them without signing.
829
+ const state = await sdk.client.state.global.getAll();
830
+ requireStateFields(state, ["prize", "ticketAsset", "startTimestamp", "endTimestamp", "entryCount", "ticketCount", "minTickets", "maxTickets", "gateId", "prizeClaimed", "isPrizeBox"]);
831
+
832
+ const isPrizeBox = state.isPrizeBox > BigInt(0);
833
+ const [prizeAsset, prizeBox, entryAsset] = await Promise.all([
834
+ isPrizeBox
835
+ ? Promise.resolve(undefined)
836
+ : fetchASADetails(algorand, state.prize),
837
+ isPrizeBox
838
+ ? fetchPrizeBoxBundle(algorand, state.prize, resolveImageUrl)
839
+ : Promise.resolve(undefined),
840
+ fetchASADetails(algorand, state.ticketAsset),
841
+ ]);
842
+
843
+ // Resolve image URLs for assets
844
+ if (prizeAsset) resolveAssetImage(prizeAsset, resolveImageUrl);
845
+ resolveAssetImage(entryAsset, resolveImageUrl);
846
+
847
+ const startTs = Number(state.startTimestamp);
848
+ const endTs = Number(state.endTimestamp);
849
+ const now = Date.now() / 1000;
850
+ let status: RaffleListingType["status"];
851
+ if (state.prizeClaimed) status = "claimed";
852
+ else if (startTs > now) status = "upcoming";
853
+ else if (endTs > now) status = "active";
854
+ else status = "ended";
855
+
856
+ // 1 ticket = 1 base unit of the entry asset (e.g. 1 microAlgo for ALGO)
857
+ const entryDecimals = entryAsset.decimals || 0;
858
+ const pricePerEntry = 1 / Math.pow(10, entryDecimals);
859
+
860
+ // Winner is set when raffle is drawn — zero address means no winner yet
861
+ const winner =
862
+ state.winner &&
863
+ state.winner !==
864
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ"
865
+ ? state.winner
866
+ : undefined;
867
+ const participantCount = Number(state.entryCount);
868
+ const totalTicketWeight = Number(state.ticketCount);
869
+ const minTickets = Number(state.minTickets);
870
+ const maxTickets = Number(state.maxTickets);
871
+ const gateAppId = Number(state.gateId);
872
+
873
+ return {
874
+ id: appId.toString(),
875
+ title: `Raffle #${appId}`,
876
+ description: isPrizeBox
877
+ ? `Win a Prize Box bundle with ${entryAsset.unitName || "tokens"}.`
878
+ : `Win ${prizeAsset?.name ?? "the prize"}! Entry costs ${entryAsset.unitName || "tokens"}.`,
879
+ pricePerEntry,
880
+ pricePerEntryRaw: "1",
881
+ entryAsset,
882
+ startTime: new Date(startTs * 1000),
883
+ endTime: new Date(endTs * 1000),
884
+ prizes: prizeAsset
885
+ ? [prizeAsset]
886
+ : (prizeBox?.holdings.map((holding) => holding.asset) ?? []),
887
+ entryCount: participantCount,
888
+ ticketCount: totalTicketWeight,
889
+ participantCount,
890
+ participantCountRaw: state.entryCount.toString(),
891
+ totalTicketWeight,
892
+ totalTicketWeightRaw: state.ticketCount.toString(),
893
+ minTickets,
894
+ maxTickets,
895
+ minTicketsRaw: state.minTickets.toString(),
896
+ maxTicketsRaw: state.maxTickets.toString(),
897
+ gating:
898
+ gateAppId > 0
899
+ ? {
900
+ type: "custom",
901
+ requirements: { custom: { gateAppId } },
902
+ }
903
+ : undefined,
904
+ creator: state.seller ?? "",
905
+ status,
906
+ winner,
907
+ drawStatus: winner
908
+ ? "won"
909
+ : (state.raffleRound ?? BigInt(0)) > BigInt(0) ||
910
+ (state.winningTicket ?? BigInt(0)) > BigInt(0)
911
+ ? "drawing"
912
+ : "waiting",
913
+ prizeClaimed: Boolean(state.prizeClaimed),
914
+ isPrizeBox,
915
+ prizeBoxAppId: prizeBox?.appId,
916
+ prizeBox,
917
+ };
918
+ },
919
+ enabled: appId != null,
920
+ staleTime: 30_000,
921
+ refetchInterval: (query) =>
922
+ raffleAuctionRefetchInterval(query.state.data?.status),
923
+ refetchIntervalInBackground: false,
924
+ });
925
+ }
926
+
927
+ const STAKING_TYPE_MAP: Record<number, StakingPoolStakingType> = {
928
+ 0: "none",
929
+ 10: "heartbeat",
930
+ 20: "soft",
931
+ 30: "hard",
932
+ 40: "lock",
933
+ };
934
+
935
+ const STAKING_DISTRIBUTION_MAP: Record<number, StakingPoolDistributionType> = {
936
+ 10: "percentage",
937
+ 20: "flat",
938
+ 30: "even",
939
+ 40: "shuffle",
940
+ };
941
+
942
+ function optionalTimestamp(timestamp: bigint): Date | undefined {
943
+ return timestamp > BigInt(0) ? new Date(Number(timestamp) * 1000) : undefined;
944
+ }
945
+
946
+ type StakingPoolRootKey = {
947
+ address: string;
948
+ name: string;
949
+ };
950
+
951
+ type StakingPoolGlobalState = {
952
+ status: number;
953
+ title: string;
954
+ type: number;
955
+ signupTimestamp: bigint;
956
+ allowLateSignups: boolean;
957
+ startTimestamp: bigint;
958
+ endTimestamp: bigint;
959
+ maxEntries: bigint;
960
+ entryId: bigint;
961
+ /** Present in legacy app specs, but not maintained by every pool version. */
962
+ totalStaked?: bigint;
963
+ stakeKey: StakingPoolRootKey;
964
+ minimumStakeAmount: bigint;
965
+ gateId: bigint;
966
+ creator: string;
967
+ };
968
+
969
+ async function fetchStakingPoolGlobalState(
970
+ sdk: StakingPoolSDK,
971
+ ): Promise<StakingPoolGlobalState> {
972
+ const appClient = sdk.client.appClient;
973
+ const appState = await appClient.getGlobalState();
974
+
975
+ // Decode only state keys shared by pool versions. This does not invoke the
976
+ // version-specific getState ABI selector, and the cached snapshot prevents a
977
+ // separate algod request for every individual key.
978
+ const readRequired = async (key: string): Promise<unknown> => {
979
+ const value = await appClient.state.global.getValue(key, appState);
980
+ if (value === undefined) {
981
+ throw new Error(`Staking pool global state is missing ${key}`);
982
+ }
983
+ return value;
984
+ };
985
+ const toUint = (value: unknown, key: string): bigint => {
986
+ if (typeof value === "bigint") return value;
987
+ if (
988
+ typeof value === "number" &&
989
+ Number.isSafeInteger(value) &&
990
+ value >= 0
991
+ ) {
992
+ return BigInt(value);
993
+ }
994
+ throw new Error(
995
+ `Staking pool global state ${key} is not an unsigned integer`,
996
+ );
997
+ };
998
+ const readUint = async (key: string): Promise<bigint> =>
999
+ toUint(await readRequired(key), key);
1000
+ const readSmallUint = async (key: string): Promise<number> => {
1001
+ const value = await readUint(key);
1002
+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) {
1003
+ throw new Error(`Staking pool global state ${key} exceeds a safe number`);
1004
+ }
1005
+ return Number(value);
1006
+ };
1007
+ const readString = async (key: string): Promise<string> => {
1008
+ const value = await readRequired(key);
1009
+ if (typeof value !== "string") {
1010
+ throw new Error(`Staking pool global state ${key} is not a string`);
1011
+ }
1012
+ return value;
1013
+ };
1014
+ const readRootKey = async (): Promise<StakingPoolRootKey> => {
1015
+ const value = asRecord(await readRequired("stakeKey"));
1016
+ if (typeof value.address !== "string" || typeof value.name !== "string") {
1017
+ throw new Error("Staking pool global state stakeKey is invalid");
1018
+ }
1019
+ return { address: value.address, name: value.name };
1020
+ };
1021
+ const readOptionalUint = async (key: string): Promise<bigint | undefined> => {
1022
+ const value = await appClient.state.global.getValue(key, appState);
1023
+ return value === undefined ? undefined : toUint(value, key);
1024
+ };
1025
+
1026
+ const hasTotalStaked = Object.prototype.hasOwnProperty.call(
1027
+ appClient.appSpec.state.keys.global,
1028
+ "totalStaked",
1029
+ );
1030
+ const [
1031
+ status,
1032
+ title,
1033
+ type,
1034
+ signupTimestamp,
1035
+ allowLateSignups,
1036
+ startTimestamp,
1037
+ endTimestamp,
1038
+ maxEntries,
1039
+ entryId,
1040
+ totalStaked,
1041
+ stakeKey,
1042
+ minimumStakeAmount,
1043
+ gateId,
1044
+ creator,
1045
+ ] = await Promise.all([
1046
+ readSmallUint("status"),
1047
+ readString("title"),
1048
+ readSmallUint("type"),
1049
+ readUint("signupTimestamp"),
1050
+ readUint("allowLateSignups"),
1051
+ readUint("startTimestamp"),
1052
+ readUint("endTimestamp"),
1053
+ readUint("maxEntries"),
1054
+ readUint("entryID"),
1055
+ hasTotalStaked
1056
+ ? readOptionalUint("totalStaked")
1057
+ : Promise.resolve(undefined),
1058
+ readRootKey(),
1059
+ readUint("minimumStakeAmount"),
1060
+ readUint("gateID"),
1061
+ readString("creator"),
1062
+ ]);
1063
+
1064
+ return {
1065
+ status,
1066
+ title,
1067
+ type,
1068
+ signupTimestamp,
1069
+ allowLateSignups: allowLateSignups > BigInt(0),
1070
+ startTimestamp,
1071
+ endTimestamp,
1072
+ maxEntries,
1073
+ entryId,
1074
+ ...(totalStaked === undefined ? {} : { totalStaked }),
1075
+ stakeKey,
1076
+ minimumStakeAmount,
1077
+ gateId,
1078
+ creator,
1079
+ };
1080
+ }
1081
+
1082
+ async function fetchStakingPoolRewards(
1083
+ sdk: StakingPoolSDK,
1084
+ ): Promise<Map<number, DecodedStakingPoolReward>> {
1085
+ const boxes = await sdk.client.appClient.getBoxValues(({ nameRaw }) =>
1086
+ isStakingPoolRewardBoxName(nameRaw),
1087
+ );
1088
+ const rewards = boxes.map(({ name, value }) =>
1089
+ [
1090
+ decodeStakingPoolRewardBoxId(name.nameRaw),
1091
+ decodeStakingPoolRewardBox(value),
1092
+ ] as const,
1093
+ );
1094
+ rewards.sort(([left], [right]) => left - right);
1095
+
1096
+ const result = new Map<number, DecodedStakingPoolReward>();
1097
+ for (const [id, reward] of rewards) {
1098
+ if (result.has(id)) {
1099
+ throw new Error(`Duplicate staking pool reward box ID ${id}`);
1100
+ }
1101
+ result.set(id, reward);
1102
+ }
1103
+ return result;
1104
+ }
1105
+
1106
+ /**
1107
+ * Each reward's remaining budget. Pools built before budgets existed have no
1108
+ * budget boxes, so their rewards are left without one.
1109
+ */
1110
+ async function fetchStakingPoolBudgets(
1111
+ sdk: StakingPoolSDK,
1112
+ ): Promise<Map<number, bigint>> {
1113
+ try {
1114
+ const boxes = await sdk.client.appClient.getBoxValues(({ nameRaw }) =>
1115
+ isStakingPoolBudgetBoxName(nameRaw),
1116
+ );
1117
+ const result = new Map<number, bigint>();
1118
+ for (const { name, value } of boxes) {
1119
+ const decoded = decodeStakingPoolBudgetBox(name.nameRaw, value);
1120
+ if (decoded) result.set(decoded.rewardId, decoded.budget);
1121
+ }
1122
+ return result;
1123
+ } catch {
1124
+ return new Map();
1125
+ }
1126
+ }
1127
+
1128
+ export function useStakingPoolData(appIdInput: number | string | undefined) {
1129
+ const algorand = useAlgorandClient();
1130
+ const { config, resolveImageUrl } = useAlgomd();
1131
+ const appId = normalizeAppId(appIdInput);
1132
+ return useQuery({
1133
+ queryKey: ["algomd", config.network, "staking-pool", appId],
1134
+ queryFn: async (): Promise<StakingPoolType> => {
1135
+ if (!appId) throw new Error("No staking pool app ID provided");
1136
+
1137
+ const sdk = new StakingPoolSDK({
1138
+ algorand,
1139
+ factoryParams: { appId: BigInt(appId), defaultSender: DEFAULT_READER },
1140
+ });
1141
+ const [state, rewardsMap, budgets] = await Promise.all([
1142
+ fetchStakingPoolGlobalState(sdk),
1143
+ fetchStakingPoolRewards(sdk),
1144
+ fetchStakingPoolBudgets(sdk),
1145
+ ]);
1146
+
1147
+ const rewards = await Promise.all(
1148
+ Array.from(rewardsMap.entries()).map(async ([rewardId, reward]) => {
1149
+ const asset = await fetchASADetails(algorand, reward.asset);
1150
+ resolveAssetImage(asset, resolveImageUrl);
1151
+ return {
1152
+ id: rewardId,
1153
+ asset,
1154
+ distribution:
1155
+ STAKING_DISTRIBUTION_MAP[reward.distribution] ?? "unknown",
1156
+ rate: Number(reward.rate),
1157
+ rateRaw: reward.rate.toString(),
1158
+ expiration: Number(reward.expiration),
1159
+ expirationRaw: reward.expiration.toString(),
1160
+ interval: Number(reward.interval),
1161
+ intervalRaw: reward.interval.toString(),
1162
+ winnerCount: Number(reward.winnerCount),
1163
+ winnerCountRaw: reward.winnerCount.toString(),
1164
+ budgetRaw: budgets.get(rewardId)?.toString(),
1165
+ };
1166
+ }),
1167
+ );
1168
+
1169
+ const signupTime = optionalTimestamp(state.signupTimestamp);
1170
+ const startTime = optionalTimestamp(state.startTimestamp);
1171
+ const endTime = optionalTimestamp(state.endTimestamp);
1172
+ const status = deriveStakingPoolStatus({
1173
+ contractStatus: state.status,
1174
+ signupTimestamp: state.signupTimestamp,
1175
+ startTimestamp: state.startTimestamp,
1176
+ endTimestamp: state.endTimestamp,
1177
+ });
1178
+
1179
+ const stakeKeyName = state.stakeKey.name?.trim();
1180
+ // The contract's entryId global is the authoritative one-based next ID.
1181
+ const entryCountRaw =
1182
+ state.entryId > BigInt(0) ? state.entryId - BigInt(1) : BigInt(0);
1183
+ const rewardCount = rewardsMap.size;
1184
+ return {
1185
+ id: appId.toString(),
1186
+ appId,
1187
+ title: state.title?.trim() || `Staking Pool #${appId}`,
1188
+ description: stakeKeyName
1189
+ ? `Stake ${stakeKeyName} to earn ${rewardCount} reward${rewardCount === 1 ? "" : "s"}.`
1190
+ : undefined,
1191
+ status,
1192
+ stakingType: STAKING_TYPE_MAP[state.type] ?? "unknown",
1193
+ signupTime,
1194
+ startTime,
1195
+ endTime,
1196
+ allowLateSignups: state.allowLateSignups,
1197
+ maxEntries: Number(state.maxEntries),
1198
+ maxEntriesRaw: state.maxEntries.toString(),
1199
+ entryCount: Number(entryCountRaw),
1200
+ entryCountRaw: entryCountRaw.toString(),
1201
+ rewardCount,
1202
+ rewardCountRaw: rewardCount.toString(),
1203
+ // Deployed pool versions do not maintain a trustworthy aggregate.
1204
+ // Individual entry quantities remain authoritative, so do not present
1205
+ // the legacy `totalStaked` state slot as live data.
1206
+ minimumStakeAmount: Number(state.minimumStakeAmount),
1207
+ minimumStakeAmountRaw: state.minimumStakeAmount.toString(),
1208
+ stakeKey:
1209
+ stakeKeyName || state.stakeKey.address
1210
+ ? { address: state.stakeKey.address, name: stakeKeyName ?? "" }
1211
+ : undefined,
1212
+ gateAppId: state.gateId > BigInt(0) ? Number(state.gateId) : undefined,
1213
+ creator: state.creator ?? "",
1214
+ rewards,
1215
+ };
1216
+ },
1217
+ enabled: appId != null,
1218
+ staleTime: 30_000,
1219
+ refetchInterval: (query) =>
1220
+ stakingRefetchInterval(query.state.data?.status),
1221
+ refetchIntervalInBackground: false,
1222
+ });
1223
+ }
1224
+
1225
+ const ZERO_ADDRESS =
1226
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ";
1227
+
1228
+ /** Where the bid-fee raffle stands; undefined when the auction charges no bid fee. */
1229
+ function auctionRaffle(
1230
+ state: {
1231
+ bidFee: bigint;
1232
+ raffleAmount: bigint;
1233
+ raffleWinner: string;
1234
+ rafflePrizeClaimed: boolean;
1235
+ raffleRound: bigint;
1236
+ winningTicket: bigint;
1237
+ },
1238
+ bidCount: number,
1239
+ divisor: number,
1240
+ ): AuctionListingType["raffle"] {
1241
+ if (state.bidFee <= BigInt(0) || bidCount === 0) return undefined;
1242
+ const winner =
1243
+ state.raffleWinner && state.raffleWinner !== ZERO_ADDRESS
1244
+ ? state.raffleWinner
1245
+ : undefined;
1246
+ return {
1247
+ status: state.rafflePrizeClaimed
1248
+ ? "claimed"
1249
+ : winner
1250
+ ? "won"
1251
+ : state.raffleRound > BigInt(0) || state.winningTicket > BigInt(0)
1252
+ ? "drawing"
1253
+ : "waiting",
1254
+ winner,
1255
+ amount: Number(state.raffleAmount) / divisor,
1256
+ amountRaw: state.raffleAmount.toString(),
1257
+ };
1258
+ }
1259
+
1260
+ export function useAuctionData(appIdInput: number | string | undefined) {
1261
+ const algorand = useAlgorandClient();
1262
+ const { config, resolveImageUrl } = useAlgomd();
1263
+ const appId = normalizeAppId(appIdInput);
1264
+ return useQuery({
1265
+ queryKey: ["algomd", config.network, "auction", appId],
1266
+ queryFn: async (): Promise<AuctionListingType> => {
1267
+ if (!appId) throw new Error("No auction app ID provided");
1268
+
1269
+ const sdk = new AuctionSDK({
1270
+ algorand,
1271
+ factoryParams: { appId: BigInt(appId), defaultSender: DEFAULT_READER },
1272
+ });
1273
+ const [state, minimumBidAmount] = await Promise.all([
1274
+ sdk.state(),
1275
+ sdk.getMinimumBidAmount(),
1276
+ ]);
1277
+
1278
+ const isPrizeBox = state.isPrizeBox;
1279
+ const [prizeAsset, prizeBox, bidAsset] = await Promise.all([
1280
+ isPrizeBox
1281
+ ? Promise.resolve(undefined)
1282
+ : fetchASADetails(algorand, state.prize),
1283
+ isPrizeBox
1284
+ ? fetchPrizeBoxBundle(algorand, state.prize, resolveImageUrl)
1285
+ : Promise.resolve(undefined),
1286
+ fetchASADetails(algorand, state.bidAsset),
1287
+ ]);
1288
+
1289
+ // Resolve image URLs for assets
1290
+ if (prizeAsset) resolveAssetImage(prizeAsset, resolveImageUrl);
1291
+ resolveAssetImage(bidAsset, resolveImageUrl);
1292
+
1293
+ const startTs = Number(state.startTimestamp);
1294
+ const endTs = Number(state.endTimestamp);
1295
+ const now = Date.now() / 1000;
1296
+ let status: AuctionListingType["status"];
1297
+ if (state.prizeClaimed) status = "claimed";
1298
+ else if (startTs > now) status = "upcoming";
1299
+ else if (endTs > now) status = "active";
1300
+ else status = "ended";
1301
+
1302
+ const bidDecimals = bidAsset.decimals || 0;
1303
+ const divisor = Math.pow(10, bidDecimals);
1304
+ const bidCountRaw =
1305
+ state.bidID > BigInt(0) ? state.bidID - BigInt(1) : BigInt(0);
1306
+ const bidCount = Number(bidCountRaw);
1307
+
1308
+ // Resolve winner address for ended/claimed auctions with bids
1309
+ let winner: string | undefined;
1310
+ if (status !== "active" && status !== "upcoming" && bidCount > 0) {
1311
+ try {
1312
+ const winningBid = await sdk.getBid({
1313
+ bidId: state.bidID - BigInt(1),
1314
+ });
1315
+ winner = winningBid.account?.toString();
1316
+ } catch {
1317
+ /* box may not be readable */
1318
+ }
1319
+ }
1320
+
1321
+ return {
1322
+ id: appId.toString(),
1323
+ title: `Auction #${appId}`,
1324
+ description: isPrizeBox
1325
+ ? `Bid on a Prize Box bundle with ${bidAsset.unitName || "tokens"}.`
1326
+ : `Bid on ${prizeAsset?.name ?? "the prize"} with ${bidAsset.unitName || "tokens"}.`,
1327
+ bidAsset,
1328
+ currentHighestBid: Number(state.highestBid) / divisor,
1329
+ currentHighestBidRaw: state.highestBid.toString(),
1330
+ minimumNextBid: Number(minimumBidAmount) / divisor,
1331
+ minimumNextBidRaw: minimumBidAmount.toString(),
1332
+ startTime: new Date(startTs * 1000),
1333
+ endTime: new Date(endTs * 1000),
1334
+ prizes: prizeAsset
1335
+ ? [prizeAsset]
1336
+ : (prizeBox?.holdings.map((holding) => holding.asset) ?? []),
1337
+ // The contract takes percentages out of 100_000, so 1_000 is 1%.
1338
+ bidFeePercentage:
1339
+ Number(state.bidFee) > 0 ? Number(state.bidFee) / 1000 : undefined,
1340
+ raffle: auctionRaffle(state, bidCount, divisor),
1341
+ currentBidFeePool: Number(state.raffleAmount) / divisor,
1342
+ currentBidFeePoolRaw: state.raffleAmount.toString(),
1343
+ bidCount,
1344
+ bidCountRaw: bidCountRaw.toString(),
1345
+ timeExtended: false,
1346
+ creator: state.seller ?? "",
1347
+ status,
1348
+ winner,
1349
+ isPrizeBox,
1350
+ prizeBoxAppId: prizeBox?.appId,
1351
+ prizeBox,
1352
+ gating:
1353
+ Number(state.gateId) > 0
1354
+ ? {
1355
+ type: "custom",
1356
+ requirements: {
1357
+ custom: { gateAppId: Number(state.gateId) },
1358
+ },
1359
+ }
1360
+ : undefined,
1361
+ };
1362
+ },
1363
+ enabled: appId != null,
1364
+ staleTime: 30_000,
1365
+ refetchInterval: (query) =>
1366
+ raffleAuctionRefetchInterval(query.state.data?.status),
1367
+ refetchIntervalInBackground: false,
1368
+ });
1369
+ }
1370
+
1371
+ export function useNFTListingData(appIdInput: number | string | undefined) {
1372
+ const algorand = useAlgorandClient();
1373
+ const { config, resolveImageUrl } = useAlgomd();
1374
+ const appId = normalizeAppId(appIdInput);
1375
+ return useQuery({
1376
+ queryKey: ["algomd", config.network, "nftlisting", appId],
1377
+ queryFn: async (): Promise<NFTListingType> => {
1378
+ if (!appId) throw new Error("No NFT listing app ID provided");
1379
+
1380
+ const listing = new ListingSDK({
1381
+ algorand,
1382
+ factoryParams: { appId: BigInt(appId), defaultSender: DEFAULT_READER },
1383
+ });
1384
+ const state = await listing.state();
1385
+ const isPrizeBox = Boolean(state.isPrizeBox);
1386
+
1387
+ const [prizeBox, singleAsset, paymentAsset, gating] = await Promise.all([
1388
+ isPrizeBox
1389
+ ? fetchPrizeBoxBundle(algorand, state.prize, resolveImageUrl)
1390
+ : Promise.resolve(undefined),
1391
+ isPrizeBox
1392
+ ? Promise.resolve(undefined)
1393
+ : fetchASADetails(algorand, Number(state.prize)),
1394
+ fetchASADetails(algorand, Number(state.paymentAsset)),
1395
+ fetchGatingInfo(algorand, config.network, BigInt(state.gateId ?? 0), resolveImageUrl),
1396
+ ]);
1397
+
1398
+ // A bundle's lead asset stands in wherever a single asset is expected (pills, menus).
1399
+ const nftAsset =
1400
+ singleAsset ??
1401
+ prizeBox?.holdings.find((holding) => holding.asset.decimals === 0)?.asset ??
1402
+ prizeBox?.holdings[0]?.asset ?? {
1403
+ id: Number(state.prize),
1404
+ name: "Prize box",
1405
+ unitName: "",
1406
+ total: 0,
1407
+ decimals: 0,
1408
+ defaultFrozen: false,
1409
+ creator: "",
1410
+ createdAt: new Date(0),
1411
+ verified: false,
1412
+ };
1413
+ if (singleAsset) resolveAssetImage(singleAsset, resolveImageUrl);
1414
+
1415
+ const payDecimals = paymentAsset.decimals || 0;
1416
+ const divisor = Math.pow(10, payDecimals);
1417
+
1418
+ return {
1419
+ id: appId.toString(),
1420
+ nft: nftAsset,
1421
+ price: Number(state.price) / divisor,
1422
+ priceAsset: paymentAsset,
1423
+ currency: paymentAsset.unitName || "ALGO",
1424
+ seller: state.seller ?? "",
1425
+ authenticityBadge: false,
1426
+ quantity: 1,
1427
+ reservedFor:
1428
+ state.reservedFor &&
1429
+ state.reservedFor !==
1430
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ"
1431
+ ? state.reservedFor
1432
+ : undefined,
1433
+ gating,
1434
+ isPrizeBox,
1435
+ prizeBoxAppId: prizeBox?.appId,
1436
+ prizeBox,
1437
+ views: 0,
1438
+ favorites: 0,
1439
+ createdAt: new Date(),
1440
+ listedAt: new Date(),
1441
+ expiresAt:
1442
+ Number(state.expiration) > 0
1443
+ ? new Date(Number(state.expiration) * 1000)
1444
+ : undefined,
1445
+ };
1446
+ },
1447
+ enabled: appId != null,
1448
+ staleTime: 60_000,
1449
+ });
1450
+ }
1451
+
1452
+ async function fetchBackendData<T>(
1453
+ backendUrl: string,
1454
+ path: string,
1455
+ ): Promise<T> {
1456
+ const response = await fetch(`${backendUrl}${path}`);
1457
+ const payload = await response.json().catch(() => null);
1458
+ if (!response.ok) {
1459
+ throw new Error(payload?.error || `Request failed with ${response.status}`);
1460
+ }
1461
+ return (
1462
+ payload && typeof payload === "object" && "data" in payload
1463
+ ? payload.data
1464
+ : payload
1465
+ ) as T;
1466
+ }
1467
+
1468
+ function mapCollection(
1469
+ collection: BackendCollection,
1470
+ resolveImageUrl: (src: string, width: number, quality?: number) => string,
1471
+ fallbackId: string,
1472
+ ): CollectionType {
1473
+ const id = String(collection.id ?? collection.collection_id ?? fallbackId);
1474
+ const avatarValue = collection.avatar_url ?? collection.avatar;
1475
+ const avatarUrl =
1476
+ typeof avatarValue === "string" &&
1477
+ avatarValue.trim() &&
1478
+ !/^\d+$/.test(avatarValue)
1479
+ ? resolveImageUrl(avatarValue, 320)
1480
+ : undefined;
1481
+
1482
+ return {
1483
+ id,
1484
+ nfdId: collection.nfd_id,
1485
+ name: collection.name?.trim() || `Collection ${id}`,
1486
+ description: collection.description?.trim() || undefined,
1487
+ avatar: collection.avatar ?? undefined,
1488
+ avatarUrl,
1489
+ avatarMime: collection.avatar_mime ?? undefined,
1490
+ banner: collection.banner ?? undefined,
1491
+ network: collection.network ?? undefined,
1492
+ explicit: collection.explicit,
1493
+ prefixes: collection.prefixes,
1494
+ artists: collection.artists,
1495
+ };
1496
+ }
1497
+
1498
+ export function useTradeOfferData(
1499
+ appId: number | undefined,
1500
+ offerId: number | undefined,
1501
+ ) {
1502
+ const algorand = useAlgorandClient();
1503
+ const { config } = useAlgomd();
1504
+ return useQuery({
1505
+ queryKey: ["algomd", config.network, "trade", appId, offerId],
1506
+ queryFn: async (): Promise<TradeOfferType> => {
1507
+ if (appId == null || offerId == null)
1508
+ throw new Error("No trade offer ID provided");
1509
+
1510
+ const sdk = new HyperSwapSDK({
1511
+ algorand,
1512
+ factoryParams: { appId: BigInt(appId), defaultSender: DEFAULT_READER },
1513
+ });
1514
+ const offer = await sdk.getOffer({ id: BigInt(offerId) });
1515
+
1516
+ const stateMap: Record<number, TradeOfferType["status"]> = {
1517
+ 10: "pending", // Offered
1518
+ 20: "pending", // Escrowing
1519
+ 30: "pending", // Disbursing
1520
+ 40: "accepted", // Completed
1521
+ 50: "expired", // Cancelled
1522
+ 60: "expired", // CancelCompleted
1523
+ };
1524
+
1525
+ return {
1526
+ id: offerId.toString(),
1527
+ creator: "",
1528
+ recipients: [],
1529
+ offering: [],
1530
+ requesting: [],
1531
+ expiresAt: new Date(Number(offer.expiration) * 1000),
1532
+ status: stateMap[offer.state] ?? "pending",
1533
+ createdAt: new Date(),
1534
+ };
1535
+ },
1536
+ enabled: appId != null && offerId != null,
1537
+ staleTime: 60_000,
1538
+ });
1539
+ }