@floorlaunchpad/sdk 0.1.1 → 0.3.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 (298) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/LICENSE +201 -60
  3. package/README.md +54 -24
  4. package/dist/abi/evm-event-names.js +12 -0
  5. package/dist/abi/evm.gen.js +130 -0
  6. package/dist/abi/functions.gen.js +144 -0
  7. package/dist/abi/index.js +17 -0
  8. package/dist/abi/solana.gen.js +130 -0
  9. package/dist/burn.js +21 -0
  10. package/dist/client/evm/index.js +191 -0
  11. package/dist/client/index.js +19 -0
  12. package/dist/client/solana/index.js +259 -0
  13. package/dist/client/types.js +5 -0
  14. package/dist/codec.js +77 -0
  15. package/dist/config/codeHash.js +9 -0
  16. package/dist/config/generated.js +803 -0
  17. package/dist/config/index.js +49 -0
  18. package/dist/config/registry.gen.js +118 -0
  19. package/dist/config/solana-genesis.js +7 -0
  20. package/dist/ed25519.js +31 -0
  21. package/dist/errors.js +249 -0
  22. package/dist/events/index.js +40 -0
  23. package/dist/events/types.gen.js +3 -0
  24. package/dist/evm/abi.js +283 -0
  25. package/dist/evm/balances.js +26 -0
  26. package/dist/evm/chains.js +148 -0
  27. package/dist/evm/floor/abi.gen.js +195 -0
  28. package/dist/evm/floor/calls.js +230 -0
  29. package/dist/evm/floor/create.js +49 -0
  30. package/dist/evm/floor/events.js +41 -0
  31. package/dist/evm/floor/iface.js +44 -0
  32. package/dist/evm/items.js +209 -0
  33. package/dist/evm/keccak.js +118 -0
  34. package/dist/evm/multicall.js +30 -0
  35. package/dist/evm/router.js +184 -0
  36. package/dist/evm/squid.js +107 -0
  37. package/dist/evm/zap.js +128 -0
  38. package/dist/fixtures.js +53 -0
  39. package/dist/generated/index.js +28 -0
  40. package/dist/generated/interface.gen.js +146 -0
  41. package/dist/handle.js +22 -0
  42. package/dist/index.js +93 -7
  43. package/dist/indexer/bodies.js +473 -0
  44. package/dist/indexer/client.js +105 -0
  45. package/dist/indexer/contract.js +358 -0
  46. package/dist/indexer/decode.js +97 -0
  47. package/dist/indexer/partners.js +105 -0
  48. package/dist/indexer/paths.js +127 -0
  49. package/dist/indexer/read.js +109 -0
  50. package/dist/indexer/stream.js +71 -0
  51. package/dist/lock.js +16 -0
  52. package/dist/math/fixed.js +154 -0
  53. package/dist/math/genesis.js +39 -0
  54. package/dist/math/index.js +20 -0
  55. package/dist/math/u256.js +49 -0
  56. package/dist/math/v2/ask.js +162 -0
  57. package/dist/math/v2/book.js +607 -0
  58. package/dist/math/v2/circulating.js +62 -0
  59. package/dist/math/v2/create.js +122 -0
  60. package/dist/math/v2/display.js +208 -0
  61. package/dist/math/v2/error.js +17 -0
  62. package/dist/math/v2/feasibility.js +174 -0
  63. package/dist/math/v2/fees.js +121 -0
  64. package/dist/math/v2/holders.js +105 -0
  65. package/dist/math/v2/milestones.js +40 -0
  66. package/dist/math/v2/pow.js +69 -0
  67. package/dist/math/v2/preset.js +151 -0
  68. package/dist/math/v2/receipt.js +108 -0
  69. package/dist/math/v2/relay.js +217 -0
  70. package/dist/math/v2/rows.js +365 -0
  71. package/dist/math/v2/split.js +111 -0
  72. package/dist/math/v2/sqrt.js +84 -0
  73. package/dist/math/v2/supply.js +21 -0
  74. package/dist/math/v2/team.js +75 -0
  75. package/dist/math/v2/trade.js +126 -0
  76. package/dist/math/v2/wide.js +51 -0
  77. package/dist/quote.js +6 -0
  78. package/dist/registryPrice.js +23 -0
  79. package/dist/route/edge-jupiter.js +42 -0
  80. package/dist/route/edge.js +11 -0
  81. package/dist/route/graph.js +51 -0
  82. package/dist/route/path.js +75 -0
  83. package/dist/route/quote.js +15 -0
  84. package/dist/route-jupiter.js +35 -0
  85. package/dist/route.js +8 -0
  86. package/dist/sha256.js +61 -0
  87. package/dist/solana/alt.js +18 -0
  88. package/dist/solana/floor/accounts.js +392 -0
  89. package/dist/solana/floor/borsh.js +66 -0
  90. package/dist/solana/floor/create.js +65 -0
  91. package/dist/solana/floor/events.js +144 -0
  92. package/dist/solana/floor/genesis.js +91 -0
  93. package/dist/solana/floor/genesisList.js +68 -0
  94. package/dist/solana/floor/instructions.js +448 -0
  95. package/dist/solana/floor/metadata.js +198 -0
  96. package/dist/solana/floor/mint.js +206 -0
  97. package/dist/solana/floor/program.js +64 -0
  98. package/dist/solana/floor/registry.js +83 -0
  99. package/dist/solana/instruction.js +49 -0
  100. package/dist/solana/pda.js +88 -0
  101. package/dist/solana/tx.js +138 -0
  102. package/dist/v2/burnPreview.js +35 -0
  103. package/dist/v2/circulating.js +11 -0
  104. package/dist/v2/claimAllEvm.js +70 -0
  105. package/dist/v2/claims-evm.js +120 -0
  106. package/dist/v2/claims.js +218 -0
  107. package/dist/v2/dead.js +21 -0
  108. package/dist/v2/devbuy.js +37 -0
  109. package/dist/v2/events.js +115 -0
  110. package/dist/v2/evm.js +299 -0
  111. package/dist/v2/evmReads.js +76 -0
  112. package/dist/v2/genesis.js +76 -0
  113. package/dist/v2/layouts.js +217 -0
  114. package/dist/v2/market-evm.js +74 -0
  115. package/dist/v2/presetRowEvm.js +45 -0
  116. package/dist/v2/press.js +106 -0
  117. package/dist/v2/quoteMint.js +52 -0
  118. package/dist/v2/receipt-tx.js +149 -0
  119. package/dist/v2/route-alt.js +114 -0
  120. package/dist/v2/route.js +389 -0
  121. package/dist/v2/router.js +22 -0
  122. package/dist/v2/solana.js +391 -0
  123. package/dist/v2/solanaSettle.js +97 -0
  124. package/dist/v2/tx/evm.js +126 -0
  125. package/dist/v2/tx/genesis.js +47 -0
  126. package/dist/v2/tx/index.js +5 -0
  127. package/dist/v2/tx/solana.js +118 -0
  128. package/dist/v2/types.js +13 -0
  129. package/docs/aggregator.md +61 -0
  130. package/docs/bot.md +50 -0
  131. package/docs/floor-line.md +66 -0
  132. package/docs/frontend.md +29 -0
  133. package/docs/wallet.md +54 -0
  134. package/examples/floor-line.html +104 -0
  135. package/package.json +429 -32
  136. package/src/abi/evm-event-names.ts +12 -0
  137. package/src/abi/evm.gen.ts +139 -0
  138. package/src/abi/functions.gen.ts +154 -0
  139. package/src/abi/index.ts +30 -0
  140. package/src/abi/solana.gen.ts +140 -0
  141. package/src/burn.ts +37 -0
  142. package/src/client/evm/index.ts +199 -0
  143. package/src/client/index.ts +23 -0
  144. package/src/client/solana/index.ts +260 -0
  145. package/src/client/types.ts +162 -0
  146. package/src/codec.ts +77 -0
  147. package/src/config/codeHash.ts +9 -0
  148. package/src/config/generated.ts +803 -0
  149. package/src/config/index.ts +93 -0
  150. package/src/config/registry.gen.ts +118 -0
  151. package/src/config/solana-genesis.ts +7 -0
  152. package/src/ed25519.ts +31 -0
  153. package/src/errors.ts +270 -0
  154. package/src/events/index.ts +44 -0
  155. package/src/events/types.gen.ts +842 -0
  156. package/src/evm/abi.ts +292 -0
  157. package/src/evm/balances.ts +26 -0
  158. package/src/evm/chains.ts +171 -0
  159. package/src/evm/floor/abi.gen.ts +195 -0
  160. package/src/evm/floor/calls.ts +247 -0
  161. package/src/evm/floor/create.ts +68 -0
  162. package/src/evm/floor/events.ts +51 -0
  163. package/src/evm/floor/iface.ts +45 -0
  164. package/src/evm/items.ts +252 -0
  165. package/src/evm/keccak.ts +118 -0
  166. package/src/evm/multicall.ts +43 -0
  167. package/src/evm/router.ts +209 -0
  168. package/src/evm/squid.ts +138 -0
  169. package/src/evm/zap.ts +152 -0
  170. package/src/fixtures.ts +53 -0
  171. package/src/generated/index.ts +29 -0
  172. package/src/generated/interface.gen.ts +153 -0
  173. package/src/handle.ts +22 -0
  174. package/src/index.ts +93 -6
  175. package/src/indexer/bodies.ts +528 -0
  176. package/src/indexer/client.ts +180 -0
  177. package/src/indexer/contract.ts +419 -0
  178. package/src/indexer/decode.ts +109 -0
  179. package/src/indexer/partners.ts +115 -0
  180. package/src/indexer/paths.ts +190 -0
  181. package/src/indexer/read.ts +119 -0
  182. package/src/indexer/stream.ts +83 -0
  183. package/src/lock.ts +16 -0
  184. package/src/math/fixed.ts +154 -0
  185. package/src/math/genesis.ts +39 -0
  186. package/src/math/index.ts +24 -0
  187. package/src/math/u256.ts +49 -0
  188. package/src/math/v2/ask.ts +218 -0
  189. package/src/math/v2/book.ts +660 -0
  190. package/src/math/v2/circulating.ts +69 -0
  191. package/src/math/v2/create.ts +139 -0
  192. package/src/math/v2/display.ts +250 -0
  193. package/src/math/v2/error.ts +19 -0
  194. package/src/math/v2/feasibility.ts +200 -0
  195. package/src/math/v2/fees.ts +121 -0
  196. package/src/math/v2/holders.ts +124 -0
  197. package/src/math/v2/milestones.ts +51 -0
  198. package/src/math/v2/pow.ts +71 -0
  199. package/src/math/v2/preset.ts +189 -0
  200. package/src/math/v2/receipt.ts +162 -0
  201. package/src/math/v2/relay.ts +235 -0
  202. package/src/math/v2/rows.ts +412 -0
  203. package/src/math/v2/split.ts +160 -0
  204. package/src/math/v2/sqrt.ts +86 -0
  205. package/src/math/v2/supply.ts +27 -0
  206. package/src/math/v2/team.ts +75 -0
  207. package/src/math/v2/trade.ts +145 -0
  208. package/src/math/v2/wide.ts +52 -0
  209. package/src/quote.ts +6 -0
  210. package/src/registryPrice.ts +28 -0
  211. package/src/route/edge-jupiter.ts +71 -0
  212. package/src/route/edge.ts +22 -0
  213. package/src/route/graph.ts +77 -0
  214. package/src/route/path.ts +84 -0
  215. package/src/route/quote.ts +46 -0
  216. package/src/route-jupiter.ts +36 -0
  217. package/src/route.ts +8 -0
  218. package/src/sha256.ts +61 -0
  219. package/src/solana/alt.ts +25 -0
  220. package/src/solana/floor/accounts.ts +395 -0
  221. package/src/solana/floor/borsh.ts +66 -0
  222. package/src/solana/floor/create.ts +89 -0
  223. package/src/solana/floor/events.ts +151 -0
  224. package/src/solana/floor/genesis.ts +111 -0
  225. package/src/solana/floor/genesisList.ts +75 -0
  226. package/src/solana/floor/instructions.ts +504 -0
  227. package/src/solana/floor/metadata.ts +246 -0
  228. package/src/solana/floor/mint.ts +242 -0
  229. package/src/solana/floor/program.ts +64 -0
  230. package/src/solana/floor/registry.ts +96 -0
  231. package/src/solana/instruction.ts +61 -0
  232. package/src/solana/pda.ts +91 -0
  233. package/src/solana/tx.ts +143 -0
  234. package/src/v2/burnPreview.ts +52 -0
  235. package/src/v2/circulating.ts +22 -0
  236. package/src/v2/claimAllEvm.ts +97 -0
  237. package/src/v2/claims-evm.ts +179 -0
  238. package/src/v2/claims.ts +288 -0
  239. package/src/v2/dead.ts +21 -0
  240. package/src/v2/devbuy.ts +55 -0
  241. package/src/v2/events.ts +131 -0
  242. package/src/v2/evm.ts +349 -0
  243. package/src/v2/evmReads.ts +121 -0
  244. package/src/v2/genesis.ts +80 -0
  245. package/src/v2/layouts.ts +219 -0
  246. package/src/v2/market-evm.ts +95 -0
  247. package/src/v2/presetRowEvm.ts +54 -0
  248. package/src/v2/press.ts +124 -0
  249. package/src/v2/quoteMint.ts +63 -0
  250. package/src/v2/receipt-tx.ts +251 -0
  251. package/src/v2/route-alt.ts +114 -0
  252. package/src/v2/route.ts +494 -0
  253. package/src/v2/router.ts +22 -0
  254. package/src/v2/solana.ts +439 -0
  255. package/src/v2/solanaSettle.ts +117 -0
  256. package/src/v2/tx/evm.ts +152 -0
  257. package/src/v2/tx/genesis.ts +66 -0
  258. package/src/v2/tx/index.ts +5 -0
  259. package/src/v2/tx/solana.ts +140 -0
  260. package/src/v2/types.ts +284 -0
  261. package/dist/adapter.d.ts +0 -28
  262. package/dist/adapter.d.ts.map +0 -1
  263. package/dist/adapter.js +0 -2
  264. package/dist/adapter.js.map +0 -1
  265. package/dist/chain.d.ts +0 -23
  266. package/dist/chain.d.ts.map +0 -1
  267. package/dist/chain.js +0 -25
  268. package/dist/chain.js.map +0 -1
  269. package/dist/client.d.ts +0 -26
  270. package/dist/client.d.ts.map +0 -1
  271. package/dist/client.js +0 -43
  272. package/dist/client.js.map +0 -1
  273. package/dist/dex-adapter.d.ts +0 -228
  274. package/dist/dex-adapter.d.ts.map +0 -1
  275. package/dist/dex-adapter.js +0 -407
  276. package/dist/dex-adapter.js.map +0 -1
  277. package/dist/index.d.ts +0 -7
  278. package/dist/index.d.ts.map +0 -1
  279. package/dist/index.js.map +0 -1
  280. package/dist/quotes.d.ts +0 -12
  281. package/dist/quotes.d.ts.map +0 -1
  282. package/dist/quotes.gen.d.ts +0 -8
  283. package/dist/quotes.gen.d.ts.map +0 -1
  284. package/dist/quotes.gen.js +0 -2170
  285. package/dist/quotes.gen.js.map +0 -1
  286. package/dist/quotes.js +0 -24
  287. package/dist/quotes.js.map +0 -1
  288. package/dist/types.d.ts +0 -111
  289. package/dist/types.d.ts.map +0 -1
  290. package/dist/types.js +0 -2
  291. package/dist/types.js.map +0 -1
  292. package/src/adapter.ts +0 -20
  293. package/src/chain.ts +0 -39
  294. package/src/client.ts +0 -41
  295. package/src/dex-adapter.ts +0 -477
  296. package/src/quotes.gen.ts +0 -2170
  297. package/src/quotes.ts +0 -29
  298. package/src/types.ts +0 -115
@@ -0,0 +1,180 @@
1
+
2
+
3
+ import { decode } from "./decode.ts";
4
+ import { INDEXER_CONTRACT, clampLimit, routeLimit } from "./contract.ts";
5
+ import type { RouteBody, RouteName } from "./contract.ts";
6
+ import { indexerPath, query } from "./paths.ts";
7
+ import type { CandlesQuery, LaunchesQuery, Page, StreamQuery, TradesQuery, WalletTradesQuery } from "./paths.ts";
8
+ import { IndexerError } from "./read.ts";
9
+ import type { Get } from "./read.ts";
10
+ import type { TraderWindow } from "./bodies.ts";
11
+
12
+ type L = { launch: string };
13
+ type W = { wallet: string };
14
+
15
+ export interface RouteArgs {
16
+ head: void;
17
+ latestBlock: void;
18
+ stream: StreamQuery;
19
+ quotes: void;
20
+ summary: void;
21
+ floorRouted: void;
22
+ events: { fromBlock: number; toBlock: number };
23
+ launches: LaunchesQuery | void;
24
+ launch: L;
25
+ launchState: L;
26
+ milestones: L;
27
+ holders: L & { limit?: number };
28
+ trades: L & TradesQuery;
29
+ launchClaims: L & { claimer?: string };
30
+ devBuys: L;
31
+ traders: L & { window?: TraderWindow; limit?: number };
32
+ quoteChain: L;
33
+ devTrades: L & { limit?: number };
34
+ burns: L;
35
+ launchLocks: L;
36
+ marks: L & Page;
37
+ price: L;
38
+ highs: L & { atLeast?: bigint | string; limit?: number };
39
+ candles: CandlesQuery;
40
+ candleBundle: L & { intervals?: readonly string[]; limit?: number };
41
+ walletTrades: W & WalletTradesQuery;
42
+ positions: W;
43
+ inbox: W & { limit?: number };
44
+ walletLocks: W;
45
+ claimHistory: W;
46
+ firsts: W;
47
+ firstsMany: { wallets: readonly string[] };
48
+ claimView: W;
49
+ people: W;
50
+ roles: W;
51
+ traderBoard: { window?: TraderWindow; limit?: number } | void;
52
+ launcherBoard: { limit?: number } | void;
53
+ tokenHolders: { token: string; limit?: number; offset?: number };
54
+ dexAsset: { id: string };
55
+ dexSummary: { id: string };
56
+ dexPair: { id: string };
57
+ cgPairs: void;
58
+ cgTickers: void;
59
+ cgHistoricalTrades: { ticker_id: string; type?: "buy" | "sell"; limit?: number; start_time?: number; end_time?: number };
60
+ llamaTvl: void;
61
+ llamaFees: { from: number; to: number } | void;
62
+ health: void;
63
+ }
64
+
65
+ const need = (s: string, what: string): string => {
66
+ if (s === "") throw new RangeError(`an empty ${what}`);
67
+ return s;
68
+ };
69
+
70
+ export const routePath: { [N in RouteName]: (a: RouteArgs[N]) => string } = {
71
+ head: () => indexerPath.head(),
72
+ latestBlock: () => indexerPath.latestBlock(),
73
+ stream: (a) => indexerPath.stream(a),
74
+ quotes: () => indexerPath.quotes(),
75
+ summary: () => indexerPath.summary(),
76
+ floorRouted: () => indexerPath.floorRouted(),
77
+ events: (a) => indexerPath.events(a.fromBlock, a.toBlock),
78
+ launches: (a) => indexerPath.launches(a ?? {}),
79
+ launch: (a) => indexerPath.launch(a.launch),
80
+ launchState: (a) => indexerPath.launchState(a.launch),
81
+ milestones: (a) => indexerPath.milestones(a.launch),
82
+ holders: ({ launch, ...q }) => indexerPath.holders(launch, q),
83
+ trades: ({ launch, ...q }) => indexerPath.trades(launch, q),
84
+ launchClaims: ({ launch, ...q }) => indexerPath.launchClaims(launch, q),
85
+ devBuys: (a) => indexerPath.devBuys(a.launch),
86
+ traders: ({ launch, ...q }) => indexerPath.traders(launch, q),
87
+ quoteChain: (a) => indexerPath.quoteChain(a.launch),
88
+ devTrades: ({ launch, ...q }) => indexerPath.devTrades(launch, q),
89
+ burns: (a) => indexerPath.burns(a.launch),
90
+ launchLocks: (a) => indexerPath.launchLocks(a.launch),
91
+ marks: ({ launch, ...q }) => indexerPath.marks(launch, q),
92
+ price: (a) => indexerPath.price(a.launch),
93
+ highs: ({ launch, ...q }) => indexerPath.highs(launch, q),
94
+ candles: (a) => indexerPath.candles(a),
95
+ candleBundle: ({ launch, ...q }) => indexerPath.candleBundle(launch, q),
96
+ walletTrades: ({ wallet, ...q }) => indexerPath.walletTrades(wallet, q),
97
+ positions: (a) => indexerPath.positions(a.wallet),
98
+ inbox: ({ wallet, ...q }) => indexerPath.inbox(wallet, q),
99
+ walletLocks: (a) => indexerPath.walletLocks(a.wallet),
100
+ claimHistory: (a) => indexerPath.claimHistory(a.wallet),
101
+ firsts: (a) => indexerPath.firsts(a.wallet),
102
+ firstsMany: (a) => indexerPath.firstsMany(a.wallets),
103
+ claimView: (a) => indexerPath.claimView(a.wallet),
104
+ people: (a) => indexerPath.people(a.wallet),
105
+ roles: (a) => indexerPath.roles(a.wallet),
106
+ traderBoard: (a) => indexerPath.traderBoard(a ?? {}),
107
+ launcherBoard: (a) => indexerPath.launcherBoard(a ?? {}),
108
+ tokenHolders: (a) => `/floor-amm/holders/${encodeURIComponent(need(a.token, "token"))}${query({ limit: a.limit, offset: a.offset })}`,
109
+ dexAsset: (a) => `/v2/dex/asset${query({ id: need(a.id, "id") })}`,
110
+ dexSummary: (a) => `/v2/dex/summary${query({ id: need(a.id, "id") })}`,
111
+ dexPair: (a) => `/v2/dex/pair${query({ id: need(a.id, "id") })}`,
112
+ cgPairs: () => "/v2/coingecko/pairs",
113
+ cgTickers: () => "/v2/coingecko/tickers",
114
+ cgHistoricalTrades: (a) => `/v2/coingecko/historical_trades${query({ ticker_id: need(a.ticker_id, "ticker_id"), type: a.type, limit: a.limit, start_time: a.start_time, end_time: a.end_time })}`,
115
+ llamaTvl: () => "/v2/defillama/tvl",
116
+ llamaFees: (a) => {
117
+ if (a && a.to < a.from) throw new RangeError("from > to");
118
+ return `/v2/defillama/fees${query({ from: a?.from, to: a?.to })}`;
119
+ },
120
+ health: () => "/health",
121
+ };
122
+
123
+ export type DrainName = "trades" | "walletTrades" | "launches" | "marks";
124
+
125
+ export type ReadName = Exclude<RouteName, "stream">;
126
+
127
+ export interface IndexerClientOptions {
128
+
129
+ get: Get;
130
+
131
+ getRoot?: Get;
132
+ }
133
+
134
+ export type IndexerClient = {
135
+
136
+ read<N extends ReadName>(name: N, ...args: RouteArgs[N] extends void ? [] : [RouteArgs[N]]): Promise<RouteBody<N>>;
137
+
138
+ path<N extends RouteName>(name: N, ...args: RouteArgs[N] extends void ? [] : [RouteArgs[N]]): string;
139
+
140
+ drain<N extends DrainName>(name: N, args: RouteArgs[N], opts?: { maxPages?: number }): AsyncGenerator<RouteBody<N>>;
141
+ } & { readonly [N in ReadName]: (...args: RouteArgs[N] extends void ? [] : [RouteArgs[N]]) => Promise<RouteBody<N>> };
142
+
143
+ export function createIndexerClient(opts: IndexerClientOptions): IndexerClient {
144
+
145
+ const clamp = (name: RouteName, a: unknown): unknown => {
146
+ if (typeof a !== "object" || a === null || !("limit" in a) || typeof (a as { limit: unknown }).limit !== "number") return a;
147
+ return { ...a, limit: clampLimit(name, (a as { limit: number }).limit) };
148
+ };
149
+ const path = (name: RouteName, a?: unknown): string => (routePath[name] as (x: unknown) => string)(clamp(name, a));
150
+ const read = async (name: ReadName, a?: unknown): Promise<unknown> => {
151
+ const c = INDEXER_CONTRACT[name];
152
+ const get = c.mount === "root" ? opts.getRoot : opts.get;
153
+ if (get === undefined) throw new TypeError(`${name} is served at the server's root: pass getRoot`);
154
+ const r = await get(path(name, a));
155
+ if (r.status !== 200) throw new IndexerError(r.status, r.body);
156
+ return decode(c.body as (v: unknown, p: string) => unknown, r.body);
157
+ };
158
+ async function* drain(name: DrainName, a: Record<string, unknown>, o: { maxPages?: number } = {}): AsyncGenerator<unknown> {
159
+ const page = INDEXER_CONTRACT[name].page;
160
+ const max = o.maxPages ?? 100;
161
+ const lim = routeLimit(name)!;
162
+ let args: Record<string, unknown> = { ...a };
163
+ for (let i = 0; i < max; i++) {
164
+ const body = (await read(name, args)) as { next?: string | null; total?: number };
165
+ yield body;
166
+ if (page.kind === "cursor") {
167
+ if (body.next === null || body.next === undefined) return;
168
+ args = { ...args, before: body.next };
169
+ } else if (page.kind === "offset") {
170
+ const step = clampLimit(name, (args.limit as number | undefined) ?? lim.default);
171
+ const offset = ((args.offset as number | undefined) ?? 0) + step;
172
+ if (offset >= (body.total ?? 0)) return;
173
+ args = { ...args, offset };
174
+ } else throw new TypeError(`${name} does not page`);
175
+ }
176
+ }
177
+ const client: Record<string, unknown> = { read, path, drain };
178
+ for (const name of Object.keys(INDEXER_CONTRACT) as RouteName[]) if (name !== "stream") client[name] = (a?: unknown) => read(name, a);
179
+ return client as IndexerClient;
180
+ }
@@ -0,0 +1,419 @@
1
+
2
+
3
+ import type { Decoder } from "./decode.ts";
4
+ import { unknown } from "./decode.ts";
5
+ import * as B from "./bodies.ts";
6
+ import * as P from "./partners.ts";
7
+ import { FIRSTS_MAX, IDS_MAX, LAUNCHES_PAGE_MAX, LAUNCH_SORTS, STREAM_STATE_MAX } from "./paths.ts";
8
+
9
+ export const UNITS = {
10
+ site: "raw quote base units, token math units (6 dp), Q64.64 prices, unix s; bigint as decimal strings; USD as decimal strings",
11
+ partner: "the partner's format: whole-unit decimal strings unless a field says raw base units; unix s",
12
+ } as const;
13
+ export type Units = keyof typeof UNITS;
14
+
15
+ export const INDEXER_ERROR_CODES = [
16
+
17
+ "not_ready",
18
+
19
+ "unknown_route",
20
+
21
+ "unknown_launch",
22
+
23
+ "not_found",
24
+
25
+ "bad_query",
26
+
27
+ "too_many",
28
+
29
+ "no_reader",
30
+
31
+ "not_indexed",
32
+
33
+ "upstream",
34
+
35
+ "method",
36
+
37
+ "unknown",
38
+ ] as const;
39
+ export type IndexerErrorCode = (typeof INDEXER_ERROR_CODES)[number];
40
+
41
+ const errorWord = (body: unknown): string | null => (typeof body === "object" && body !== null && "error" in body ? String((body as { error: unknown }).error) : null);
42
+
43
+ export function errorCode(status: number, body: unknown): IndexerErrorCode {
44
+ const w = errorWord(body);
45
+ switch (status) {
46
+ case 400:
47
+ return "bad_query";
48
+ case 404:
49
+ return w === "unknown route" ? "unknown_route" : w === "unknown launch" ? "unknown_launch" : "not_found";
50
+ case 405:
51
+ return "method";
52
+ case 413:
53
+ return "too_many";
54
+ case 501:
55
+ return "no_reader";
56
+ case 502:
57
+ return "upstream";
58
+ case 503:
59
+ return w === "not ready" ? "not_ready" : "not_indexed";
60
+ default:
61
+ return "unknown";
62
+ }
63
+ }
64
+
65
+ export interface QueryKey {
66
+ readonly kind: "int" | "string" | "bool" | "list" | "enum" | "unix" | "block" | "cursor";
67
+ readonly doc: string;
68
+ readonly values?: readonly string[];
69
+ readonly min?: number;
70
+ readonly max?: number;
71
+ readonly default?: string | number;
72
+ readonly required?: boolean;
73
+ }
74
+
75
+ export type Pagination =
76
+ | { readonly kind: "none" }
77
+
78
+ | { readonly kind: "limit"; readonly limit: { readonly default: number; readonly max: number } }
79
+
80
+ | { readonly kind: "offset"; readonly limit: { readonly default: number; readonly max: number }; readonly total: "total" }
81
+
82
+ | { readonly kind: "cursor"; readonly limit: { readonly default: number; readonly max: number }; readonly cursor: "before"; readonly next: "next" }
83
+
84
+ | { readonly kind: "range"; readonly from: string; readonly to: string; readonly span?: { readonly interval: string; readonly max: number } };
85
+
86
+ export type PathParam = "launch" | "wallet" | "token";
87
+
88
+ export interface RouteContract<T = unknown> {
89
+ readonly pattern: string;
90
+ readonly aliases: readonly string[];
91
+ readonly mount: "chain" | "root";
92
+ readonly params: readonly PathParam[];
93
+ readonly query: Readonly<Record<string, QueryKey>>;
94
+ readonly page: Pagination;
95
+ readonly errors: readonly IndexerErrorCode[];
96
+
97
+ readonly gated: boolean;
98
+
99
+ readonly sse?: true;
100
+ readonly units: Units;
101
+ readonly audience: "site" | "partner" | "ops";
102
+ readonly body: Decoder<T>;
103
+ }
104
+
105
+ const NONE = { kind: "none" } as const;
106
+ const limit = (dflt: number, max: number) => ({ kind: "limit", limit: { default: dflt, max } }) as const;
107
+ const cursor = (dflt: number, max: number) => ({ kind: "cursor", limit: { default: dflt, max }, cursor: "before", next: "next" }) as const;
108
+ const LIMIT = (dflt: number, max: number): QueryKey => ({ kind: "int", doc: "rows", min: 1, max, default: dflt });
109
+ const BEFORE: QueryKey = { kind: "cursor", doc: "a block, or a row id <block>:<txnIndex>:<eventIndex> (a page's next): rows strictly before it" };
110
+ const WINDOW: QueryKey = { kind: "enum", doc: "the volume window", values: B.TRADER_WINDOWS, default: "24h" };
111
+
112
+ const GATED = ["not_ready", "upstream"] as const;
113
+ const LAUNCH_ERR = [...GATED, "unknown_launch"] as const;
114
+ const WALLET_ERR = [...GATED, "bad_query"] as const;
115
+
116
+ type Spec<T> = Omit<RouteContract<T>, "aliases" | "mount" | "params" | "query" | "page" | "errors" | "gated" | "units" | "audience"> & Partial<RouteContract<T>>;
117
+
118
+ function site<T>(s: Spec<T> & { v2?: boolean }): RouteContract<T> {
119
+ const params = [...s.pattern.matchAll(/<(launch|wallet|token)>/g)].map((m) => m[1] as PathParam);
120
+ const { v2, ...rest } = s;
121
+ const aliases = s.aliases ?? (v2 ? [s.pattern.replace(/^\/floor-amm\//, "/floor-amm/v2/")] : []);
122
+ return { mount: "chain", query: {}, page: NONE, errors: GATED, gated: true, units: "site", audience: "site", ...rest, params, aliases };
123
+ }
124
+ function partner<T>(s: Spec<T>): RouteContract<T> {
125
+ return { mount: "chain", params: [], query: {}, page: NONE, errors: [...GATED, "bad_query"], gated: true, units: "partner", audience: "partner", aliases: [], ...s };
126
+ }
127
+
128
+ export const INDEXER_CONTRACT = {
129
+
130
+ head: site({ pattern: "/floor-amm/head", aliases: ["/head"], gated: false, errors: [], body: B.HEAD }),
131
+ latestBlock: site({ pattern: "/floor-amm/latest-block", aliases: ["/latest-block"], errors: [...GATED, "not_found"], body: B.LATEST_BLOCK }),
132
+ stream: site({
133
+ pattern: "/floor-amm/stream",
134
+ aliases: ["/stream"],
135
+ sse: true,
136
+ query: {
137
+ launch: { kind: "list", doc: "only these launches' frames (and their quote chains' relatives)" },
138
+ state: { kind: "list", doc: "state frames (the launch whole on each change) for these", max: STREAM_STATE_MAX },
139
+ lastEventId: { kind: "string", doc: "resume after this frame id (EventSource sends Last-Event-ID itself)" },
140
+ },
141
+ body: unknown,
142
+ }),
143
+ quotes: site({ pattern: "/floor-amm/quotes", body: B.QUOTES }),
144
+ summary: site({ pattern: "/floor-amm/summary", aliases: ["/floor-amm/v2/summary"], body: B.SUMMARY }),
145
+ floorRouted: site({ pattern: "/floor-amm/floor-routed", aliases: ["/floor-amm/v2/floor-routed"], body: B.FLOOR_ROUTED }),
146
+ events: site({
147
+ pattern: "/floor-amm/events",
148
+ aliases: ["/events", "/v2/dex/events"],
149
+ query: { fromBlock: { kind: "block", doc: "first block, inclusive", required: true }, toBlock: { kind: "block", doc: "last block, inclusive", required: true } },
150
+ page: { kind: "range", from: "fromBlock", to: "toBlock" },
151
+ errors: [...GATED, "bad_query", "too_many"],
152
+ body: B.EVENTS,
153
+ }),
154
+
155
+ launches: site({
156
+ pattern: "/floor-amm/launches",
157
+ v2: true,
158
+ query: {
159
+ sort: { kind: "enum", doc: "the order (larger first with order=desc)", values: LAUNCH_SORTS, default: "created" },
160
+ order: { kind: "enum", doc: "asc or desc", values: ["asc", "desc"], default: "desc" },
161
+ q: { kind: "string", doc: "name or symbol contains, or an id, token or creator equals" },
162
+ ids: { kind: "list", doc: "these launches (ids or tokens), in the order asked without sort", max: IDS_MAX },
163
+ quote: { kind: "string", doc: "launches quoted in this coin" },
164
+ creator: { kind: "string", doc: "launches by this creator" },
165
+ rankable: { kind: "bool", doc: "true (or 1) listed only, false (or 0) unlisted only" },
166
+ graduated: { kind: "bool", doc: "graduated or not (true / false, or 1 / 0)" },
167
+ limit: LIMIT(LAUNCHES_PAGE_MAX, LAUNCHES_PAGE_MAX),
168
+ offset: { kind: "int", doc: "rows skipped", min: 0, default: 0 },
169
+ },
170
+ page: { kind: "offset", limit: { default: LAUNCHES_PAGE_MAX, max: LAUNCHES_PAGE_MAX }, total: "total" },
171
+ errors: [...GATED, "bad_query"],
172
+ body: B.LAUNCHES,
173
+ }),
174
+ launch: site({ pattern: "/floor-amm/launches/<launch>", v2: true, errors: LAUNCH_ERR, body: B.LAUNCH_ONE }),
175
+ launchState: site({ pattern: "/floor-amm/launches/<launch>/state", v2: true, errors: ["not_ready", "unknown_launch"], body: B.LAUNCH_STATE }),
176
+ milestones: site({ pattern: "/floor-amm/launches/<launch>/milestones", v2: true, errors: LAUNCH_ERR, body: B.LAUNCH_MILESTONES }),
177
+ holders: site({ pattern: "/floor-amm/launches/<launch>/holders", v2: true, query: { limit: LIMIT(100, 500) }, page: limit(100, 500), errors: [...LAUNCH_ERR, "bad_query"], body: B.HOLDERS }),
178
+ trades: site({
179
+ pattern: "/floor-amm/launches/<launch>/trades",
180
+ v2: true,
181
+ query: { limit: LIMIT(100, 500), before: BEFORE, traders: { kind: "list", doc: "only these wallets' trades (EVM case-blind)" } },
182
+ page: cursor(100, 500),
183
+ errors: [...LAUNCH_ERR, "bad_query"],
184
+ body: B.TRADES,
185
+ }),
186
+ launchClaims: site({ pattern: "/floor-amm/launches/<launch>/claims", v2: true, query: { claimer: { kind: "string", doc: "only this claimer's rows" } }, errors: LAUNCH_ERR, body: B.LAUNCH_CLAIMS }),
187
+ devBuys: site({ pattern: "/floor-amm/launches/<launch>/dev-buys", v2: true, errors: LAUNCH_ERR, body: B.DEV_BUYS }),
188
+ traders: site({ pattern: "/floor-amm/launches/<launch>/traders", v2: true, query: { window: WINDOW, limit: LIMIT(100, 500) }, page: limit(100, 500), errors: [...LAUNCH_ERR, "bad_query"], body: B.LAUNCH_TRADERS }),
189
+ quoteChain: site({ pattern: "/floor-amm/launches/<launch>/chain", v2: true, errors: LAUNCH_ERR, body: B.QUOTE_CHAIN }),
190
+ devTrades: site({ pattern: "/floor-amm/launches/<launch>/dev", v2: true, query: { limit: LIMIT(100, 500) }, page: limit(100, 500), errors: [...LAUNCH_ERR, "bad_query"], body: B.DEV_TRADES }),
191
+ burns: site({ pattern: "/floor-amm/launches/<launch>/burns", v2: true, errors: LAUNCH_ERR, body: B.BURNS }),
192
+ launchLocks: site({ pattern: "/floor-amm/launches/<launch>/locks", v2: true, errors: LAUNCH_ERR, body: B.LAUNCH_LOCKS }),
193
+ marks: site({
194
+ pattern: "/floor-amm/launches/<launch>/marks",
195
+ v2: true,
196
+ query: { limit: LIMIT(100, 1_000), before: BEFORE },
197
+ page: cursor(100, 1_000),
198
+ errors: [...LAUNCH_ERR, "bad_query"],
199
+ body: B.MARKS,
200
+ }),
201
+ price: site({ pattern: "/floor-amm/launches/<launch>/price", v2: true, errors: LAUNCH_ERR, body: B.PRICE }),
202
+ highs: site({
203
+ pattern: "/floor-amm/launches/<launch>/highs",
204
+ v2: true,
205
+ query: { atLeast: { kind: "int", doc: "only the highs whose market cap reaches this (quote base units)", min: 0 }, limit: LIMIT(100, 1_000) },
206
+ page: limit(100, 1_000),
207
+ errors: [...LAUNCH_ERR, "bad_query"],
208
+ body: B.HIGHS,
209
+ }),
210
+ candles: site({
211
+ pattern: "/floor-amm/candles",
212
+ aliases: ["/candles", "/floor-amm/v2/candles", "/floor-amm/v2/launches/<launch>/candles"],
213
+ query: {
214
+ launch: { kind: "string", doc: "a launch id or its token", required: true },
215
+ interval: { kind: "enum", doc: "the bucket", values: B.CANDLE_INTERVALS, default: "1h" },
216
+ from: { kind: "unix", doc: "range start (absent: the most candles one read spans, back from to)" },
217
+ to: { kind: "unix", doc: "range end (absent: the indexed head's time)" },
218
+ before: { kind: "unix", doc: "instead of from / to: the newest limit traded buckets starting before it" },
219
+ limit: { kind: "int", doc: "with before only", min: 1, max: B.CANDLES_MAX, default: B.CANDLES_MAX },
220
+ },
221
+ page: { kind: "range", from: "from", to: "to", span: { interval: "interval", max: B.CANDLES_MAX } },
222
+ errors: [...GATED, "bad_query", "unknown_launch", "not_found"],
223
+ body: B.CANDLES,
224
+ }),
225
+ candleBundle: site({
226
+ pattern: "/floor-amm/launches/<launch>/candle-bundle",
227
+ v2: true,
228
+ query: {
229
+ intervals: { kind: "list", doc: "these buckets' pages (absent: every one, in CANDLE_INTERVALS order)", max: B.CANDLE_INTERVALS.length },
230
+ limit: LIMIT(B.CANDLE_BUNDLE_LIMIT, B.CANDLES_MAX),
231
+ },
232
+ page: limit(B.CANDLE_BUNDLE_LIMIT, B.CANDLES_MAX),
233
+ errors: [...LAUNCH_ERR, "bad_query", "not_found"],
234
+ body: B.CANDLE_BUNDLE,
235
+ }),
236
+
237
+ walletTrades: site({
238
+ pattern: "/floor-amm/wallets/<wallet>/trades",
239
+ v2: true,
240
+ query: { limit: LIMIT(100, 500), before: BEFORE, launch: { kind: "string", doc: "only this launch (an id or its token)" } },
241
+ page: cursor(100, 500),
242
+ errors: [...WALLET_ERR, "unknown_launch"],
243
+ body: B.WALLET_TRADES,
244
+ }),
245
+ positions: site({ pattern: "/floor-amm/wallets/<wallet>/positions", v2: true, errors: WALLET_ERR, body: B.POSITIONS }),
246
+ inbox: site({ pattern: "/floor-amm/wallets/<wallet>/inbox", v2: true, query: { limit: LIMIT(1_000, 1_000) }, page: limit(1_000, 1_000), errors: WALLET_ERR, body: B.INBOX }),
247
+ walletLocks: site({ pattern: "/floor-amm/wallets/<wallet>/locks", v2: true, errors: WALLET_ERR, body: B.WALLET_LOCKS }),
248
+ claimHistory: site({ pattern: "/floor-amm/wallets/<wallet>/claims", errors: WALLET_ERR, body: B.CLAIM_HISTORY }),
249
+ firsts: site({ pattern: "/floor-amm/wallets/<wallet>/firsts", errors: WALLET_ERR, body: B.FIRSTS }),
250
+ firstsMany: site({ pattern: "/floor-amm/wallets/firsts", query: { wallets: { kind: "list", doc: "the wallets", required: true, min: 1, max: FIRSTS_MAX } }, errors: WALLET_ERR, body: B.FIRSTS_MANY }),
251
+ claimView: site({ pattern: "/floor-amm/claims/<wallet>", errors: [...WALLET_ERR, "no_reader"], body: B.CLAIM_VIEW }),
252
+ people: site({ pattern: "/floor-amm/referrals/<wallet>/people", errors: WALLET_ERR, body: B.PEOPLE }),
253
+ roles: site({ pattern: "/floor-amm/roles/<wallet>", errors: WALLET_ERR, body: B.ROLES }),
254
+
255
+ traderBoard: site({ pattern: "/floor-amm/leaderboards/traders", v2: true, query: { window: WINDOW, limit: LIMIT(100, 500) }, page: limit(100, 500), errors: [...GATED, "bad_query"], body: B.TRADER_BOARD }),
256
+ launcherBoard: site({ pattern: "/floor-amm/leaderboards/launchers", v2: true, query: { limit: LIMIT(100, 500) }, page: limit(100, 500), errors: [...GATED, "bad_query"], body: B.LAUNCHER_BOARD }),
257
+
258
+ tokenHolders: partner({
259
+ pattern: "/floor-amm/holders/<token>",
260
+ aliases: ["/holders/<token>"],
261
+ params: ["token"],
262
+ query: { limit: LIMIT(100, 500), offset: { kind: "int", doc: "rows skipped", min: 0, default: 0 } },
263
+ page: { kind: "offset", limit: { default: 100, max: 500 }, total: "total" },
264
+ errors: [...GATED, "bad_query", "not_found"],
265
+ body: P.TOKEN_HOLDERS,
266
+ }),
267
+ dexAsset: partner({ pattern: "/v2/dex/asset", aliases: ["/asset"], query: { id: { kind: "string", doc: "a launch's token, or a quote", required: true } }, errors: [...GATED, "bad_query", "not_found", "not_indexed"], body: P.DEX_ASSET }),
268
+ dexSummary: partner({ pattern: "/v2/dex/summary", aliases: ["/summary"], query: { id: { kind: "string", doc: "the pair id", required: true } }, errors: [...GATED, "bad_query", "not_found"], body: P.DEX_SUMMARY }),
269
+ dexPair: partner({ pattern: "/v2/dex/pair", aliases: ["/pair"], query: { id: { kind: "string", doc: "the pair id", required: true } }, errors: [...GATED, "unknown_launch"], body: P.DEX_PAIR }),
270
+ cgPairs: partner({ pattern: "/v2/coingecko/pairs", aliases: ["/coingecko/pairs"], errors: GATED, body: P.CG_PAIRS }),
271
+ cgTickers: partner({ pattern: "/v2/coingecko/tickers", aliases: ["/coingecko/tickers"], errors: GATED, body: P.CG_TICKERS }),
272
+ cgHistoricalTrades: partner({
273
+ pattern: "/v2/coingecko/historical_trades",
274
+ aliases: ["/coingecko/historical_trades", "/historical_trades"],
275
+ query: {
276
+ ticker_id: { kind: "string", doc: "<token>_<quote>", required: true },
277
+ type: { kind: "enum", doc: "one side only", values: ["buy", "sell"] },
278
+ limit: { kind: "int", doc: "rows per side (0: all)", min: 0 },
279
+ start_time: { kind: "unix", doc: "from (10^11 and over: milliseconds)" },
280
+ end_time: { kind: "unix", doc: "to (10^11 and over: milliseconds)" },
281
+ },
282
+ page: { kind: "range", from: "start_time", to: "end_time" },
283
+ errors: [...GATED, "bad_query", "not_found"],
284
+ body: P.CG_HISTORICAL,
285
+ }),
286
+ llamaTvl: partner({ pattern: "/v2/defillama/tvl", errors: GATED, body: P.LLAMA_TVL }),
287
+ llamaFees: partner({
288
+ pattern: "/v2/defillama/fees",
289
+ query: { from: { kind: "unix", doc: "window start, inclusive (with to)" }, to: { kind: "unix", doc: "window end, exclusive (with from)" } },
290
+ page: { kind: "range", from: "from", to: "to" },
291
+ body: P.LLAMA_FEES,
292
+ }),
293
+
294
+ health: { pattern: "/health", aliases: [], mount: "root", params: [], query: {}, page: NONE, errors: [], gated: false, units: "site", audience: "ops", body: P.HEALTH },
295
+ } as const satisfies Record<string, RouteContract<any>>;
296
+
297
+ export type RouteName = keyof typeof INDEXER_CONTRACT;
298
+
299
+ export type RouteBody<N extends RouteName> = (typeof INDEXER_CONTRACT)[N]["body"] extends Decoder<infer T> ? T : never;
300
+
301
+ export const ROUTE_NAMES = Object.keys(INDEXER_CONTRACT) as RouteName[];
302
+
303
+ export function matchRoute(path: string): { name: RouteName; params: Partial<Record<PathParam, string>> } | null {
304
+ const p = path.replace(/\/+$/, "") || "/";
305
+ for (const name of ROUTE_NAMES) {
306
+ const c: RouteContract = INDEXER_CONTRACT[name];
307
+ for (const pat of [c.pattern, ...c.aliases]) {
308
+ const keys: PathParam[] = [];
309
+ const re = new RegExp(`^${pat.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/<(launch|wallet|token)>/g, (_, k: PathParam) => (keys.push(k), "([^/]+)"))}$`);
310
+ const m = re.exec(p);
311
+ if (m === null) continue;
312
+ const params: Partial<Record<PathParam, string>> = {};
313
+ keys.forEach((k, i) => (params[k] = decodeURIComponent(m[i + 1])));
314
+ return { name, params };
315
+ }
316
+ }
317
+ return null;
318
+ }
319
+
320
+ export type Served<T> = T extends bigint
321
+ ? bigint | string | number
322
+ : T extends readonly (infer E)[]
323
+ ? readonly Served<E>[]
324
+ : T extends object
325
+ ? { [K in keyof T]: Served<T[K]> }
326
+ : T;
327
+
328
+ export type ServedBody<N extends RouteName> = Served<RouteBody<N>>;
329
+
330
+ export type ServedKeys<N extends RouteName> = RouteBody<N> extends readonly unknown[] ? readonly unknown[] : { [K in keyof RouteBody<N>]: unknown };
331
+
332
+ export const OPEN_ROUTES = {
333
+
334
+ genesisSeries: { pattern: "/floor-amm/genesis/series", served: false, open: "undecided: kept or dropped with the site's row" },
335
+
336
+ points: { pattern: null, served: false, open: "undecided: a points route, or the trades drain as now" },
337
+ } as const;
338
+
339
+ export function routeLimit(name: RouteName): { readonly default: number; readonly max: number } | null {
340
+ const p: Pagination = INDEXER_CONTRACT[name].page;
341
+ return p.kind === "limit" || p.kind === "offset" || p.kind === "cursor" ? p.limit : null;
342
+ }
343
+
344
+ export const LIMITS = Object.fromEntries(ROUTE_NAMES.flatMap((n) => {
345
+ const l = routeLimit(n);
346
+ return l === null ? [] : [[n, l]];
347
+ })) as Readonly<Partial<Record<RouteName, { readonly default: number; readonly max: number }>>>;
348
+
349
+ export function clampLimit(name: RouteName, n: number): number {
350
+ const l = routeLimit(name);
351
+ return l === null ? n : Math.min(Math.max(1, Math.trunc(n)), l.max);
352
+ }
353
+
354
+ const DIGITS = /^\d+$/;
355
+
356
+ export function queryLimit(name: RouteName, q: URLSearchParams): number {
357
+ const l = routeLimit(name);
358
+ if (l === null) throw new TypeError(`${name} takes no limit`);
359
+ const raw = q.get("limit");
360
+ return raw === null || raw === "" || !DIGITS.test(raw) ? l.default : clampLimit(name, Number(raw));
361
+ }
362
+
363
+ export function queryRefusal(name: RouteName, q: URLSearchParams): string | null {
364
+ const spec: Readonly<Record<string, QueryKey>> = INDEXER_CONTRACT[name].query;
365
+ for (const [key, k] of Object.entries(spec)) {
366
+ const raw = q.get(key);
367
+ if (raw === null || raw === "") continue;
368
+ switch (k.kind) {
369
+ case "int": {
370
+ const lo = k.min ?? 0;
371
+ const n = DIGITS.test(raw) ? Number(raw) : NaN;
372
+ if (!(n >= lo) || (k.max !== undefined && n > k.max)) return k.max === undefined ? `${key} must be an integer ≥ ${lo}` : `${key} must be ${lo}..${k.max}`;
373
+ break;
374
+ }
375
+ case "list": {
376
+ const n = raw.split(",").filter((s) => s !== "").length;
377
+ if (k.max !== undefined && n > k.max) return `at most ${k.max} ${key}`;
378
+ break;
379
+ }
380
+ case "enum":
381
+ if (k.values !== undefined && !k.values.includes(raw)) return `${key} must be one of ${k.values.join(", ")}`;
382
+ break;
383
+ case "bool":
384
+ if (!(raw in BOOLS)) return `${key} must be true or false`;
385
+ break;
386
+ default:
387
+ break;
388
+ }
389
+ }
390
+ return spanRefusal(name, q);
391
+ }
392
+
393
+ const BOOLS: Readonly<Record<string, boolean>> = { true: true, false: false, 1: true, 0: false };
394
+
395
+ export function queryArg(name: RouteName, q: URLSearchParams, key: string): string | undefined {
396
+ const k: QueryKey | undefined = (INDEXER_CONTRACT[name].query as Readonly<Record<string, QueryKey>>)[key];
397
+ if (k === undefined) throw new TypeError(`${name} reads no ${key}`);
398
+ const raw = q.get(key);
399
+ return raw !== null && raw !== "" ? raw : k.default === undefined ? undefined : String(k.default);
400
+ }
401
+
402
+ export function queryBool(name: RouteName, q: URLSearchParams, key: string): boolean | null {
403
+ const raw = queryArg(name, q, key);
404
+ return raw === undefined ? null : (BOOLS[raw] ?? null);
405
+ }
406
+
407
+ export function spanRefusal(name: RouteName, q: URLSearchParams, toDefault?: number): string | null {
408
+ const p: Pagination = INDEXER_CONTRACT[name].page;
409
+ if (p.kind !== "range" || p.span === undefined) return null;
410
+ const sec = (B.CANDLE_INTERVAL_SECS as Readonly<Record<string, number>>)[queryArg(name, q, p.span.interval) ?? ""];
411
+ const fromRaw = q.get(p.from), toRaw = q.get(p.to);
412
+ if (sec === undefined || fromRaw === null || !DIGITS.test(fromRaw)) return null;
413
+ const to = toRaw === null ? toDefault : DIGITS.test(toRaw) ? Number(toRaw) : undefined;
414
+ if (to === undefined) return null;
415
+ const from = Number(fromRaw);
416
+ if (from > to) return null;
417
+ const bucket = (t: number) => Math.floor(t / sec) * sec;
418
+ return (bucket(to) - bucket(from)) / sec + 1 > p.span.max ? `the range spans more than ${p.span.max} candles` : null;
419
+ }