@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,181 @@
1
+ /**
2
+ * Format an Algorand address for display (truncated).
3
+ */
4
+ export function formatAddress(address: string, chars = 5): string {
5
+ if (address.length <= chars * 2) return address;
6
+ return `${address.slice(0, chars)}...${address.slice(-chars)}`;
7
+ }
8
+
9
+ /**
10
+ * Format a number with locale-aware separators.
11
+ */
12
+ export function formatNumber(num: number, decimals = 2): string {
13
+ return new Intl.NumberFormat("en-US", {
14
+ minimumFractionDigits: 0,
15
+ maximumFractionDigits: decimals,
16
+ }).format(num);
17
+ }
18
+
19
+ /**
20
+ * Format a currency value with its unit.
21
+ */
22
+ export function formatCurrency(amount: number, currency = "ALGO"): string {
23
+ return `${formatNumber(amount)} ${currency}`;
24
+ }
25
+
26
+ /**
27
+ * Format a date into a readable string.
28
+ */
29
+ export function formatDate(date: Date): string {
30
+ return new Intl.DateTimeFormat("en-US", {
31
+ year: "numeric",
32
+ month: "short",
33
+ day: "numeric",
34
+ hour: "2-digit",
35
+ minute: "2-digit",
36
+ }).format(date);
37
+ }
38
+
39
+ /**
40
+ * Format a date into a human-readable relative time string.
41
+ */
42
+ export function formatRelativeTime(date: Date): string {
43
+ const now = new Date();
44
+ const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
45
+
46
+ if (diffInSeconds < 0) {
47
+ // Future date
48
+ const absDiff = Math.abs(diffInSeconds);
49
+ if (absDiff < 60) return "in a moment";
50
+ if (absDiff < 3600) return `in ${Math.floor(absDiff / 60)}m`;
51
+ if (absDiff < 86400) return `in ${Math.floor(absDiff / 3600)}h`;
52
+ if (absDiff < 2592000) return `in ${Math.floor(absDiff / 86400)}d`;
53
+ return formatDate(date);
54
+ }
55
+
56
+ if (diffInSeconds < 60) return "just now";
57
+ if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}m ago`;
58
+ if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}h ago`;
59
+ if (diffInSeconds < 2592000)
60
+ return `${Math.floor(diffInSeconds / 86400)}d ago`;
61
+
62
+ return formatDate(date);
63
+ }
64
+
65
+ /**
66
+ * Format an asset amount considering its decimals.
67
+ */
68
+ export function formatAssetAmount(amount: number, decimals: number): string {
69
+ const divisor = Math.pow(10, decimals);
70
+ return formatNumber(amount / divisor, Math.min(decimals, 6));
71
+ }
72
+
73
+ /**
74
+ * Format an exact raw uint64 amount without converting through `number`.
75
+ *
76
+ * This preserves small values for high-decimal assets (for example one
77
+ * microAlgo renders as `0.000001`, never `0`) and avoids precision loss for
78
+ * large on-chain counters.
79
+ */
80
+ export function formatBaseUnitAmount(
81
+ amount: bigint | string | number,
82
+ decimals = 0,
83
+ ): string {
84
+ const safeDecimals = Number.isInteger(decimals)
85
+ ? Math.max(0, Math.min(19, decimals))
86
+ : 0;
87
+ let raw: bigint;
88
+
89
+ try {
90
+ if (typeof amount === "number") {
91
+ if (!Number.isSafeInteger(amount)) return String(amount);
92
+ raw = BigInt(amount);
93
+ } else {
94
+ const value = typeof amount === "string" ? amount.trim() : amount;
95
+ if (value === "") return "0";
96
+ raw = BigInt(value);
97
+ }
98
+ } catch {
99
+ return "0";
100
+ }
101
+
102
+ const negative = raw < BigInt(0);
103
+ const absolute = negative ? -raw : raw;
104
+ const divisor = BigInt(10) ** BigInt(safeDecimals);
105
+ const whole = absolute / divisor;
106
+ const groupedWhole = whole.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
107
+ if (safeDecimals === 0) return `${negative ? "-" : ""}${groupedWhole}`;
108
+
109
+ const fraction = (absolute % divisor)
110
+ .toString()
111
+ .padStart(safeDecimals, "0")
112
+ .replace(/0+$/, "");
113
+ return `${negative ? "-" : ""}${groupedWhole}${fraction ? `.${fraction}` : ""}`;
114
+ }
115
+
116
+ const DURATION_UNITS = [
117
+ { seconds: BigInt(31_536_000), label: "year" },
118
+ { seconds: BigInt(2_592_000), label: "month" },
119
+ { seconds: BigInt(604_800), label: "week" },
120
+ { seconds: BigInt(86_400), label: "day" },
121
+ { seconds: BigInt(3_600), label: "hour" },
122
+ { seconds: BigInt(60), label: "minute" },
123
+ { seconds: BigInt(1), label: "second" },
124
+ ] as const;
125
+
126
+ /** Format an exact duration in seconds without converting through `number`. */
127
+ export function formatDurationSeconds(
128
+ duration: bigint | string | number,
129
+ maxParts = 2,
130
+ ): string {
131
+ let remaining: bigint;
132
+ try {
133
+ if (typeof duration === "number" && !Number.isSafeInteger(duration)) {
134
+ return "Unknown duration";
135
+ }
136
+ const value = typeof duration === "string" ? duration.trim() : duration;
137
+ if (value === "") return "Unknown duration";
138
+ remaining = BigInt(value);
139
+ } catch {
140
+ return "Unknown duration";
141
+ }
142
+
143
+ if (remaining < BigInt(0)) return "Unknown duration";
144
+ if (remaining === BigInt(0)) return "0 seconds";
145
+
146
+ const partLimit = Number.isFinite(maxParts)
147
+ ? Math.max(1, Math.floor(maxParts))
148
+ : 2;
149
+ const parts: string[] = [];
150
+ for (const unit of DURATION_UNITS) {
151
+ if (remaining < unit.seconds) continue;
152
+ const count = remaining / unit.seconds;
153
+ remaining %= unit.seconds;
154
+ parts.push(
155
+ `${count.toString()} ${unit.label}${count === BigInt(1) ? "" : "s"}`,
156
+ );
157
+ if (parts.length >= partLimit) break;
158
+ }
159
+
160
+ return parts.join(" ");
161
+ }
162
+
163
+ /**
164
+ * Like formatBaseUnitAmount, but whole parts of a million or more collapse to 1.2M / 3.4B / 18.4T
165
+ * so huge balances stay readable in a card. Exact values stay available through formatBaseUnitAmount.
166
+ */
167
+ export function formatCompactBaseUnitAmount(
168
+ amount: bigint | string | number,
169
+ decimals = 0,
170
+ ): string {
171
+ const exact = formatBaseUnitAmount(amount, decimals);
172
+ const whole = exact.split(".")[0].replace(/[-,]/g, "");
173
+ if (whole.length < 7) return exact;
174
+ const units = ["M", "B", "T", "Q"];
175
+ const group = Math.min(units.length - 1, Math.floor((whole.length - 7) / 3));
176
+ const shift = 6 + group * 3;
177
+ const head = whole.slice(0, whole.length - shift);
178
+ const tenth = whole.charAt(whole.length - shift);
179
+ const sign = exact.startsWith("-") ? "-" : "";
180
+ return `${sign}${head}${tenth !== "0" && head.length < 3 ? `.${tenth}` : ""}${units[group]}`;
181
+ }
@@ -0,0 +1,31 @@
1
+ /** Normalize a persisted application ID without accepting lossy JS numbers. */
2
+ export function normalizeAppId(
3
+ value: number | string | undefined,
4
+ ): number | undefined {
5
+ if (value == null) return undefined;
6
+
7
+ if (typeof value === "number") {
8
+ return Number.isSafeInteger(value) && value > 0 ? value : undefined;
9
+ }
10
+
11
+ const normalized = value.trim();
12
+ if (!/^\d+$/.test(normalized)) return undefined;
13
+ const parsed = Number(normalized);
14
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
15
+ }
16
+
17
+ /** Normalize an asset ID, including native ALGO's asset ID 0. */
18
+ export function normalizeAssetId(
19
+ value: number | string | undefined,
20
+ ): number | undefined {
21
+ if (value == null) return undefined;
22
+
23
+ if (typeof value === "number") {
24
+ return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
25
+ }
26
+
27
+ const normalized = value.trim();
28
+ if (!/^\d+$/.test(normalized)) return undefined;
29
+ const parsed = Number(normalized);
30
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : undefined;
31
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./format";
2
+ export * from "./ids";
3
+ export * from "./capacity";
4
+ export * from "./stakingPool";
5
+ export * from "./search";
6
+ export * from "./arc19";
@@ -0,0 +1,45 @@
1
+ const NAMESPACED_NFD_SUFFIXES = [
2
+ "eth",
3
+ "sol",
4
+ "icp",
5
+ "btc",
6
+ "base",
7
+ "arb",
8
+ "op",
9
+ "bnb",
10
+ "avax",
11
+ "sui",
12
+ "apt",
13
+ "near",
14
+ "cosmos",
15
+ "atom",
16
+ "tez",
17
+ "xtz",
18
+ "com",
19
+ "net",
20
+ "org",
21
+ "io",
22
+ "app",
23
+ "xyz",
24
+ "dev",
25
+ "fi",
26
+ "ai",
27
+ ]
28
+
29
+ export function shouldAlwaysShowNfdAlgoSuffix(nfdName: string): boolean {
30
+ const normalizedName = nfdName.trim().toLowerCase()
31
+ if (!normalizedName.endsWith(".algo")) return true
32
+
33
+ const withoutAlgo = normalizedName.slice(0, -".algo".length)
34
+
35
+ return NAMESPACED_NFD_SUFFIXES.includes(withoutAlgo)
36
+ }
37
+
38
+ export function formatNfdName(nfdName: string, options?: { showNfdSuffix?: boolean }): string {
39
+ const trimmedName = nfdName.trim()
40
+ if (options?.showNfdSuffix || shouldAlwaysShowNfdAlgoSuffix(trimmedName)) {
41
+ return trimmedName
42
+ }
43
+ return trimmedName.slice(0, -".algo".length)
44
+ }
45
+
@@ -0,0 +1,87 @@
1
+ import type {
2
+ SearchResult,
3
+ SearchableEntity,
4
+ AlgorandAccount,
5
+ NFDProfile,
6
+ ASA,
7
+ Application,
8
+ } from '../types/algorand';
9
+
10
+ /**
11
+ * Simple fuzzy search across Algorand entity collections.
12
+ */
13
+ export function searchEntities<T extends SearchableEntity>(
14
+ entities: T[],
15
+ query: string,
16
+ maxResults = 10,
17
+ ): SearchResult<T>[] {
18
+ if (!query.trim()) return [];
19
+
20
+ const queryLower = query.trim().toLowerCase();
21
+ const results: SearchResult<T>[] = [];
22
+
23
+ for (const entity of entities) {
24
+ const matches: string[] = [];
25
+ let score = 0;
26
+
27
+ if ('address' in entity) {
28
+ const account = entity as unknown as AlgorandAccount;
29
+ if (account.address.toLowerCase().includes(queryLower)) {
30
+ matches.push('address');
31
+ score += account.address.toLowerCase().startsWith(queryLower) ? 10 : 5;
32
+ }
33
+ }
34
+
35
+ if ('name' in entity) {
36
+ const named = entity as unknown as NFDProfile | ASA;
37
+ if (named.name.toLowerCase().includes(queryLower)) {
38
+ matches.push('name');
39
+ score += named.name.toLowerCase().startsWith(queryLower) ? 10 : 5;
40
+ }
41
+ }
42
+
43
+ if ('unitName' in entity) {
44
+ const asa = entity as unknown as ASA;
45
+ if (asa.unitName.toLowerCase().includes(queryLower)) {
46
+ matches.push('unitName');
47
+ score += asa.unitName.toLowerCase().startsWith(queryLower) ? 8 : 4;
48
+ }
49
+ }
50
+
51
+ if ('description' in entity && (entity as unknown as Application).description) {
52
+ const app = entity as unknown as Application;
53
+ if (app.description && app.description.toLowerCase().includes(queryLower)) {
54
+ matches.push('description');
55
+ score += 2;
56
+ }
57
+ }
58
+
59
+ // Each search component supplies a different entity shape. Include the
60
+ // fields visible in its result row, including nested NFT/trade assets.
61
+ const addMatch = (field: string, value: unknown, weight = 5) => {
62
+ if (typeof value !== 'string' && typeof value !== 'number') return;
63
+ const text = String(value).toLowerCase();
64
+ if (!text.includes(queryLower)) return;
65
+ matches.push(field);
66
+ score += text === queryLower ? weight * 3 : text.startsWith(queryLower) ? weight * 2 : weight;
67
+ };
68
+ addMatch('id', entity.id);
69
+ for (const field of ['question', 'title', 'note', 'message', 'from', 'to', 'creator'] as const) {
70
+ if (field in entity) addMatch(field, entity[field as keyof typeof entity]);
71
+ }
72
+ if ('recipients' in entity) entity.recipients.forEach(address => addMatch('recipients', address));
73
+ const nested = 'nft' in entity ? [entity.nft] : 'offering' in entity ? [...entity.offering, ...entity.requesting] : [];
74
+ for (const item of nested) {
75
+ addMatch('item.id', item.id);
76
+ if ('name' in item) addMatch('item.name', item.name);
77
+ if ('unitName' in item) addMatch('item.unitName', item.unitName);
78
+ if ('address' in item) addMatch('item.address', item.address);
79
+ }
80
+
81
+ if (score > 0) {
82
+ results.push({ item: entity, score, matches });
83
+ }
84
+ }
85
+
86
+ return results.sort((a, b) => b.score - a.score).slice(0, maxResults);
87
+ }
@@ -0,0 +1,174 @@
1
+ import { ABIType } from "algosdk";
2
+ import type { StakingPoolStatus } from "../types/algorand";
3
+
4
+ const REWARD_BOX_PREFIX = "r".charCodeAt(0);
5
+
6
+ const LEGACY_REWARD_ABI = ABIType.from(
7
+ "(uint64,uint8,uint64,uint64,uint64,uint64,uint64,uint64,uint64[],(uint64,uint64,uint64),uint64,uint8,uint64,uint64,uint64,uint64)",
8
+ );
9
+
10
+ const ROYALTY_REWARD_ABI = ABIType.from(
11
+ "(uint64,uint8,uint64,uint64,uint64,uint64,uint64,uint64,uint64,uint64[],(uint64,uint64,uint64),uint64,uint8,uint64,uint64,uint64,uint64)",
12
+ );
13
+
14
+ export type StakingPoolRewardLayout = "legacy" | "royalty";
15
+
16
+ /** Stable reward fields used by the renderer across deployed box layouts. */
17
+ export interface DecodedStakingPoolReward {
18
+ layout: StakingPoolRewardLayout;
19
+ asset: bigint;
20
+ distribution: number;
21
+ /** Configured gross rate before the protocol royalty is deducted. */
22
+ rate: bigint;
23
+ expiration: bigint;
24
+ interval: bigint;
25
+ /** Only stored by the royalty-aware reward layout. */
26
+ royaltyAmount?: bigint;
27
+ winnerCount: bigint;
28
+ }
29
+
30
+ function asUint(value: unknown, field: string): bigint {
31
+ if (typeof value === "bigint") return value;
32
+ if (
33
+ typeof value === "number" &&
34
+ Number.isSafeInteger(value) &&
35
+ value >= 0
36
+ ) {
37
+ return BigInt(value);
38
+ }
39
+ throw new Error(`Staking pool reward ${field} is not an unsigned integer`);
40
+ }
41
+
42
+ function asSmallUint(value: unknown, field: string): number {
43
+ const decoded = asUint(value, field);
44
+ if (decoded > BigInt(Number.MAX_SAFE_INTEGER)) {
45
+ throw new Error(`Staking pool reward ${field} exceeds a safe number`);
46
+ }
47
+ return Number(decoded);
48
+ }
49
+
50
+ function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {
51
+ if (left.length !== right.length) return false;
52
+ return left.every((value, index) => value === right[index]);
53
+ }
54
+
55
+ function decodeRewardLayout(
56
+ value: Uint8Array,
57
+ layout: StakingPoolRewardLayout,
58
+ ): DecodedStakingPoolReward | undefined {
59
+ const codec = layout === "royalty" ? ROYALTY_REWARD_ABI : LEGACY_REWARD_ABI;
60
+ try {
61
+ const tuple = codec.decode(value);
62
+ if (!Array.isArray(tuple) || !bytesEqual(codec.encode(tuple), value)) {
63
+ return undefined;
64
+ }
65
+
66
+ const royaltyAware = layout === "royalty";
67
+ const royaltyAmount = royaltyAware
68
+ ? asUint(tuple[7], "royaltyAmount")
69
+ : undefined;
70
+ const winnerCountIndex = royaltyAware ? 8 : 7;
71
+ return {
72
+ layout,
73
+ asset: asUint(tuple[0], "asset"),
74
+ distribution: asSmallUint(tuple[1], "distribution"),
75
+ rate: asUint(tuple[2], "rate"),
76
+ expiration: asUint(tuple[3], "expiration"),
77
+ interval: asUint(tuple[4], "interval"),
78
+ ...(royaltyAmount === undefined ? {} : { royaltyAmount }),
79
+ winnerCount: asUint(tuple[winnerCountIndex], "winnerCount"),
80
+ };
81
+ } catch {
82
+ return undefined;
83
+ }
84
+ }
85
+
86
+ /** Budget boxes ('b' + reward ID) hold how much of the reward asset is still reserved for it. */
87
+ const BUDGET_BOX_PREFIX = 0x62;
88
+
89
+ export function isStakingPoolBudgetBoxName(name: Uint8Array): boolean {
90
+ return name.length === 9 && name[0] === BUDGET_BOX_PREFIX;
91
+ }
92
+
93
+ function readUint64(bytes: Uint8Array): bigint {
94
+ let value = BigInt(0);
95
+ for (const byte of bytes) value = (value << BigInt(8)) | BigInt(byte);
96
+ return value;
97
+ }
98
+
99
+ /** Reward ID and remaining budget from a budget box; undefined when the box isn't one. */
100
+ export function decodeStakingPoolBudgetBox(
101
+ name: Uint8Array,
102
+ value: Uint8Array,
103
+ ): { rewardId: number; budget: bigint } | undefined {
104
+ if (!isStakingPoolBudgetBoxName(name) || value.length !== 8) return undefined;
105
+ const id = readUint64(name.slice(1));
106
+ if (id > BigInt(Number.MAX_SAFE_INTEGER)) return undefined;
107
+ return { rewardId: Number(id), budget: readUint64(value) };
108
+ }
109
+
110
+ export function isStakingPoolRewardBoxName(name: Uint8Array): boolean {
111
+ return name.length === 9 && name[0] === REWARD_BOX_PREFIX;
112
+ }
113
+
114
+ export function decodeStakingPoolRewardBoxId(name: Uint8Array): number {
115
+ if (!isStakingPoolRewardBoxName(name)) {
116
+ throw new Error("Invalid staking pool reward box name");
117
+ }
118
+
119
+ let id = BigInt(0);
120
+ for (const byte of name.slice(1)) {
121
+ id = (id << BigInt(8)) | BigInt(byte);
122
+ }
123
+ if (id > BigInt(Number.MAX_SAFE_INTEGER)) {
124
+ throw new Error("Staking pool reward ID exceeds a safe number");
125
+ }
126
+ return Number(id);
127
+ }
128
+
129
+ /** Decode either deployed Reward struct without relying on the installed SDK spec. */
130
+ export function decodeStakingPoolRewardBox(
131
+ value: Uint8Array,
132
+ ): DecodedStakingPoolReward {
133
+ const decoded = (["royalty", "legacy"] as const).flatMap((layout) => {
134
+ const reward = decodeRewardLayout(value, layout);
135
+ return reward ? [reward] : [];
136
+ });
137
+
138
+ if (decoded.length === 1) return decoded[0];
139
+ if (decoded.length > 1) {
140
+ throw new Error("Ambiguous staking pool reward box layout");
141
+ }
142
+ throw new Error(
143
+ `Unsupported staking pool reward box layout (${value.length} bytes)`,
144
+ );
145
+ }
146
+
147
+ export interface StakingPoolLifecycle {
148
+ contractStatus: number;
149
+ signupTimestamp: bigint;
150
+ startTimestamp: bigint;
151
+ endTimestamp: bigint;
152
+ nowTimestamp?: bigint;
153
+ }
154
+
155
+ /**
156
+ * Derive a display lifecycle from the pool's exact on-chain timestamps.
157
+ *
158
+ * Contract status 0 is draft and 10 is final. A final pool is active through
159
+ * its end timestamp (inclusive), matching the contract's `isLive` check.
160
+ */
161
+ export function deriveStakingPoolStatus({
162
+ contractStatus,
163
+ signupTimestamp,
164
+ startTimestamp,
165
+ endTimestamp,
166
+ nowTimestamp = BigInt(Math.floor(Date.now() / 1000)),
167
+ }: StakingPoolLifecycle): StakingPoolStatus {
168
+ if (contractStatus === 0) return "draft";
169
+ if (contractStatus !== 10) return "unknown";
170
+ if (endTimestamp > BigInt(0) && nowTimestamp > endTimestamp) return "ended";
171
+ if (nowTimestamp >= startTimestamp) return "active";
172
+ if (nowTimestamp < signupTimestamp) return "upcoming";
173
+ return "signups";
174
+ }
@@ -0,0 +1,132 @@
1
+ import type {
2
+ StakingPoolDisplayData,
3
+ StakingPoolRewardDisplayData,
4
+ StakingPoolStatus,
5
+ } from "../presentation/StakingPoolDisplay"
6
+
7
+ function snapshotBoolean(value: string | undefined): boolean | undefined {
8
+ if (value == null) return undefined
9
+ if (value === "true" || value === "1") return true
10
+ if (value === "false" || value === "0") return false
11
+ return undefined
12
+ }
13
+
14
+ function snapshotNumber(value: string | undefined): number | undefined {
15
+ if (!value || !/^\d+$/.test(value)) return undefined
16
+ const parsed = Number(value)
17
+ return Number.isSafeInteger(parsed) ? parsed : undefined
18
+ }
19
+
20
+ function snapshotUint(value: string | undefined): string | undefined {
21
+ return value && /^\d+$/.test(value) ? value : undefined
22
+ }
23
+
24
+ function snapshotDate(value: string | undefined): Date | undefined {
25
+ const seconds = snapshotNumber(value)
26
+ return seconds && seconds > 0 ? new Date(seconds * 1000) : undefined
27
+ }
28
+
29
+ export function deriveStakingPoolStatus(
30
+ input: {
31
+ finalized?: boolean
32
+ signupTime?: Date
33
+ startTime?: Date
34
+ endTime?: Date
35
+ },
36
+ nowMs = Date.now(),
37
+ ): StakingPoolStatus {
38
+ if (input.finalized === false) return "draft"
39
+ if (!input.finalized) return "unknown"
40
+
41
+ if (input.endTime && input.endTime.getTime() <= nowMs) return "ended"
42
+ if (input.startTime && input.startTime.getTime() <= nowMs) return "active"
43
+ if (input.signupTime && input.signupTime.getTime() <= nowMs) return "signups"
44
+ if (input.signupTime || input.startTime) return "upcoming"
45
+ return "final"
46
+ }
47
+
48
+ function rewardFromProps(props: Record<string, string>): StakingPoolRewardDisplayData | undefined {
49
+ const assetId = snapshotUint(props.primaryRewardAssetId)
50
+ const rateRaw = snapshotUint(props.primaryRewardRateRaw)
51
+ const amountRaw = snapshotUint(props.primaryRewardAmountRaw)
52
+ if (!assetId && !rateRaw && !amountRaw && !props.primaryRewardName) return undefined
53
+
54
+ return {
55
+ assetId,
56
+ name: props.primaryRewardName,
57
+ unitName: props.primaryRewardUnitName,
58
+ decimals: snapshotNumber(props.primaryRewardDecimals),
59
+ amountRaw,
60
+ rateRaw,
61
+ distribution: props.primaryRewardDistribution,
62
+ intervalSecondsRaw: snapshotUint(props.primaryRewardIntervalSecondsRaw),
63
+ expirationSecondsRaw: snapshotUint(props.primaryRewardExpirationSecondsRaw),
64
+ winnerCountRaw: snapshotUint(props.primaryRewardWinnerCountRaw),
65
+ }
66
+ }
67
+
68
+ export function stakingSnapshotFromProps(
69
+ props: Record<string, string>,
70
+ appId: string,
71
+ nowMs = Date.now(),
72
+ ): StakingPoolDisplayData | undefined {
73
+ const hasSnapshot = [
74
+ props.title,
75
+ props.stakingType,
76
+ props.poolType,
77
+ props.minimumStakeAmount,
78
+ props.minimumStakeAmountRaw,
79
+ props.maxEntries,
80
+ props.maxEntriesRaw,
81
+ props.status,
82
+ props.finalized,
83
+ props.signupTimestamp,
84
+ props.primaryRewardRateRaw,
85
+ ].some(Boolean)
86
+ if (!hasSnapshot) return undefined
87
+
88
+ const signupTime = snapshotDate(props.signupTimestamp)
89
+ const startTime = snapshotDate(props.startTimestamp)
90
+ const endTime = snapshotDate(props.endTimestamp)
91
+ const explicitFinalized = snapshotBoolean(props.finalized)
92
+ const legacyStatus = props.status?.toLowerCase()
93
+ const finalized =
94
+ explicitFinalized ??
95
+ (legacyStatus === "draft" || legacyStatus === "0" ? false : legacyStatus ? true : undefined)
96
+ const derivedStatus = deriveStakingPoolStatus(
97
+ { finalized, signupTime, startTime, endTime },
98
+ nowMs,
99
+ )
100
+ const status: StakingPoolStatus =
101
+ derivedStatus !== "unknown"
102
+ ? derivedStatus
103
+ : legacyStatus === "upcoming" ||
104
+ legacyStatus === "signups" ||
105
+ legacyStatus === "active" ||
106
+ legacyStatus === "ended" ||
107
+ legacyStatus === "final"
108
+ ? legacyStatus
109
+ : "unknown"
110
+
111
+ return {
112
+ id: appId,
113
+ title: props.title || `Staking Pool #${appId}`,
114
+ status,
115
+ finalized,
116
+ poolType: props.stakingType || props.poolType,
117
+ signupTime,
118
+ startTime,
119
+ endTime,
120
+ minimumStakeAmount: props.minimumStakeAmountRaw || props.minimumStakeAmount,
121
+ totalStaked: props.totalStaked,
122
+ maxEntries: snapshotNumber(props.maxEntriesRaw || props.maxEntries),
123
+ entryCount: snapshotNumber(props.entryCount),
124
+ allowLateSignups: snapshotBoolean(props.allowLateSignups),
125
+ unrestricted: snapshotBoolean(props.unrestricted),
126
+ gateId: snapshotNumber(props.gateId),
127
+ stakeDecimals: snapshotNumber(props.stakeDecimals),
128
+ stakeUnitName: props.stakeUnitName || props.unitName,
129
+ rewardCount: snapshotNumber(props.rewardCount),
130
+ primaryReward: rewardFromProps(props),
131
+ }
132
+ }