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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) 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 +268 -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/HostRefs.tsx +82 -0
  104. package/src/refs/ListingRef.tsx +90 -0
  105. package/src/refs/NfdRef.tsx +96 -0
  106. package/src/refs/PollRef.tsx +120 -0
  107. package/src/refs/RaffleRef.tsx +101 -0
  108. package/src/refs/RewardRef.tsx +78 -0
  109. package/src/refs/StakingPoolRef.tsx +136 -0
  110. package/src/refs/SubscriptionRef.tsx +200 -0
  111. package/src/refs/TradeRef.tsx +100 -0
  112. package/src/refs/TransactionRef.tsx +156 -0
  113. package/src/refs/assetInfo.ts +49 -0
  114. package/src/refs/contractParts.tsx +159 -0
  115. package/src/refs/index.tsx +137 -0
  116. package/src/refs/primitives.tsx +588 -0
  117. package/src/refs/types.ts +13 -0
  118. package/src/types/algorand.ts +496 -0
  119. package/src/types/index.ts +1 -0
  120. package/src/ui/CopyButton.tsx +44 -0
  121. package/src/ui/DataStates.tsx +45 -0
  122. package/src/ui/ProgressBar.tsx +64 -0
  123. package/src/ui/SearchSheet.tsx +141 -0
  124. package/src/ui/SizeContainer.tsx +25 -0
  125. package/src/ui/StatusBadge.tsx +51 -0
  126. package/src/ui/index.ts +6 -0
  127. package/src/utils/algomdImageUrl.ts +20 -0
  128. package/src/utils/arc19.ts +120 -0
  129. package/src/utils/arc62.ts +246 -0
  130. package/src/utils/capacity.ts +26 -0
  131. package/src/utils/format.ts +181 -0
  132. package/src/utils/ids.ts +31 -0
  133. package/src/utils/index.ts +6 -0
  134. package/src/utils/nfdDisplay.ts +45 -0
  135. package/src/utils/search.ts +87 -0
  136. package/src/utils/stakingPool.ts +174 -0
  137. package/src/utils/stakingSnapshot.ts +132 -0
@@ -0,0 +1,141 @@
1
+ import React, { useCallback, useMemo, useRef, useState } from 'react';
2
+ import { View, Text, TextInput, Pressable, Modal } from 'react-native';
3
+ import { FlashList } from '@shopify/flash-list';
4
+ import BottomSheet, { BottomSheetBackdrop, BottomSheetView } from '@gorhom/bottom-sheet';
5
+ import Svg, { Path } from 'react-native-svg';
6
+ import type { SearchableEntity, SearchResult } from '../types/algorand';
7
+ import { searchEntities } from '../utils/search';
8
+
9
+ function SearchIcon({ size = 16, color = '#a1a1aa' }: { size?: number; color?: string }) {
10
+ return (
11
+ <Svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
12
+ <Path d="M11 3a8 8 0 1 0 0 16 8 8 0 0 0 0-16Z" />
13
+ <Path d="m21 21-4.35-4.35" />
14
+ </Svg>
15
+ );
16
+ }
17
+
18
+ interface SearchSheetProps<T extends SearchableEntity> {
19
+ data: T[];
20
+ placeholder?: string;
21
+ onSelect?: (item: T) => void;
22
+ renderItem: (item: T) => React.ReactElement;
23
+ className?: string;
24
+ }
25
+
26
+ export function SearchSheet<T extends SearchableEntity>({
27
+ data,
28
+ placeholder = 'Search...',
29
+ onSelect,
30
+ renderItem,
31
+ className,
32
+ }: SearchSheetProps<T>) {
33
+ const sheetRef = useRef<BottomSheet>(null);
34
+ const [query, setQuery] = useState('');
35
+ const [isOpen, setIsOpen] = useState(false);
36
+ const snapPoints = useMemo(() => ['50%', '80%'], []);
37
+
38
+ const results = useMemo(() => {
39
+ if (!query.trim()) {
40
+ return data.slice(0, 10).map((item) => ({ item, score: 1, matches: [] as string[] }));
41
+ }
42
+ return searchEntities(data, query, 10);
43
+ }, [data, query]);
44
+
45
+ const handleOpen = useCallback(() => {
46
+ setIsOpen(true);
47
+ sheetRef.current?.snapToIndex(0);
48
+ }, []);
49
+
50
+ const handleSelect = useCallback(
51
+ (item: T) => {
52
+ onSelect?.(item);
53
+ setQuery('');
54
+ sheetRef.current?.close();
55
+ },
56
+ [onSelect],
57
+ );
58
+
59
+ const renderBackdrop = useCallback(
60
+ (props: React.ComponentProps<typeof BottomSheetBackdrop>) => (
61
+ <BottomSheetBackdrop {...props} disappearsOnIndex={-1} appearsOnIndex={0} />
62
+ ),
63
+ [],
64
+ );
65
+
66
+ const renderResultItem = useCallback(
67
+ ({ item }: { item: SearchResult<T> }) => (
68
+ <Pressable
69
+ onPress={() => handleSelect(item.item)}
70
+ className="px-4 py-3 border-b border-zinc-800"
71
+ >
72
+ {renderItem(item.item)}
73
+ </Pressable>
74
+ ),
75
+ [handleSelect, renderItem],
76
+ );
77
+
78
+ return (
79
+ <View className={className}>
80
+ {/* Search Trigger Button */}
81
+ <Pressable
82
+ onPress={handleOpen}
83
+ className="flex-row items-center gap-2 px-3 py-2.5 rounded-lg border border-zinc-700 bg-zinc-900"
84
+ >
85
+ <SearchIcon size={16} color="#71717a" />
86
+ <Text className="flex-1 text-sm text-zinc-500">{placeholder}</Text>
87
+ </Pressable>
88
+
89
+ {/* Bottom Sheet */}
90
+ <Modal visible={isOpen} transparent animationType="none" onRequestClose={() => setIsOpen(false)}>
91
+ <View style={{ flex: 1 }}>
92
+ <BottomSheet
93
+ ref={sheetRef}
94
+ index={0}
95
+ animateOnMount={false}
96
+ enableDynamicSizing={false}
97
+ snapPoints={snapPoints}
98
+ enablePanDownToClose
99
+ backdropComponent={renderBackdrop}
100
+ backgroundStyle={{ backgroundColor: '#18181b' }}
101
+ handleIndicatorStyle={{ backgroundColor: '#52525b' }}
102
+ onChange={(index) => {
103
+ if (index === -1) setIsOpen(false);
104
+ }}
105
+ >
106
+ <BottomSheetView style={{ flex: 1 }}>
107
+ <View className="flex-1 px-4 pt-2">
108
+ {/* Search Input */}
109
+ <View className="flex-row items-center gap-2 px-3 py-2 mb-3 rounded-lg border border-zinc-700 bg-zinc-800">
110
+ <SearchIcon size={16} color="#71717a" />
111
+ <TextInput
112
+ value={query}
113
+ onChangeText={setQuery}
114
+ placeholder={placeholder}
115
+ placeholderTextColor="#71717a"
116
+ className="flex-1 text-sm text-white p-0"
117
+ autoFocus={isOpen}
118
+ />
119
+ </View>
120
+
121
+ {/* Results */}
122
+ <FlashList
123
+ data={results}
124
+ renderItem={renderResultItem}
125
+ keyExtractor={(item, index) => `search-${index}`}
126
+ ListEmptyComponent={
127
+ <View className="py-8 items-center">
128
+ <Text className="text-sm text-zinc-500">
129
+ {query.trim() ? 'No results found.' : 'No items available.'}
130
+ </Text>
131
+ </View>
132
+ }
133
+ />
134
+ </View>
135
+ </BottomSheetView>
136
+ </BottomSheet>
137
+ </View>
138
+ </Modal>
139
+ </View>
140
+ );
141
+ }
@@ -0,0 +1,25 @@
1
+ import React from 'react';
2
+ import { View } from 'react-native';
3
+ import type { ComponentSize } from '../types/algorand';
4
+
5
+ const SIZE_MAP: Record<ComponentSize, string> = {
6
+ sm: 'w-full max-w-xs',
7
+ md: 'w-full max-w-sm',
8
+ lg: 'w-full max-w-lg',
9
+ full: 'w-full',
10
+ fullscreen: 'w-full',
11
+ };
12
+
13
+ interface SizeContainerProps {
14
+ size: ComponentSize;
15
+ className?: string;
16
+ children: React.ReactNode;
17
+ }
18
+
19
+ export function SizeContainer({ size, className, children }: SizeContainerProps) {
20
+ return (
21
+ <View className={`${SIZE_MAP[size]} ${className ?? ''}`}>
22
+ {children}
23
+ </View>
24
+ );
25
+ }
@@ -0,0 +1,51 @@
1
+ import React from 'react';
2
+ import { View, Text } from 'react-native';
3
+
4
+ type BadgeVariant = 'success' | 'warning' | 'error' | 'info' | 'neutral' | 'primary';
5
+
6
+ const VARIANT_CLASSES: Record<BadgeVariant, { container: string; text: string }> = {
7
+ success: {
8
+ container: 'bg-green-500/20',
9
+ text: 'text-green-400',
10
+ },
11
+ warning: {
12
+ container: 'bg-yellow-500/20',
13
+ text: 'text-yellow-400',
14
+ },
15
+ error: {
16
+ container: 'bg-red-500/20',
17
+ text: 'text-red-400',
18
+ },
19
+ info: {
20
+ container: 'bg-blue-500/20',
21
+ text: 'text-blue-400',
22
+ },
23
+ neutral: {
24
+ container: 'bg-zinc-500/20',
25
+ text: 'text-zinc-400',
26
+ },
27
+ primary: {
28
+ container: 'bg-purple-500/20',
29
+ text: 'text-purple-400',
30
+ },
31
+ };
32
+
33
+ interface StatusBadgeProps {
34
+ label: string;
35
+ variant?: BadgeVariant;
36
+ icon?: React.ReactNode;
37
+ className?: string;
38
+ }
39
+
40
+ export function StatusBadge({ label, variant = 'neutral', icon, className }: StatusBadgeProps) {
41
+ const styles = VARIANT_CLASSES[variant];
42
+
43
+ return (
44
+ <View
45
+ className={`flex-row items-center gap-1 px-2 py-0.5 rounded-full ${styles.container} ${className ?? ''}`}
46
+ >
47
+ {icon}
48
+ <Text className={`text-xs font-medium ${styles.text}`}>{label}</Text>
49
+ </View>
50
+ );
51
+ }
@@ -0,0 +1,6 @@
1
+ export { SizeContainer } from './SizeContainer';
2
+ export { CopyButton } from './CopyButton';
3
+ export { StatusBadge } from './StatusBadge';
4
+ export { ProgressBar } from './ProgressBar';
5
+ export { SearchSheet } from './SearchSheet';
6
+ export { LoadingSkeleton, ErrorState } from './DataStates';
@@ -0,0 +1,20 @@
1
+ const IMAGE_PROXY_HOST = "https://imageproxy.akita.community/"
2
+
3
+ export function normalizeAlgomdImageUrl(
4
+ imageUrl: string | undefined,
5
+ resolveImageUrl: (src: string, width: number) => string,
6
+ width: number,
7
+ ): string | undefined {
8
+ const cleaned = imageUrl?.trim()
9
+ if (!cleaned) return undefined
10
+ if (cleaned.startsWith("file://")) return cleaned
11
+ if (cleaned.startsWith(IMAGE_PROXY_HOST)) return cleaned
12
+ if (
13
+ cleaned.startsWith("ipfs://") ||
14
+ cleaned.startsWith("https://") ||
15
+ cleaned.startsWith("http://")
16
+ ) {
17
+ return resolveImageUrl(cleaned, width)
18
+ }
19
+ return undefined
20
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * ARC-19 template-ipfs:// URL resolution.
3
+ *
4
+ * Resolves ARC-19 template URLs to standard IPFS URLs by computing the CID
5
+ * from the asset's reserve address.
6
+ *
7
+ * @see https://arc.algorand.foundation/ARCs/arc-0019
8
+ */
9
+
10
+ import algosdk from 'algosdk'
11
+
12
+ // RFC 4648 base32 lowercase alphabet (no padding)
13
+ const BASE32 = 'abcdefghijklmnopqrstuvwxyz234567'
14
+
15
+ function base32Encode(bytes: Uint8Array): string {
16
+ let result = ''
17
+ let buffer = 0
18
+ let bitsLeft = 0
19
+ for (const byte of bytes) {
20
+ buffer = (buffer << 8) | byte
21
+ bitsLeft += 8
22
+ while (bitsLeft >= 5) {
23
+ bitsLeft -= 5
24
+ result += BASE32[(buffer >> bitsLeft) & 0x1f]
25
+ }
26
+ }
27
+ if (bitsLeft > 0) {
28
+ result += BASE32[(buffer << (5 - bitsLeft)) & 0x1f]
29
+ }
30
+ return result
31
+ }
32
+
33
+ const MULTICODEC: Record<string, number> = {
34
+ raw: 0x55,
35
+ 'dag-pb': 0x70,
36
+ }
37
+
38
+ const MULTIHASH: Record<string, number> = {
39
+ 'sha2-256': 0x12,
40
+ }
41
+
42
+ /**
43
+ * Resolves an ARC-19 `template-ipfs://` URL to a standard `ipfs://` URL
44
+ * by deriving the CID from the asset's reserve address.
45
+ *
46
+ * Supports CIDv1 (base32lower with 'b' prefix). CIDv0 is not supported.
47
+ *
48
+ * @example
49
+ * resolveArc19Url('template-ipfs://{ipfscid:1:raw:reserve:sha2-256}', 'Y76M...')
50
+ * // => 'ipfs://bafkrei...'
51
+ */
52
+ export function resolveArc19Url(
53
+ templateUrl: string,
54
+ reserveAddress: string,
55
+ ): string | undefined {
56
+ const match = templateUrl.match(
57
+ /^template-ipfs:\/\/\{ipfscid:(\d+):([^:]+):([^:]+):([^}]+)\}(.*)/,
58
+ )
59
+ if (!match) return undefined
60
+
61
+ const [, versionStr, codec, field, hash, pathSuffix] = match
62
+
63
+ // Only 'reserve' field is currently supported
64
+ if (field !== 'reserve' || !reserveAddress) return undefined
65
+
66
+ const version = parseInt(versionStr)
67
+ const codecByte = MULTICODEC[codec]
68
+ const hashByte = MULTIHASH[hash]
69
+ if (codecByte === undefined || hashByte === undefined) return undefined
70
+
71
+ // Decode the reserve address to get the 32-byte public key (our content hash)
72
+ const decoded = algosdk.decodeAddress(reserveAddress)
73
+ const publicKey = decoded.publicKey
74
+
75
+ if (version === 1) {
76
+ // CIDv1: version(1) + codec + multihash(hashFn + hashLen + hash)
77
+ const cidBytes = new Uint8Array(4 + publicKey.length)
78
+ cidBytes[0] = 0x01
79
+ cidBytes[1] = codecByte
80
+ cidBytes[2] = hashByte
81
+ cidBytes[3] = 0x20 // 32 bytes
82
+ cidBytes.set(publicKey, 4)
83
+ return `ipfs://b${base32Encode(cidBytes)}${pathSuffix || ''}`
84
+ }
85
+
86
+ // CIDv0 (base58btc / "Qm...") not supported
87
+ return undefined
88
+ }
89
+
90
+ /**
91
+ * Resolves an asset URL to a direct IPFS or HTTP URL.
92
+ * Handles ARC-19 template URLs, plain IPFS URLs, and HTTP(S) URLs.
93
+ * Returns undefined for JSON metadata files and unresolvable URLs.
94
+ */
95
+ export function resolveAssetUrl(
96
+ url: string | undefined,
97
+ reserveAddress: string | undefined,
98
+ ): string | undefined {
99
+ if (!url) return undefined
100
+
101
+ // Skip JSON metadata files (ARC-3 metadata, not images)
102
+ if (url.endsWith('.json')) return undefined
103
+
104
+ // ARC-19 template resolution
105
+ if (url.startsWith('template-ipfs://')) {
106
+ return reserveAddress ? resolveArc19Url(url, reserveAddress) : undefined
107
+ }
108
+
109
+ // Direct IPFS, HTTP(S), or file:// URLs pass through
110
+ if (
111
+ url.startsWith('ipfs://') ||
112
+ url.startsWith('https://') ||
113
+ url.startsWith('http://') ||
114
+ url.startsWith('file://')
115
+ ) {
116
+ return url
117
+ }
118
+
119
+ return undefined
120
+ }
@@ -0,0 +1,246 @@
1
+ /**
2
+ * ARC-62 ASA circulating supply.
3
+ *
4
+ * Finds the asset's Circulating Supply App and simulates its read-only
5
+ * `arc62_get_circulating_supply(uint64)uint64` getter. Assets that declare no
6
+ * app, or whose app has no configuration for them, fall back to the
7
+ * conventional `total - reserve_balance`, as the ARC recommends.
8
+ *
9
+ * @see https://arc.algorand.foundation/ARCs/arc-0062
10
+ */
11
+
12
+ import algosdk from 'algosdk'
13
+
14
+ export type Arc62Network = 'mainnet' | 'testnet' | 'localnet'
15
+
16
+ /** The Algorand Foundation's trusted singleton Circulating Supply App deployments. */
17
+ export const ARC62_SINGLETON_APP_IDS: Partial<Record<Arc62Network, number>> = {
18
+ mainnet: 3749374065,
19
+ testnet: 774666409,
20
+ }
21
+
22
+ const GETTER = algosdk.ABIMethod.fromSignature('arc62_get_circulating_supply(uint64)uint64')
23
+ const RETURN_PREFIX = '151f7c75'
24
+ const ZERO_ADDRESS = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ'
25
+
26
+ export interface Arc62Clients {
27
+ /** GET an algod path and return the parsed JSON, or throw. A 404 must reject with `status: 404`. */
28
+ algodGet: (path: string) => Promise<any>
29
+ /** POST msgpack to an algod path and return the raw response bytes, or throw. */
30
+ algodPostMsgpack: (path: string, body: Uint8Array) => Promise<Uint8Array>
31
+ /** GET an indexer path and return the parsed JSON. Leave out when there is no indexer. */
32
+ indexerGet?: (path: string) => Promise<any>
33
+ /** Fetch the asset's ARC-3 / ARC-19 metadata JSON. Leave out to skip metadata discovery. */
34
+ fetchMetadata?: () => Promise<unknown>
35
+ }
36
+
37
+ export interface Arc62Asset {
38
+ id: number
39
+ totalRaw: string
40
+ reserve?: string
41
+ }
42
+
43
+ export interface CirculatingSupply {
44
+ /** Circulating supply in base units. */
45
+ raw: string
46
+ /** `arc62` when an app answered; `reserve` for the `total - reserve_balance` fallback. */
47
+ source: 'arc62' | 'reserve'
48
+ }
49
+
50
+ /** The `application-id` in an `arc-62` map, as metadata properties or an ARC-2 note carry it. */
51
+ export function arc62AppIdFrom(value: unknown): number | undefined {
52
+ if (!value || typeof value !== 'object') return undefined
53
+ const id = (value as Record<string, unknown>)['application-id']
54
+ const n = typeof id === 'string' && /^\d+$/.test(id) ? Number(id) : id
55
+ return typeof n === 'number' && Number.isSafeInteger(n) && n > 0 ? n : undefined
56
+ }
57
+
58
+ /** Reads `arc62:j{...}` from an ARC-2 note. MsgPack notes (`arc62:m`) are left out. */
59
+ export function parseArc62Note(note: Uint8Array): number | undefined {
60
+ const text = new TextDecoder().decode(note)
61
+ const match = /^arc62:j([\s\S]*)$/.exec(text)
62
+ if (!match) return undefined
63
+ try {
64
+ return arc62AppIdFrom(JSON.parse(match[1]))
65
+ } catch {
66
+ return undefined
67
+ }
68
+ }
69
+
70
+ function base64ToBytes(value: string): Uint8Array {
71
+ return new Uint8Array(algosdk.base64ToBytes(value))
72
+ }
73
+
74
+ /** The latest Circulating Supply App ID declared in the asset's config transaction notes. */
75
+ async function appIdFromNotes(clients: Arc62Clients, assetId: number): Promise<number | undefined> {
76
+ if (!clients.indexerGet) return undefined
77
+ const prefix = algosdk.bytesToBase64(new TextEncoder().encode('arc62:'))
78
+ const response = await clients.indexerGet(
79
+ `/v2/assets/${assetId}/transactions?tx-type=acfg&note-prefix=${encodeURIComponent(prefix)}&limit=50`,
80
+ )
81
+ const transactions: { note?: string; 'confirmed-round'?: number; 'intra-round-offset'?: number }[] =
82
+ response?.transactions ?? []
83
+ const latest = [...transactions].sort(
84
+ (a, b) =>
85
+ (b['confirmed-round'] ?? 0) - (a['confirmed-round'] ?? 0) ||
86
+ (b['intra-round-offset'] ?? 0) - (a['intra-round-offset'] ?? 0),
87
+ )
88
+ for (const transaction of latest) {
89
+ if (!transaction.note) continue
90
+ const id = parseArc62Note(base64ToBytes(transaction.note))
91
+ if (id) return id
92
+ }
93
+ return undefined
94
+ }
95
+
96
+ async function appIdFromMetadata(clients: Arc62Clients): Promise<number | undefined> {
97
+ if (!clients.fetchMetadata) return undefined
98
+ const metadata = (await clients.fetchMetadata()) as { properties?: Record<string, unknown> } | undefined
99
+ return arc62AppIdFrom(metadata?.properties?.['arc-62'])
100
+ }
101
+
102
+ /** Reads the uint64 an ABI method returned from its last log. */
103
+ export function decodeArc62Return(logs: readonly Uint8Array[] | undefined): bigint | undefined {
104
+ const last = logs?.[logs.length - 1]
105
+ if (!last || last.length !== 12) return undefined
106
+ const hex = Array.from(last, (byte) => byte.toString(16).padStart(2, '0')).join('')
107
+ if (!hex.startsWith(RETURN_PREFIX)) return undefined
108
+ return BigInt(`0x${hex.slice(8)}`)
109
+ }
110
+
111
+ /** Simulates the getter. Resolves undefined when the app has no answer for this asset. */
112
+ async function simulateGetter(
113
+ clients: Arc62Clients,
114
+ appId: number,
115
+ assetId: number,
116
+ sender: string,
117
+ ): Promise<bigint | undefined> {
118
+ const params = await clients.algodGet('/v2/transactions/params')
119
+ const suggestedParams: algosdk.SuggestedParams = {
120
+ fee: BigInt(0),
121
+ minFee: BigInt(params['min-fee'] ?? 1000),
122
+ flatFee: false,
123
+ firstValid: BigInt(params['last-round']),
124
+ lastValid: BigInt(params['last-round']) + BigInt(1000),
125
+ genesisID: params['genesis-id'],
126
+ genesisHash: base64ToBytes(params['genesis-hash']),
127
+ }
128
+ const transaction = algosdk.makeApplicationNoOpTxnFromObject({
129
+ sender,
130
+ appIndex: appId,
131
+ appArgs: [GETTER.getSelector(), algosdk.encodeUint64(assetId)],
132
+ suggestedParams,
133
+ })
134
+ const signed = algosdk.decodeMsgpack(
135
+ algosdk.encodeUnsignedSimulateTransaction(transaction),
136
+ algosdk.SignedTransaction,
137
+ )
138
+ const request = new algosdk.modelsv2.SimulateRequest({
139
+ txnGroups: [new algosdk.modelsv2.SimulateRequestTransactionGroup({ txns: [signed] })],
140
+ allowEmptySignatures: true,
141
+ allowUnnamedResources: true,
142
+ })
143
+ const bytes = await clients.algodPostMsgpack(
144
+ '/v2/transactions/simulate?format=msgpack',
145
+ algosdk.encodeMsgpack(request),
146
+ )
147
+ const response = algosdk.decodeMsgpack(bytes, algosdk.modelsv2.SimulateResponse)
148
+ const group = response.txnGroups[0]
149
+ if (!group || group.failureMessage) return undefined
150
+ return decodeArc62Return(group.txnResults[0]?.txnResult.logs)
151
+ }
152
+
153
+ async function reserveBalance(clients: Arc62Clients, asset: Arc62Asset): Promise<bigint> {
154
+ if (!asset.reserve || asset.reserve === ZERO_ADDRESS) return BigInt(0)
155
+ try {
156
+ const holding = await clients.algodGet(`/v2/accounts/${asset.reserve}/assets/${asset.id}`)
157
+ return BigInt(holding?.['asset-holding']?.amount ?? 0)
158
+ } catch (error) {
159
+ // A reserve that is not opted in holds none of the asset.
160
+ if ((error as { status?: number })?.status === 404) return BigInt(0)
161
+ throw error
162
+ }
163
+ }
164
+
165
+ /**
166
+ * The asset's circulating supply. The app is the one its metadata or its
167
+ * latest ARC-2 config note declares, else the singleton for the network.
168
+ */
169
+ export async function fetchCirculatingSupply(
170
+ clients: Arc62Clients,
171
+ asset: Arc62Asset,
172
+ options: { network: Arc62Network; sender: string },
173
+ ): Promise<CirculatingSupply> {
174
+ const declared =
175
+ (await appIdFromMetadata(clients).catch(() => undefined)) ??
176
+ (await appIdFromNotes(clients, asset.id).catch(() => undefined))
177
+ const candidates = [declared, ARC62_SINGLETON_APP_IDS[options.network]].filter(
178
+ (id, index, ids): id is number => id != null && ids.indexOf(id) === index,
179
+ )
180
+ for (const appId of candidates) {
181
+ const supply = await simulateGetter(clients, appId, asset.id, options.sender).catch(() => undefined)
182
+ if (supply != null) return { raw: supply.toString(), source: 'arc62' }
183
+ }
184
+ const total = BigInt(asset.totalRaw)
185
+ const reserve = await reserveBalance(clients, asset)
186
+ return { raw: (total > reserve ? total - reserve : BigInt(0)).toString(), source: 'reserve' }
187
+ }
188
+
189
+ const IPFS_GATEWAY = 'https://ipfs.io/ipfs/'
190
+
191
+ /** The URL of an asset's ARC-3 or ARC-19 metadata JSON, when its URL field points at one. */
192
+ export function assetMetadataUrl(url: string | undefined, resolvedUrl: string | undefined): string | undefined {
193
+ if (!url || !resolvedUrl) return undefined
194
+ const isMetadata = url.startsWith('template-ipfs://') || /#arc3$/i.test(url)
195
+ if (!isMetadata) return undefined
196
+ const plain = resolvedUrl.replace(/#arc3$/i, '')
197
+ if (plain.startsWith('ipfs://')) return `${IPFS_GATEWAY}${plain.slice('ipfs://'.length)}`
198
+ return /^https:\/\//.test(plain) ? plain : undefined
199
+ }
200
+
201
+ export interface RestArc62Options {
202
+ algodServer: string
203
+ algodToken?: string
204
+ indexerServer?: string
205
+ indexerToken?: string
206
+ headers?: Record<string, string>
207
+ metadataUrl?: string
208
+ }
209
+
210
+ /** Arc62Clients over plain fetch, for hosts without an algod client of their own. */
211
+ export function restArc62Clients(options: RestArc62Options): Arc62Clients {
212
+ const algod = options.algodServer.replace(/\/+$/, '')
213
+ const algodHeaders: Record<string, string> = {
214
+ ...(options.algodToken ? { 'X-Algo-API-Token': options.algodToken } : {}),
215
+ ...options.headers,
216
+ }
217
+ const check = (response: Response) => {
218
+ if (!response.ok) throw Object.assign(new Error(`Request failed with ${response.status}`), { status: response.status })
219
+ return response
220
+ }
221
+ return {
222
+ algodGet: async (path) => (await fetch(`${algod}${path}`, { headers: algodHeaders }).then(check)).json(),
223
+ algodPostMsgpack: async (path, body) => {
224
+ const response = await fetch(`${algod}${path}`, {
225
+ method: 'POST',
226
+ headers: { ...algodHeaders, 'Content-Type': 'application/msgpack' },
227
+ body: body as unknown as BodyInit,
228
+ }).then(check)
229
+ return new Uint8Array(await response.arrayBuffer())
230
+ },
231
+ indexerGet: options.indexerServer
232
+ ? async (path) =>
233
+ (
234
+ await fetch(`${options.indexerServer!.replace(/\/+$/, '')}${path}`, {
235
+ headers: {
236
+ ...(options.indexerToken ? { 'X-Indexer-API-Token': options.indexerToken } : {}),
237
+ ...options.headers,
238
+ },
239
+ }).then(check)
240
+ ).json()
241
+ : undefined,
242
+ fetchMetadata: options.metadataUrl
243
+ ? async () => (await fetch(options.metadataUrl!).then(check)).json()
244
+ : undefined,
245
+ }
246
+ }
@@ -0,0 +1,26 @@
1
+ /** Compare an on-chain count against capacity without losing uint64 precision. */
2
+ export function isCapacityFull(
3
+ current: number,
4
+ currentRaw: string | undefined,
5
+ capacity: number | undefined,
6
+ capacityRaw: string | undefined,
7
+ ): boolean {
8
+ if (capacityRaw != null) {
9
+ try {
10
+ const exactCapacity = BigInt(capacityRaw);
11
+ // Protocol capacity 0 means unlimited.
12
+ if (exactCapacity <= BigInt(0)) return false;
13
+ const exactCurrent =
14
+ currentRaw != null
15
+ ? BigInt(currentRaw)
16
+ : Number.isSafeInteger(current)
17
+ ? BigInt(current)
18
+ : undefined;
19
+ if (exactCurrent != null) return exactCurrent >= exactCapacity;
20
+ } catch {
21
+ // Fall back to legacy numeric fields when persisted raw data is invalid.
22
+ }
23
+ }
24
+
25
+ return capacity != null && capacity > 0 && current >= capacity;
26
+ }