faucet-server-app 0.1.0 → 0.3.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 (51) hide show
  1. package/dist/esm/api/index.d.ts +41 -1
  2. package/dist/esm/api/index.d.ts.map +1 -1
  3. package/dist/esm/api/index.js +395 -41
  4. package/dist/esm/api/index.js.map +1 -1
  5. package/dist/esm/calls.d.ts +107 -0
  6. package/dist/esm/calls.d.ts.map +1 -0
  7. package/dist/esm/calls.js +304 -0
  8. package/dist/esm/calls.js.map +1 -0
  9. package/dist/esm/chains.d.ts +884 -786
  10. package/dist/esm/chains.d.ts.map +1 -1
  11. package/dist/esm/chains.js +155 -1
  12. package/dist/esm/chains.js.map +1 -1
  13. package/dist/esm/config.d.ts +18 -0
  14. package/dist/esm/config.d.ts.map +1 -0
  15. package/dist/esm/config.js +56 -0
  16. package/dist/esm/config.js.map +1 -0
  17. package/dist/esm/env.d.ts +46 -1
  18. package/dist/esm/env.d.ts.map +1 -1
  19. package/dist/esm/env.js +55 -7
  20. package/dist/esm/env.js.map +1 -1
  21. package/dist/esm/index.d.ts +87 -0
  22. package/dist/esm/index.d.ts.map +1 -1
  23. package/dist/esm/index.js +7 -2
  24. package/dist/esm/index.js.map +1 -1
  25. package/dist/esm/setup.d.ts.map +1 -1
  26. package/dist/esm/setup.js +22 -0
  27. package/dist/esm/setup.js.map +1 -1
  28. package/dist/esm/storage/RemoteSQLStorage.d.ts.map +1 -1
  29. package/dist/esm/storage/RemoteSQLStorage.js +11 -4
  30. package/dist/esm/storage/RemoteSQLStorage.js.map +1 -1
  31. package/package.json +1 -1
  32. package/src/api/index.ts +517 -52
  33. package/src/calls.ts +447 -0
  34. package/src/chains.ts +203 -1
  35. package/src/config.ts +70 -0
  36. package/src/env.ts +87 -9
  37. package/src/index.ts +25 -2
  38. package/src/setup.ts +24 -0
  39. package/src/storage/RemoteSQLStorage.ts +11 -4
  40. package/dist/esm/api/captcha.d.ts +0 -38
  41. package/dist/esm/api/captcha.d.ts.map +0 -1
  42. package/dist/esm/api/captcha.js +0 -44
  43. package/dist/esm/api/captcha.js.map +0 -1
  44. package/dist/esm/api/claim.d.ts +0 -2
  45. package/dist/esm/api/claim.d.ts.map +0 -1
  46. package/dist/esm/api/claim.js +0 -2
  47. package/dist/esm/api/claim.js.map +0 -1
  48. package/dist/esm/api/dummy.d.ts +0 -28
  49. package/dist/esm/api/dummy.d.ts.map +0 -1
  50. package/dist/esm/api/dummy.js +0 -17
  51. package/dist/esm/api/dummy.js.map +0 -1
package/src/api/index.ts CHANGED
@@ -4,20 +4,32 @@ import {setup} from '../setup.js';
4
4
  import {
5
5
  CHAIN_LOCK_TIMEOUT_SECONDS,
6
6
  CLAIM_RETENTION_SECONDS,
7
- DEFAULT_CLAIM_COOLDOWN_SECONDS,
8
7
  Env,
9
8
  USED_TOKEN_RETENTION_SECONDS,
10
- getNumberEnv,
9
+ getBigIntEnv,
10
+ getCooldowns,
11
11
  } from '../env.js';
12
12
  import {isAddress, type Hex, type Address} from 'viem';
13
13
  import {privateKeyToAccount} from 'viem/accounts';
14
14
  import {
15
15
  estimateTransferCost,
16
- getChainConfig,
16
+ feePerGas,
17
+ getChainStateKey,
18
+ getFeeParams,
17
19
  getPublicClient,
18
20
  getWalletClient,
21
+ parseChainId,
22
+ resolveChain,
19
23
  } from '../chains.js';
20
24
  import {hashToken, verifyProsopoCaptcha} from '../captcha.js';
25
+ import {
26
+ getArbitraryCallsMode,
27
+ getCallAllowlist,
28
+ getCallLimits,
29
+ isCallAllowed,
30
+ parseCallRequest,
31
+ planGas,
32
+ } from '../calls.js';
21
33
 
22
34
  type ClaimRequest = {
23
35
  token: string;
@@ -25,6 +37,63 @@ type ClaimRequest = {
25
37
  address: string;
26
38
  };
27
39
 
40
+ type ExecuteRequest = {
41
+ token: string;
42
+ chainId: string;
43
+ to: string;
44
+ data?: string;
45
+ value?: string;
46
+ };
47
+
48
+ // A refusal, kept as data so shared checks can be reused across endpoints
49
+ // without fighting hono's response typing.
50
+ type Refusal = {error: string; status: 401 | 500 | 503};
51
+
52
+ /**
53
+ * Burns the captcha token so it cannot be replayed, then verifies it with the
54
+ * provider. Shared by /claim and /execute. Returns null when the caller may
55
+ * proceed. A disabled captcha skips both.
56
+ */
57
+ async function checkCaptcha(params: {
58
+ env: Env;
59
+ storage: {burnToken: (hash: string, now: number) => Promise<boolean>};
60
+ token: string;
61
+ ip: string;
62
+ now: number;
63
+ }): Promise<Refusal | null> {
64
+ const {env, storage, token, ip, now} = params;
65
+ if (env.DISABLE_CAPTCHA === 'true') {
66
+ return null;
67
+ }
68
+
69
+ const tokenHash = await hashToken(token);
70
+ const fresh = await storage.burnToken(tokenHash, now);
71
+ if (!fresh) {
72
+ return {error: 'Captcha token already used', status: 401};
73
+ }
74
+
75
+ const verification = await verifyProsopoCaptcha(
76
+ token,
77
+ env.PROSOPO_SITE_PRIVATE_KEY!,
78
+ {
79
+ failOpen: env.CAPTCHA_FAIL_OPEN === 'true',
80
+ ip: ip || undefined,
81
+ },
82
+ );
83
+ if (!verification.ok) {
84
+ if (verification.reason === 'unavailable') {
85
+ console.error(`captcha unavailable: ${verification.details}`);
86
+ return {
87
+ error:
88
+ 'Captcha verification is temporarily unavailable, please try again later',
89
+ status: 503,
90
+ };
91
+ }
92
+ return {error: 'Captcha verification failed', status: 401};
93
+ }
94
+ return null;
95
+ }
96
+
28
97
  const TX_HASH_REGEX = /^0x[0-9a-fA-F]{64}$/;
29
98
 
30
99
  /**
@@ -99,18 +168,44 @@ export function getAPI<CustomEnv extends Env>(
99
168
  const config = c.get('config');
100
169
  const env = config.env;
101
170
  const captchaDisabled = env.DISABLE_CAPTCHA === 'true';
102
- return c.json({captchaDisabled});
171
+ const modeLookup = getArbitraryCallsMode(env);
172
+ if (modeLookup.status === 'invalid') {
173
+ // same answer as /execute gives, rather than quietly reporting 'off'
174
+ // for a mode the operator clearly meant to set
175
+ console.error(
176
+ `invalid ENABLE_ARBITRARY_CALLS: "${env.ENABLE_ARBITRARY_CALLS}"`,
177
+ );
178
+ return c.json({error: 'Faucet misconfigured'}, 500);
179
+ }
180
+ const mode = modeLookup.mode;
181
+ // only advertised when enabled, so a faucet that never turns this on
182
+ // answers exactly what it always did
183
+ if (mode === 'off') {
184
+ return c.json({captchaDisabled});
185
+ }
186
+ // the address a call is signed by is what the user is really lending,
187
+ // so the popup can show it. It is public: every dispensed transaction
188
+ // carries it as the sender.
189
+ let faucetAddress: string | undefined;
190
+ try {
191
+ faucetAddress = privateKeyToAccount(
192
+ env.FAUCET_PRIVATE_KEY as Hex,
193
+ ).address;
194
+ } catch (err) {
195
+ // a missing or malformed key is reported by the claim path instead
196
+ }
197
+ return c.json({captchaDisabled, arbitraryCalls: mode, faucetAddress});
103
198
  })
104
199
  .get('/chain/:chainId', async (c) => {
105
200
  const config = c.get('config');
106
201
  const env = config.env;
107
202
 
108
- const chainIdNum = parseInt(c.req.param('chainId'), 10);
109
- if (isNaN(chainIdNum) || chainIdNum <= 0) {
203
+ const chainIdNum = parseChainId(c.req.param('chainId'));
204
+ if (chainIdNum === null) {
110
205
  return c.json({error: 'Invalid chainId'}, 400);
111
206
  }
112
207
 
113
- const lookup = getChainConfig(env, chainIdNum);
208
+ const lookup = await resolveChain(env, chainIdNum);
114
209
  if (lookup.status === 'not-configured') {
115
210
  return c.json(
116
211
  {error: `Faucet not configured for chain ${chainIdNum}`},
@@ -123,20 +218,24 @@ export function getAPI<CustomEnv extends Env>(
123
218
  );
124
219
  return c.json({error: `Faucet misconfigured`}, 500);
125
220
  }
221
+ if (lookup.status === 'unreachable') {
222
+ console.error(`could not reach the followed node: ${lookup.details}`);
223
+ return c.json({error: 'Could not reach the chain rpc'}, 503);
224
+ }
126
225
 
127
226
  // Note: the rpc endpoint is deliberately NOT returned, it is a server
128
227
  // side secret. Clients follow their transaction through /tx instead.
129
228
  return c.json({
130
229
  chainId: chainIdNum,
131
- amount: lookup.config.amount.toString(),
230
+ amount: lookup.chain.config.amount.toString(),
132
231
  });
133
232
  })
134
233
  .get('/tx/:chainId/:txHash', async (c) => {
135
234
  const config = c.get('config');
136
235
  const env = config.env;
137
236
 
138
- const chainIdNum = parseInt(c.req.param('chainId'), 10);
139
- if (isNaN(chainIdNum) || chainIdNum <= 0) {
237
+ const chainIdNum = parseChainId(c.req.param('chainId'));
238
+ if (chainIdNum === null) {
140
239
  return c.json({error: 'Invalid chainId'}, 400);
141
240
  }
142
241
 
@@ -145,7 +244,11 @@ export function getAPI<CustomEnv extends Env>(
145
244
  return c.json({error: 'Invalid transaction hash'}, 400);
146
245
  }
147
246
 
148
- const lookup = getChainConfig(env, chainIdNum);
247
+ const lookup = await resolveChain(env, chainIdNum);
248
+ if (lookup.status === 'unreachable') {
249
+ console.error(`could not reach the followed node: ${lookup.details}`);
250
+ return c.json({error: 'Could not reach the chain rpc'}, 503);
251
+ }
149
252
  if (lookup.status !== 'ok') {
150
253
  return c.json(
151
254
  {error: `Faucet not configured for chain ${chainIdNum}`},
@@ -153,7 +256,7 @@ export function getAPI<CustomEnv extends Env>(
153
256
  );
154
257
  }
155
258
 
156
- const publicClient = getPublicClient(lookup.config);
259
+ const publicClient = getPublicClient(lookup.chain.config);
157
260
  try {
158
261
  const receipt = await publicClient.getTransactionReceipt({
159
262
  hash: txHash as Hex,
@@ -203,12 +306,12 @@ export function getAPI<CustomEnv extends Env>(
203
306
  return c.json({error: 'Invalid Ethereum address'}, 400);
204
307
  }
205
308
 
206
- const chainIdNum = parseInt(chainId, 10);
207
- if (isNaN(chainIdNum) || chainIdNum <= 0) {
309
+ const chainIdNum = parseChainId(chainId);
310
+ if (chainIdNum === null) {
208
311
  return c.json({error: 'Invalid chainId'}, 400);
209
312
  }
210
313
 
211
- const lookup = getChainConfig(env, chainIdNum);
314
+ const lookup = await resolveChain(env, chainIdNum);
212
315
  if (lookup.status === 'not-configured') {
213
316
  return c.json(
214
317
  {error: `Faucet not configured for chain ${chainIdNum}`},
@@ -221,40 +324,58 @@ export function getAPI<CustomEnv extends Env>(
221
324
  );
222
325
  return c.json({error: 'Faucet misconfigured'}, 500);
223
326
  }
224
- const chainConfig = lookup.config;
327
+ if (lookup.status === 'unreachable') {
328
+ console.error(`could not reach the followed node: ${lookup.details}`);
329
+ return c.json({error: 'Could not reach the chain rpc'}, 503);
330
+ }
331
+ const chain = lookup.chain;
332
+ const chainConfig = chain.config;
333
+
334
+ // ---------------------------------------------------------------
335
+ // 0. the limits this faucet runs under. Parsed up front, before any
336
+ // network work: a typo in one of them is a refusal, never a
337
+ // quietly weaker limit.
338
+ // ---------------------------------------------------------------
339
+ const maxRecipientBalanceEnv = getBigIntEnv(env.MAX_RECIPIENT_BALANCE);
340
+ if (maxRecipientBalanceEnv.status === 'invalid') {
341
+ console.error(
342
+ `MAX_RECIPIENT_BALANCE is not a wei amount: "${env.MAX_RECIPIENT_BALANCE}"`,
343
+ );
344
+ return c.json({error: 'Faucet misconfigured'}, 500);
345
+ }
346
+ const maxRecipientBalance =
347
+ maxRecipientBalanceEnv.status === 'ok'
348
+ ? maxRecipientBalanceEnv.value
349
+ : chainConfig.amount * 10n;
350
+
351
+ const cooldowns = getCooldowns(env);
352
+ if (cooldowns.status === 'invalid') {
353
+ console.error(cooldowns.details);
354
+ return c.json({error: 'Faucet misconfigured'}, 500);
355
+ }
356
+ const {addressCooldown, ipCooldown} = cooldowns;
225
357
 
226
358
  const now = Math.floor(Date.now() / 1000);
227
359
  const ip = getClientIp(c);
228
360
  const normalizedAddress = address.toLowerCase();
229
- const chainIdKey = String(chainIdNum);
361
+
362
+ // the key the rate limits and the nonce lock live under: the bare id
363
+ // for a CHAIN_<id> entry, the chain identity for a followed one. Read
364
+ // before the captcha so an unreachable node does not burn the token.
365
+ let chainIdKey: string;
366
+ try {
367
+ chainIdKey = await getChainStateKey(chain);
368
+ } catch (err) {
369
+ console.error('could not read the chain identity', err);
370
+ return c.json({error: 'Could not reach the chain rpc'}, 503);
371
+ }
230
372
 
231
373
  // ---------------------------------------------------------------
232
374
  // 1. captcha: single use token, then provider verification
233
375
  // ---------------------------------------------------------------
234
- if (!captchaDisabled) {
235
- const tokenHash = await hashToken(token);
236
- const fresh = await storage.burnToken(tokenHash, now);
237
- if (!fresh) {
238
- return c.json({error: 'Captcha token already used'}, 401);
239
- }
240
-
241
- const verification = await verifyProsopoCaptcha(token, secret!, {
242
- failOpen: env.CAPTCHA_FAIL_OPEN === 'true',
243
- ip: ip || undefined,
244
- });
245
- if (!verification.ok) {
246
- if (verification.reason === 'unavailable') {
247
- console.error(`captcha unavailable: ${verification.details}`);
248
- return c.json(
249
- {
250
- error:
251
- 'Captcha verification is temporarily unavailable, please try again later',
252
- },
253
- 503,
254
- );
255
- }
256
- return c.json({error: 'Captcha verification failed'}, 401);
257
- }
376
+ const refusal = await checkCaptcha({env, storage, token, ip, now});
377
+ if (refusal) {
378
+ return c.json({error: refusal.error}, refusal.status);
258
379
  }
259
380
 
260
381
  const publicClient = getPublicClient(chainConfig);
@@ -262,11 +383,6 @@ export function getAPI<CustomEnv extends Env>(
262
383
  // ---------------------------------------------------------------
263
384
  // 2. do not top up an address that already holds enough
264
385
  // ---------------------------------------------------------------
265
- const maxRecipientBalance =
266
- env.MAX_RECIPIENT_BALANCE === undefined ||
267
- env.MAX_RECIPIENT_BALANCE === ''
268
- ? chainConfig.amount * 10n
269
- : BigInt(env.MAX_RECIPIENT_BALANCE);
270
386
  if (maxRecipientBalance > 0n) {
271
387
  try {
272
388
  const recipientBalance = await publicClient.getBalance({
@@ -290,12 +406,6 @@ export function getAPI<CustomEnv extends Env>(
290
406
  // ---------------------------------------------------------------
291
407
  // 3. rate limit: atomically reserve a slot for this address / ip
292
408
  // ---------------------------------------------------------------
293
- const addressCooldown = getNumberEnv(
294
- env.CLAIM_COOLDOWN_SECONDS,
295
- DEFAULT_CLAIM_COOLDOWN_SECONDS,
296
- );
297
- const ipCooldown = getNumberEnv(env.IP_COOLDOWN_SECONDS, addressCooldown);
298
-
299
409
  const claimId = await storage.reserveClaim({
300
410
  chainId: chainIdKey,
301
411
  address: normalizedAddress,
@@ -410,6 +520,361 @@ export function getAPI<CustomEnv extends Env>(
410
520
  ),
411
521
  );
412
522
 
523
+ return c.json({success: true, txHash});
524
+ } catch (err) {
525
+ console.error('Transaction error:', err);
526
+ await storage.releaseChainLock(chainIdKey, nonceUsed).catch((e) => {
527
+ console.error('could not release chain lock', e);
528
+ });
529
+ const errorMessage =
530
+ err instanceof Error ? err.message : 'Transaction failed';
531
+ return abort(errorMessage, 500);
532
+ }
533
+ })
534
+ /**
535
+ * Executes a caller chosen call, paid for by the faucet.
536
+ *
537
+ * Off unless ENABLE_ARBITRARY_CALLS says otherwise, because this lends the
538
+ * faucet key's authority to whoever passes the captcha. See
539
+ * docs/specs/arbitrary-calls.md for the threat model.
540
+ */
541
+ .post('/execute', async (c) => {
542
+ const config = c.get('config');
543
+ const {env, storage} = config;
544
+
545
+ const modeLookup = getArbitraryCallsMode(env);
546
+ if (modeLookup.status === 'invalid') {
547
+ console.error(
548
+ `invalid ENABLE_ARBITRARY_CALLS: "${env.ENABLE_ARBITRARY_CALLS}"`,
549
+ );
550
+ return c.json({error: 'Faucet misconfigured'}, 500);
551
+ }
552
+ const mode = modeLookup.mode;
553
+ if (mode === 'off') {
554
+ return c.json(
555
+ {error: 'Arbitrary calls are not enabled on this faucet'},
556
+ 404,
557
+ );
558
+ }
559
+
560
+ const captchaDisabled = env.DISABLE_CAPTCHA === 'true';
561
+ const secret = env.PROSOPO_SITE_PRIVATE_KEY;
562
+ if (!captchaDisabled && !secret) {
563
+ return c.json({error: 'PROSOPO_SITE_PRIVATE_KEY not configured'}, 500);
564
+ }
565
+
566
+ const faucetPrivateKey = env.FAUCET_PRIVATE_KEY;
567
+ if (!faucetPrivateKey) {
568
+ return c.json({error: 'FAUCET_PRIVATE_KEY not configured'}, 500);
569
+ }
570
+
571
+ let body: ExecuteRequest;
572
+ try {
573
+ body = await c.req.json<ExecuteRequest>();
574
+ } catch (err) {
575
+ return c.json({error: 'Invalid JSON body'}, 400);
576
+ }
577
+ const {token, chainId} = body;
578
+
579
+ if (!token && !captchaDisabled) {
580
+ return c.json({error: 'Missing token'}, 400);
581
+ }
582
+ if (!chainId) {
583
+ return c.json({error: 'Missing chainId'}, 400);
584
+ }
585
+ const chainIdNum = parseChainId(chainId);
586
+ if (chainIdNum === null) {
587
+ return c.json({error: 'Invalid chainId'}, 400);
588
+ }
589
+
590
+ const parsed = parseCallRequest(body);
591
+ if (parsed.status === 'invalid') {
592
+ return c.json({error: parsed.error}, 400);
593
+ }
594
+ const {to, data, value} = parsed.call;
595
+
596
+ const lookup = await resolveChain(env, chainIdNum);
597
+ if (lookup.status === 'not-configured') {
598
+ return c.json(
599
+ {error: `Faucet not configured for chain ${chainIdNum}`},
600
+ 400,
601
+ );
602
+ }
603
+ if (lookup.status === 'invalid') {
604
+ console.error(
605
+ `invalid config for chain ${chainIdNum}: ${lookup.details}`,
606
+ );
607
+ return c.json({error: 'Faucet misconfigured'}, 500);
608
+ }
609
+ if (lookup.status === 'unreachable') {
610
+ console.error(`could not reach the followed node: ${lookup.details}`);
611
+ return c.json({error: 'Could not reach the chain rpc'}, 503);
612
+ }
613
+ const chain = lookup.chain;
614
+ const chainConfig = chain.config;
615
+
616
+ // parsed before any network work, so a typo in a limit is a refusal
617
+ const cooldowns = getCooldowns(env);
618
+ if (cooldowns.status === 'invalid') {
619
+ console.error(cooldowns.details);
620
+ return c.json({error: 'Faucet misconfigured'}, 500);
621
+ }
622
+ const {addressCooldown, ipCooldown} = cooldowns;
623
+
624
+ // ---------------------------------------------------------------
625
+ // 1. is this call permitted at all
626
+ // ---------------------------------------------------------------
627
+ if (mode === 'allowlist') {
628
+ const allowlistLookup = getCallAllowlist(env, chainIdNum);
629
+ if (allowlistLookup.status !== 'ok') {
630
+ console.error(
631
+ `CALL_ALLOWLIST_${chainIdNum} is ${
632
+ allowlistLookup.status === 'invalid'
633
+ ? `invalid: ${allowlistLookup.details}`
634
+ : 'not set, every call on this chain is refused'
635
+ }`,
636
+ );
637
+ return c.json({error: 'Faucet misconfigured'}, 500);
638
+ }
639
+ if (!isCallAllowed(allowlistLookup.allowlist, to, data)) {
640
+ return c.json(
641
+ {
642
+ error:
643
+ 'This faucet does not allow that contract and function combination',
644
+ },
645
+ 400,
646
+ );
647
+ }
648
+ }
649
+
650
+ const now = Math.floor(Date.now() / 1000);
651
+ const ip = getClientIp(c);
652
+
653
+ // `to` is a shared contract, so it cannot be a rate limiting key: the ip
654
+ // is the only one this endpoint has. Without it there is no limit at
655
+ // all, so an unknown ip is refused rather than served.
656
+ if (!captchaDisabled && ip === '') {
657
+ console.error(
658
+ 'refusing /execute: no client ip, so no rate limit would apply. Put the server behind a proxy that sets X-Forwarded-For.',
659
+ );
660
+ return c.json(
661
+ {
662
+ error:
663
+ 'This faucet cannot determine your ip, and refuses to execute calls it cannot rate limit',
664
+ },
665
+ 503,
666
+ );
667
+ }
668
+
669
+ // the key the rate limits and the nonce lock live under: the bare id
670
+ // for a CHAIN_<id> entry, the chain identity for a followed one. Read
671
+ // before the captcha so an unreachable node does not burn the token.
672
+ let chainIdKey: string;
673
+ try {
674
+ chainIdKey = await getChainStateKey(chain);
675
+ } catch (err) {
676
+ console.error('could not read the chain identity', err);
677
+ return c.json({error: 'Could not reach the chain rpc'}, 503);
678
+ }
679
+
680
+ // ---------------------------------------------------------------
681
+ // 2. captcha: single use token, then provider verification
682
+ // ---------------------------------------------------------------
683
+ const refusal = await checkCaptcha({env, storage, token, ip, now});
684
+ if (refusal) {
685
+ return c.json({error: refusal.error}, refusal.status);
686
+ }
687
+
688
+ // ---------------------------------------------------------------
689
+ // 3. rate limit, on the ip alone. A disabled captcha means localhost,
690
+ // where every account shares one ip, so the bucket is skipped.
691
+ // ---------------------------------------------------------------
692
+ let claimId: number | null = null;
693
+ if (!captchaDisabled) {
694
+ // an empty address disables the address bucket, see RemoteSQLStorage
695
+ claimId = await storage.reserveClaim({
696
+ chainId: chainIdKey,
697
+ address: '',
698
+ ip,
699
+ amount: value.toString(),
700
+ now,
701
+ addressCutoff: now,
702
+ ipCutoff: now - ipCooldown,
703
+ });
704
+ if (claimId === null) {
705
+ const hit = await storage.getRateLimitHit({
706
+ chainId: chainIdKey,
707
+ address: '',
708
+ ip,
709
+ now,
710
+ addressCutoff: now,
711
+ ipCutoff: now - ipCooldown,
712
+ addressCooldown,
713
+ ipCooldown,
714
+ });
715
+ return c.json(
716
+ {
717
+ error: `You already used this faucet recently, try again in ${formatDuration(
718
+ hit.retryAfter,
719
+ )}`,
720
+ retryAfter: hit.retryAfter,
721
+ },
722
+ 429,
723
+ {'Retry-After': String(hit.retryAfter)},
724
+ );
725
+ }
726
+ }
727
+
728
+ // From here on, any failure must give the reservation back.
729
+ const reservedId = claimId;
730
+ const abort = async (
731
+ message: string,
732
+ status: 400 | 500 | 503,
733
+ ): Promise<Response> => {
734
+ if (reservedId !== null) {
735
+ await storage.cancelClaim(reservedId).catch((err) => {
736
+ console.error('could not cancel claim reservation', err);
737
+ });
738
+ }
739
+ return c.json({error: message}, status);
740
+ };
741
+
742
+ const publicClient = getPublicClient(chainConfig);
743
+ const account = privateKeyToAccount(faucetPrivateKey as Hex);
744
+
745
+ // ---------------------------------------------------------------
746
+ // 4. budget: turn a wei ceiling into a gas limit
747
+ // ---------------------------------------------------------------
748
+ // ONE fee reading feeds the budget, the division and the transaction:
749
+ // re-reading would let a bare transfer fail on a fee tick.
750
+ let fees;
751
+ try {
752
+ fees = await getFeeParams(publicClient);
753
+ } catch (err) {
754
+ console.error('could not read gas price', err);
755
+ return abort('Could not reach the chain rpc', 503);
756
+ }
757
+ const fee = feePerGas(fees);
758
+
759
+ const limitsLookup = getCallLimits(env, chainConfig, fee);
760
+ if (limitsLookup.status === 'invalid') {
761
+ console.error(`invalid call limits: ${limitsLookup.details}`);
762
+ return abort('Faucet misconfigured', 500);
763
+ }
764
+ const limits = limitsLookup.limits;
765
+
766
+ if (value > limits.maxValue) {
767
+ return abort(
768
+ `This faucet sends at most ${limits.maxValue} wei with a call, asked for ${value}`,
769
+ 400,
770
+ );
771
+ }
772
+
773
+ // A revert is free here. Refusing now also avoids broadcasting a call
774
+ // that would run out of gas, which would burn the whole limit.
775
+ let estimated: bigint;
776
+ try {
777
+ estimated = await publicClient.estimateGas({
778
+ account,
779
+ to,
780
+ data,
781
+ value,
782
+ });
783
+ } catch (err) {
784
+ const details =
785
+ err instanceof Error && 'shortMessage' in err
786
+ ? String((err as {shortMessage: unknown}).shortMessage)
787
+ : err instanceof Error
788
+ ? err.message
789
+ : 'unknown error';
790
+ return abort(`This call cannot be executed: ${details}`, 400);
791
+ }
792
+
793
+ const plan = planGas({limits, value, estimated, feePerGas: fee});
794
+ if (plan.status === 'does-not-fit') {
795
+ return abort(plan.details, 400);
796
+ }
797
+
798
+ // ---------------------------------------------------------------
799
+ // 5. can the faucet still pay the worst case?
800
+ // ---------------------------------------------------------------
801
+ try {
802
+ const faucetBalance = await publicClient.getBalance({
803
+ address: account.address,
804
+ });
805
+ if (faucetBalance < plan.ceiling) {
806
+ console.error(
807
+ `faucet ${account.address} is out of funds on chain ${chainIdNum}: balance ${faucetBalance}, needs ${plan.ceiling}`,
808
+ );
809
+ return abort(
810
+ 'The faucet is temporarily out of funds, please try again later',
811
+ 503,
812
+ );
813
+ }
814
+ } catch (err) {
815
+ console.error('could not check faucet balance', err);
816
+ return abort('Could not reach the chain rpc', 503);
817
+ }
818
+
819
+ // ---------------------------------------------------------------
820
+ // 6. serialise sending so concurrent calls cannot reuse a nonce
821
+ // ---------------------------------------------------------------
822
+ const lock = await acquireChainLockWaiting(storage, chainIdKey);
823
+ if (!lock.acquired) {
824
+ return abort(
825
+ 'The faucet is busy dispensing other claims, please try again in a few seconds',
826
+ 503,
827
+ );
828
+ }
829
+
830
+ let nonceUsed: number | null = null;
831
+ try {
832
+ const pendingNonce = await publicClient.getTransactionCount({
833
+ address: account.address,
834
+ blockTag: 'pending',
835
+ });
836
+ const nonce =
837
+ lock.lastNonce === null
838
+ ? pendingNonce
839
+ : Math.max(lock.lastNonce + 1, pendingNonce);
840
+
841
+ const walletClient = getWalletClient(chainConfig, account);
842
+ // gas and fee are both explicit: the ceiling is only a real bound
843
+ // because the server picked both numbers.
844
+ const txHash =
845
+ fees.type === 'eip1559'
846
+ ? await walletClient.sendTransaction({
847
+ to,
848
+ data,
849
+ value,
850
+ nonce,
851
+ gas: plan.gasLimit,
852
+ maxFeePerGas: fees.maxFeePerGas,
853
+ maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
854
+ })
855
+ : await walletClient.sendTransaction({
856
+ to,
857
+ data,
858
+ value,
859
+ nonce,
860
+ gas: plan.gasLimit,
861
+ gasPrice: fees.gasPrice,
862
+ });
863
+ nonceUsed = nonce;
864
+
865
+ await storage.releaseChainLock(chainIdKey, nonceUsed);
866
+ if (reservedId !== null) {
867
+ await storage.recordClaimTx(reservedId, txHash);
868
+ }
869
+
870
+ background(
871
+ c,
872
+ storage.cleanup(
873
+ now - USED_TOKEN_RETENTION_SECONDS,
874
+ now - CLAIM_RETENTION_SECONDS,
875
+ ),
876
+ );
877
+
413
878
  return c.json({success: true, txHash});
414
879
  } catch (err) {
415
880
  console.error('Transaction error:', err);