@flayerlabs/gamemode-gate 0.5.5 → 0.6.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 (54) hide show
  1. package/DEPLOY.md +37 -9
  2. package/README.md +7 -1
  3. package/dist/chain/chains.d.ts +14 -6
  4. package/dist/chain/chains.d.ts.map +1 -1
  5. package/dist/chain/chains.js +8 -4
  6. package/dist/chain/chains.js.map +1 -1
  7. package/dist/chain/discover.d.ts +61 -3
  8. package/dist/chain/discover.d.ts.map +1 -1
  9. package/dist/chain/discover.js +181 -21
  10. package/dist/chain/discover.js.map +1 -1
  11. package/dist/chain/registry-prices.d.ts +69 -0
  12. package/dist/chain/registry-prices.d.ts.map +1 -0
  13. package/dist/chain/registry-prices.js +157 -0
  14. package/dist/chain/registry-prices.js.map +1 -0
  15. package/dist/chain/secure.d.ts +28 -0
  16. package/dist/chain/secure.d.ts.map +1 -1
  17. package/dist/chain/secure.js +55 -20
  18. package/dist/chain/secure.js.map +1 -1
  19. package/dist/economy.d.ts.map +1 -1
  20. package/dist/economy.js +12 -3
  21. package/dist/economy.js.map +1 -1
  22. package/dist/index.d.ts +7 -4
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/main.d.ts +14 -3
  27. package/dist/main.d.ts.map +1 -1
  28. package/dist/main.js +44 -11
  29. package/dist/main.js.map +1 -1
  30. package/dist/room.d.ts +7 -0
  31. package/dist/room.d.ts.map +1 -1
  32. package/dist/room.js +15 -6
  33. package/dist/room.js.map +1 -1
  34. package/dist/server.d.ts +26 -0
  35. package/dist/server.d.ts.map +1 -1
  36. package/dist/server.js +21 -0
  37. package/dist/server.js.map +1 -1
  38. package/dist/store.d.ts +1 -1
  39. package/dist/store.d.ts.map +1 -1
  40. package/dist/store.js +6 -0
  41. package/dist/store.js.map +1 -1
  42. package/dist/version.js +2 -2
  43. package/package.json +2 -2
  44. package/src/chain/chains.ts +14 -6
  45. package/src/chain/discover.ts +212 -21
  46. package/src/chain/registry-prices.ts +194 -0
  47. package/src/chain/secure.ts +75 -31
  48. package/src/economy.ts +13 -3
  49. package/src/index.ts +7 -4
  50. package/src/main.ts +50 -11
  51. package/src/room.ts +14 -3
  52. package/src/server.ts +49 -0
  53. package/src/store.ts +6 -0
  54. package/src/version.ts +2 -2
@@ -1,5 +1,6 @@
1
1
  import { encodeAbiParameters, keccak256, parseAbi, type PublicClient } from 'viem';
2
2
  import { ETH_SPEND_TOKEN, type SpendToken } from '@flayerlabs/gamemode-spec/live';
3
+ import { checkPositionManagerWiring, type PositionManagerWiring } from './secure.js';
3
4
 
4
5
  /**
5
6
  * All this needs of a client: the ability to read a contract.
@@ -22,11 +23,15 @@ export type ChainReader = Pick<PublicClient, 'readContract'>;
22
23
  * can forge. So adoption needs no API key and no allowlist — anyone may ask, and the chain decides.
23
24
  * That single property is what makes third-party games permissionless.
24
25
  *
25
- * A gate serves exactly one (PositionManager, calculator) pair and adopts only coins launched on
26
- * THAT manager: `poolKey(coin)` is asked of the configured manager alone, so a coin on a superseded
27
- * generation of hooks (which keeps trading on its own gate) reads back as not a launch here. That
28
- * is deliberate — the EIP-712 domain binds every authorisation to the calculator, so a coin this
29
- * gate cannot sign for must not be given a room by it.
26
+ * A gate serves one calculator and adopts a coin on ANY PositionManager wired to it. The coin
27
+ * names its own manager (`Memecoin.flaunch()` is the launch ERC721, whose `positionManager()` is
28
+ * the hook), and that manager is accepted when its fee wiring routes to the gate's calculator —
29
+ * the same three reads boot makes of the primary manager, made here per manager and cached. There
30
+ * is no list: wiring a new manager to the dispatcher on chain is what approves it. A coin on a
31
+ * manager wired to some OTHER calculator is refused for good — the EIP-712 domain binds every
32
+ * authorisation to the calculator, so a coin this gate cannot sign for must not be given a room
33
+ * by it — and every later read (`poolKey`, `flaunchesAt`, `pairedToken`) is asked of the coin's
34
+ * own manager, never the configured one.
30
35
  */
31
36
 
32
37
  const poolKeyComponents = [
@@ -37,6 +42,12 @@ const poolKeyComponents = [
37
42
  { name: 'hooks', type: 'address' },
38
43
  ] as const;
39
44
 
45
+ /** What a coin knows about its own launch: `flaunch()` is the ERC721 that minted it. */
46
+ const memecoinAbi = parseAbi(['function flaunch() view returns (address)']);
47
+
48
+ /** The launch ERC721 (`Flaunch`, `AnyFlaunch`) names the PositionManager that hooks its pools. */
49
+ const flaunchAbi = parseAbi(['function positionManager() view returns (address)']);
50
+
40
51
  export const positionManagerAbi = [
41
52
  {
42
53
  type: 'function',
@@ -91,6 +102,11 @@ export interface Launch {
91
102
  name: string;
92
103
  symbol: string;
93
104
  imageUrl?: string | null;
105
+ /**
106
+ * The PositionManager the coin was launched on — the pool's hook — resolved from the coin
107
+ * itself. Absent only from hand-built launches (demos, tests), where it means the primary one.
108
+ */
109
+ positionManager?: `0x${string}`;
94
110
  /**
95
111
  * The token spend is measured in: the coin's paired token, read from the manager. Absent only
96
112
  * from hand-built launches (demos, tests), where it means ETH.
@@ -115,12 +131,122 @@ export interface Refused {
115
131
  export type LaunchCheck = ({ ok: true } & Launch) | Refused;
116
132
 
117
133
  export interface Deployment {
134
+ /**
135
+ * The primary manager: what boot asserted and `/config` announces. Adoption does not require a
136
+ * coin to be on it — see {@link verifyLaunch} — but it is the one manager known wired before any
137
+ * coin arrives, so its wiring is never asked of the chain again.
138
+ */
118
139
  positionManager: `0x${string}`;
119
140
  spendGatedCalculator: `0x${string}`;
120
141
  /** The signer this gate holds. A launch naming anyone else is not ours to run. */
121
142
  signer: `0x${string}`;
122
143
  }
123
144
 
145
+ /**
146
+ * Whether a manager's fee wiring routes to a calculator. {@link checkPositionManagerWiring} is the
147
+ * one implementation; this is its shape, so a test can stand in for the chain.
148
+ */
149
+ export type WiringCheck = (
150
+ client: ChainReader,
151
+ wiring: { positionManager: `0x${string}`; spendGatedCalculator: `0x${string}` },
152
+ ) => Promise<PositionManagerWiring>;
153
+
154
+ /**
155
+ * Remembers which managers are wired to this gate's calculator, so the three wiring reads happen
156
+ * once per manager rather than once per coin.
157
+ *
158
+ * A yes is kept for the life of the process: wiring is a one-time owner action, and un-wiring a
159
+ * manager with live pools would also strand every coin already adopted on it, so nothing is lost
160
+ * by not re-asking. A no is kept a minute — long enough that a coin page polling an unwired
161
+ * manager is not a lever on the RPC, short enough that the owner wiring it up sees the gate follow.
162
+ */
163
+ export class WiringCache {
164
+ private readonly verdicts = new Map<string, { verdict: PositionManagerWiring; until: number }>();
165
+ private readonly inFlight = new Map<string, Promise<PositionManagerWiring>>();
166
+
167
+ constructor(
168
+ private readonly check: WiringCheck = checkPositionManagerWiring,
169
+ private readonly now: () => number = Date.now,
170
+ private readonly negativeHoldMs = 60_000,
171
+ ) {}
172
+
173
+ async isWired(
174
+ client: ChainReader,
175
+ positionManager: `0x${string}`,
176
+ spendGatedCalculator: `0x${string}`,
177
+ ): Promise<PositionManagerWiring> {
178
+ const key = positionManager.toLowerCase();
179
+ const cached = this.verdicts.get(key);
180
+ if (cached && cached.until > this.now()) return cached.verdict;
181
+
182
+ const existing = this.inFlight.get(key);
183
+ if (existing) return existing;
184
+
185
+ const flight = this.check(client, { positionManager, spendGatedCalculator })
186
+ .then((verdict) => {
187
+ const until = verdict.ok ? Number.POSITIVE_INFINITY : this.now() + this.negativeHoldMs;
188
+ this.verdicts.set(key, { verdict, until });
189
+ return verdict;
190
+ })
191
+ .finally(() => this.inFlight.delete(key));
192
+ this.inFlight.set(key, flight);
193
+ return flight;
194
+ }
195
+
196
+ /** A fresh cache that already trusts the primary manager, which boot asserted before any coin arrived. */
197
+ static trusting(positionManager: `0x${string}`): WiringCache {
198
+ const cache = new WiringCache();
199
+ cache.trust(positionManager);
200
+ return cache;
201
+ }
202
+
203
+ /** Record a manager known wired without asking — the primary one, which boot already asserted. */
204
+ trust(positionManager: `0x${string}`, dispatcher: `0x${string}` = ZERO_ADDRESS): void {
205
+ this.verdicts.set(positionManager.toLowerCase(), {
206
+ verdict: { ok: true, dispatcher },
207
+ until: Number.POSITIVE_INFINITY,
208
+ });
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Which PositionManager a coin was launched on, from the coin itself.
214
+ *
215
+ * Two reads: `Memecoin.flaunch()` names the launch ERC721 that minted the coin, and that contract's
216
+ * `positionManager()` names the hook. Both are public state written at launch, so the answer is the
217
+ * coin's and cannot be steered by whoever offers it for adoption. Null when the CONTRACT says no —
218
+ * an address with no code, or one that is not a Flaunch coin, answers `flaunch()` with no data.
219
+ * An RPC that did not answer is not a statement about the coin, so that is thrown to the caller
220
+ * rather than folded into null.
221
+ */
222
+ export async function resolvePositionManager(
223
+ client: ChainReader,
224
+ memecoin: `0x${string}`,
225
+ ): Promise<`0x${string}` | null> {
226
+ let flaunch: `0x${string}`;
227
+ try {
228
+ flaunch = (await client.readContract({ address: memecoin, abi: memecoinAbi, functionName: 'flaunch' })) as `0x${string}`;
229
+ } catch (error) {
230
+ if (isMissingFunction(error)) return null;
231
+ throw error;
232
+ }
233
+ if (!flaunch || flaunch.toLowerCase() === ZERO_ADDRESS) return null;
234
+
235
+ let manager: `0x${string}`;
236
+ try {
237
+ manager = (await client.readContract({
238
+ address: flaunch,
239
+ abi: flaunchAbi,
240
+ functionName: 'positionManager',
241
+ })) as `0x${string}`;
242
+ } catch (error) {
243
+ if (isMissingFunction(error)) return null;
244
+ throw error;
245
+ }
246
+ if (!manager || manager.toLowerCase() === ZERO_ADDRESS) return null;
247
+ return manager;
248
+ }
249
+
124
250
  export function poolIdOf(key: PoolKey): `0x${string}` {
125
251
  return keccak256(
126
252
  encodeAbiParameters(
@@ -142,11 +268,28 @@ export async function verifyLaunch(
142
268
  client: ChainReader,
143
269
  deployment: Deployment,
144
270
  memecoin: `0x${string}`,
271
+ wiring: WiringCache = WiringCache.trusting(deployment.positionManager),
145
272
  ): Promise<LaunchCheck> {
273
+ // The coin's own manager first. A coin the protocol has never heard of has no `flaunch()`, which
274
+ // is still "not yet": the coin page loads the instant a launch is submitted, before the chain has
275
+ // caught up, and that must not be remembered as "no".
276
+ let positionManager: `0x${string}` | null;
277
+ try {
278
+ positionManager = await resolvePositionManager(client, memecoin);
279
+ } catch {
280
+ return refuse('launch.unreadable', true);
281
+ }
282
+ if (!positionManager) return refuse('launch.not_flaunched', true);
283
+
284
+ // Approval is a fact about the chain: is this manager's fee wiring routed to OUR calculator? A
285
+ // manager wired elsewhere is another gate's, permanently — no amount of waiting rewires it.
286
+ const wired = await wiring.isWired(client, positionManager, deployment.spendGatedCalculator);
287
+ if (!wired.ok) return refuse('launch.unapproved_position_manager', false);
288
+
146
289
  let poolKey: PoolKey;
147
290
  try {
148
291
  poolKey = (await client.readContract({
149
- address: deployment.positionManager,
292
+ address: positionManager,
150
293
  abi: positionManagerAbi,
151
294
  functionName: 'poolKey',
152
295
  args: [memecoin],
@@ -164,9 +307,8 @@ export async function verifyLaunch(
164
307
 
165
308
  let settings: readonly [boolean, bigint, `0x${string}`, bigint];
166
309
  let trusted: readonly [`0x${string}`, boolean];
167
- let flaunchesAt: bigint;
168
310
  try {
169
- [settings, trusted, flaunchesAt] = (await Promise.all([
311
+ [settings, trusted] = (await Promise.all([
170
312
  client.readContract({
171
313
  address: deployment.spendGatedCalculator,
172
314
  abi: spendGatedAbi,
@@ -179,17 +321,27 @@ export async function verifyLaunch(
179
321
  functionName: 'trustedPoolKeySigner',
180
322
  args: [poolId],
181
323
  }),
182
- client.readContract({
183
- address: deployment.positionManager,
184
- abi: positionManagerAbi,
185
- functionName: 'flaunchesAt',
186
- args: [poolId],
187
- }),
188
- ])) as [typeof settings, typeof trusted, bigint];
324
+ ])) as [typeof settings, typeof trusted];
189
325
  } catch {
190
326
  return refuse('launch.unreadable', true);
191
327
  }
192
328
 
329
+ // The window's open is the manager's to report. A manager that is wired but has no
330
+ // `flaunchesAt` is a generation this gate has no round model for — a permanent fact about the
331
+ // contract, not an outage, so it is refused as unsupported rather than as unreadable and retried
332
+ // forever.
333
+ let flaunchesAt: bigint;
334
+ try {
335
+ flaunchesAt = (await client.readContract({
336
+ address: positionManager,
337
+ abi: positionManagerAbi,
338
+ functionName: 'flaunchesAt',
339
+ args: [poolId],
340
+ })) as bigint;
341
+ } catch (error) {
342
+ return refuse(isMissingFunction(error) ? 'launch.unsupported_position_manager' : 'launch.unreadable', !isMissingFunction(error));
343
+ }
344
+
193
345
  const [enabled, walletCap, , endsAt] = settings;
194
346
  const [signer, signerEnabled] = trusted;
195
347
 
@@ -204,7 +356,7 @@ export async function verifyLaunch(
204
356
  const closesAt = Number(endsAt) * 1000;
205
357
  if (closesAt <= Date.now()) return refuse('launch.already_over', false);
206
358
 
207
- const spendToken = await resolveSpendToken(client, deployment, memecoin, poolKey, poolId);
359
+ const spendToken = await resolveSpendToken(client, positionManager, memecoin, poolKey, poolId);
208
360
  if (!spendToken) return refuse('launch.paired_unreadable', true);
209
361
 
210
362
  let name = '';
@@ -231,9 +383,38 @@ export async function verifyLaunch(
231
383
  name,
232
384
  symbol,
233
385
  spendToken,
386
+ positionManager,
234
387
  };
235
388
  }
236
389
 
390
+ /**
391
+ * Did a read fail because the contract has no such function, rather than because the chain did
392
+ * not answer? viem reports the former as a call that returned no data or reverted at the
393
+ * contract (`ContractFunctionZeroDataError`, `ContractFunctionRevertedError`); a transport
394
+ * failure looks nothing like it, and a `view` that exists does not revert on a pool id.
395
+ */
396
+ function isMissingFunction(error: unknown): boolean {
397
+ const seen = new Set<unknown>();
398
+ let current: unknown = error;
399
+ while (current && typeof current === 'object' && !seen.has(current)) {
400
+ seen.add(current);
401
+ const name = (current as { name?: unknown }).name;
402
+ if (
403
+ name === 'ContractFunctionZeroDataError' ||
404
+ name === 'AbiDecodingZeroDataError' ||
405
+ name === 'ContractFunctionRevertedError'
406
+ ) {
407
+ return true;
408
+ }
409
+ const message = (current as { message?: unknown }).message;
410
+ if (typeof message === 'string' && /returned no data|zero data|function (selector )?was not (recognized|found)/i.test(message)) {
411
+ return true;
412
+ }
413
+ current = (current as { cause?: unknown }).cause;
414
+ }
415
+ return false;
416
+ }
417
+
237
418
  /**
238
419
  * Which token this pool's spend is measured in.
239
420
  *
@@ -246,7 +427,7 @@ export async function verifyLaunch(
246
427
  */
247
428
  async function resolveSpendToken(
248
429
  client: ChainReader,
249
- deployment: Deployment,
430
+ positionManager: `0x${string}`,
250
431
  memecoin: `0x${string}`,
251
432
  poolKey: PoolKey,
252
433
  poolId: `0x${string}`,
@@ -254,7 +435,7 @@ async function resolveSpendToken(
254
435
  let paired: `0x${string}`;
255
436
  try {
256
437
  paired = (await client.readContract({
257
- address: deployment.positionManager,
438
+ address: positionManager,
258
439
  abi: positionManagerAbi,
259
440
  functionName: 'pairedToken',
260
441
  args: [poolId],
@@ -278,7 +459,7 @@ async function resolveSpendToken(
278
459
  /**
279
460
  * Verification with a memory, because every coin-page view asks.
280
461
  *
281
- * Unmemoised, each call costs five chain reads against one endpoint from one address — which is a
462
+ * Unmemoised, each call costs seven chain reads against one endpoint from one address — which is a
282
463
  * free denial-of-service lever, and public endpoints rate-limit long before a launch does.
283
464
  *
284
465
  * A positive verdict is cached until the window closes, because a launch that qualifies cannot
@@ -288,12 +469,22 @@ async function resolveSpendToken(
288
469
  export class Discovery {
289
470
  private readonly verdicts = new Map<string, { verdict: LaunchCheck; until: number }>();
290
471
  private readonly inFlight = new Map<string, Promise<LaunchCheck>>();
472
+ /**
473
+ * Which managers are wired to this gate's calculator, remembered per manager. The primary one is
474
+ * trusted from the start: boot asserted it, and asking again would be the only three reads that
475
+ * could never answer differently.
476
+ */
477
+ readonly wiring: WiringCache;
291
478
 
292
479
  constructor(
293
480
  private readonly client: ChainReader,
294
481
  private readonly deployment: Deployment,
295
482
  private readonly now: () => number = Date.now,
296
- ) {}
483
+ wiring: WiringCache = new WiringCache(checkPositionManagerWiring, now),
484
+ ) {
485
+ this.wiring = wiring;
486
+ this.wiring.trust(deployment.positionManager);
487
+ }
297
488
 
298
489
  async verify(memecoin: `0x${string}`): Promise<LaunchCheck> {
299
490
  const key = memecoin.toLowerCase();
@@ -305,7 +496,7 @@ export class Discovery {
305
496
  const existing = this.inFlight.get(key);
306
497
  if (existing) return existing;
307
498
 
308
- const flight = verifyLaunch(this.client, this.deployment, memecoin)
499
+ const flight = verifyLaunch(this.client, this.deployment, memecoin, this.wiring)
309
500
  .then((verdict) => {
310
501
  this.verdicts.set(key, { verdict, until: this.now() + this.holdFor(verdict) });
311
502
  return verdict;
@@ -0,0 +1,194 @@
1
+ import { formatUnits, parseAbi, type PublicClient } from 'viem';
2
+ import type { SpendToken } from '@flayerlabs/gamemode-spec/live';
3
+ import type { AnnouncedSpendToken, PriceFor } from '../server.js';
4
+ import { resolveEconomy, unitsPerToken } from '../economy.js';
5
+
6
+ /**
7
+ * Prices for any paired token the chain itself has approved, so a gate runs rounds on every
8
+ * pairing the protocol allows without anyone listing it first.
9
+ *
10
+ * A v1.3 PositionManager names its `PairedTokenRegistry`, and the registry names the price
11
+ * calculator each approved token was registered with — the same quote a launch uses to size a
12
+ * coin's starting price. That calculator answers "how many tokens is one ETH", and the operator's
13
+ * `USD_PER_ETH` turns that into dollars. Nothing here is typed by a person: an unapproved token has
14
+ * no calculator and is refused, exactly as the launch itself would be.
15
+ *
16
+ * Quotes are cached briefly. Adoption happens once per launch, so the cache protects the RPC from a
17
+ * burst of `/config/spend-tokens` reads by launch tooling, not from adoption itself. A quote that
18
+ * cannot be read throws, and the server answers adoption with 503 rather than a made-up price.
19
+ */
20
+
21
+ const managerAbi = parseAbi(['function pairedTokenRegistry() view returns (address)']);
22
+ const registryAbi = parseAbi([
23
+ 'function isApproved(address token) view returns (bool)',
24
+ 'function tokenConfig(address token) view returns ((bool approved, uint8 tokenType, uint8 decimals, address underlying, address feeEscrow, address priceCalculator, uint256 minDistribute, uint256 bidWallThreshold))',
25
+ ]);
26
+ const calculatorAbi = parseAbi(['function ethToPairedToken(uint256 ethAmount) view returns (uint256)']);
27
+ const erc20Abi = parseAbi(['function symbol() view returns (string)', 'function decimals() view returns (uint8)']);
28
+
29
+ const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
30
+
31
+ /** The subset of a viem public client this module needs, so tests can script it. */
32
+ export type RegistryReader = Pick<PublicClient, 'readContract'>;
33
+
34
+ export interface RegistryPricesOptions {
35
+ /** The manager whose registry decides which pairings exist. */
36
+ positionManager: `0x${string}`;
37
+ /** The chain's flETH wrapper, priced as ETH and never asked of the registry. */
38
+ fleth?: `0x${string}`;
39
+ /** Dollars per ETH; every registry quote is in ETH. */
40
+ usdPerEth: number;
41
+ /** How long a quote is reused, in milliseconds. */
42
+ ttlMs?: number;
43
+ /** Injectable for tests. */
44
+ now?: () => number;
45
+ }
46
+
47
+ export interface RegistryQuote {
48
+ /** Dollars per whole token, to eight significant digits. */
49
+ usdPerToken: number;
50
+ /** Whole tokens per ETH as the registry's calculator quoted them. */
51
+ tokensPerEth: number;
52
+ priceCalculator: `0x${string}`;
53
+ }
54
+
55
+ /** What `/config/spend-tokens/:address` needs to size a launch's cap. */
56
+ export interface AnnounceOptions {
57
+ maxPointsPerPlayer: number;
58
+ pointsPerDollar: number;
59
+ /** Percent added over the smallest cap a flawless round fits under. */
60
+ headroomPercent: number;
61
+ }
62
+
63
+ export class RegistryPrices {
64
+ private registry: Promise<`0x${string}` | null> | undefined;
65
+ private readonly quotes = new Map<string, { quote: RegistryQuote | null; at: number }>();
66
+ private readonly ttlMs: number;
67
+ private readonly now: () => number;
68
+
69
+ constructor(
70
+ private readonly client: RegistryReader,
71
+ private readonly options: RegistryPricesOptions,
72
+ ) {
73
+ this.ttlMs = options.ttlMs ?? 60_000;
74
+ this.now = options.now ?? Date.now;
75
+ }
76
+
77
+ /**
78
+ * The registry the manager names, or null for a manager that predates paired tokens. Read once:
79
+ * the address is immutable on chain, and a gate serves exactly one manager.
80
+ */
81
+ registryAddress(): Promise<`0x${string}` | null> {
82
+ this.registry ??= this.client
83
+ .readContract({ address: this.options.positionManager, abi: managerAbi, functionName: 'pairedTokenRegistry' })
84
+ .then((address) => (address.toLowerCase() === ZERO_ADDRESS ? null : address))
85
+ .catch(() => null);
86
+ return this.registry;
87
+ }
88
+
89
+ /** ETH by any name is the operator's `USD_PER_ETH`; it is never asked of the registry. */
90
+ private isEthEquivalent(address: string): boolean {
91
+ const lower = address.toLowerCase();
92
+ return lower === ZERO_ADDRESS || (this.options.fleth !== undefined && lower === this.options.fleth.toLowerCase());
93
+ }
94
+
95
+ /**
96
+ * The registry's quote for a token, or null when it is not approved or has no calculator.
97
+ * Throws when the chain cannot be read, so a caller refuses for now rather than for good.
98
+ */
99
+ async quote(address: string): Promise<RegistryQuote | null> {
100
+ const key = address.toLowerCase();
101
+ const cached = this.quotes.get(key);
102
+ if (cached && this.now() - cached.at < this.ttlMs) return cached.quote;
103
+ const quote = await this.read(address as `0x${string}`);
104
+ this.quotes.set(key, { quote, at: this.now() });
105
+ return quote;
106
+ }
107
+
108
+ private async read(token: `0x${string}`): Promise<RegistryQuote | null> {
109
+ const registry = await this.registryAddress();
110
+ if (!registry) return null;
111
+ const approved = await this.client.readContract({ address: registry, abi: registryAbi, functionName: 'isApproved', args: [token] });
112
+ if (!approved) return null;
113
+ const config = await this.client.readContract({ address: registry, abi: registryAbi, functionName: 'tokenConfig', args: [token] });
114
+ const priceCalculator = config.priceCalculator;
115
+ if (!priceCalculator || priceCalculator.toLowerCase() === ZERO_ADDRESS) return null;
116
+ const decimals = Number(config.decimals);
117
+ const perEth = await this.client.readContract({
118
+ address: priceCalculator,
119
+ abi: calculatorAbi,
120
+ functionName: 'ethToPairedToken',
121
+ args: [unitsPerToken(18)],
122
+ });
123
+ if (perEth <= 0n) return null;
124
+ // String-based division: no binary float noise in a whole-token quote.
125
+ const tokensPerEth = Number(formatUnits(perEth, decimals));
126
+ if (!Number.isFinite(tokensPerEth) || tokensPerEth <= 0) return null;
127
+ const usdPerToken = Number((this.options.usdPerEth / tokensPerEth).toPrecision(8));
128
+ return { usdPerToken, tokensPerEth, priceCalculator };
129
+ }
130
+
131
+ /** A {@link PriceFor}: dollars per whole token for any approved pairing, null for the rest. */
132
+ priceFor: PriceFor = async (token: SpendToken) => {
133
+ if (this.isEthEquivalent(token.address)) return null;
134
+ const quote = await this.quote(token.address);
135
+ return quote?.usdPerToken ?? null;
136
+ };
137
+
138
+ /**
139
+ * The entry launch tooling needs before a coin is paid for: the token as the chain describes
140
+ * it, the price the gate will fix a round at, and the smallest per-wallet cap a flawless round
141
+ * fits under plus the operator's headroom. Null for a token the registry does not approve.
142
+ */
143
+ async announce(address: `0x${string}`, options: AnnounceOptions): Promise<AnnouncedSpendToken | null> {
144
+ if (this.isEthEquivalent(address)) return null;
145
+ const quote = await this.quote(address);
146
+ if (!quote) return null;
147
+ const [symbol, decimals] = await Promise.all([
148
+ this.client.readContract({ address, abi: erc20Abi, functionName: 'symbol' }),
149
+ this.client.readContract({ address, abi: erc20Abi, functionName: 'decimals' }).then(Number),
150
+ ]);
151
+ const walletCap = minimumWalletCap(quote.usdPerToken, decimals, options);
152
+ if (walletCap === null) return null;
153
+ return {
154
+ address,
155
+ symbol,
156
+ decimals,
157
+ usdPerToken: quote.usdPerToken,
158
+ walletCap: withHeadroom(walletCap, options.headroomPercent).toString(),
159
+ };
160
+ }
161
+ }
162
+
163
+ /**
164
+ * The smallest per-wallet cap under which a flawless round fits, in the token's base units, or
165
+ * null when no cap makes the economy work at this price. Checked against {@link resolveEconomy}
166
+ * rather than trusted, because that function is the one place the rule is written down.
167
+ */
168
+ export function minimumWalletCap(
169
+ usdPerToken: number,
170
+ decimals: number,
171
+ options: Pick<AnnounceOptions, 'maxPointsPerPlayer' | 'pointsPerDollar'>,
172
+ ): bigint | null {
173
+ const pointsPerToken = Math.round(usdPerToken * options.pointsPerDollar);
174
+ if (pointsPerToken <= 0) return null;
175
+ const unitsPerPoint = unitsPerToken(decimals) / BigInt(pointsPerToken);
176
+ if (unitsPerPoint <= 0n) return null;
177
+ const minimum = BigInt(Math.floor(options.maxPointsPerPlayer)) * unitsPerPoint;
178
+ const fit = resolveEconomy({
179
+ maxPointsPerPlayer: options.maxPointsPerPlayer,
180
+ walletCap: minimum,
181
+ pointsPerDollar: options.pointsPerDollar,
182
+ usdPerSpendToken: usdPerToken,
183
+ decimals,
184
+ });
185
+ return fit.ok ? minimum : null;
186
+ }
187
+
188
+ /** A cap with the operator's percentage headroom, rounded down to base units. */
189
+ export function withHeadroom(cap: bigint, headroomPercent: number): bigint {
190
+ if (!Number.isSafeInteger(headroomPercent) || headroomPercent < 0) {
191
+ throw new Error('headroom percent must be a non-negative integer');
192
+ }
193
+ return (cap * BigInt(100 + headroomPercent)) / 100n;
194
+ }