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
@@ -7,6 +7,13 @@ export declare function getAPI<CustomEnv extends Env>(options: ServerOptions<Cus
7
7
  } ? T extends import("hono").Env ? import("hono").Env extends T ? {} : T : T : never : never> & {}, {
8
8
  "/config": {
9
9
  $get: {
10
+ input: {};
11
+ output: {
12
+ error: string;
13
+ };
14
+ outputFormat: "json";
15
+ status: 500;
16
+ } | {
10
17
  input: {};
11
18
  output: {
12
19
  captchaDisabled: boolean;
@@ -50,6 +57,17 @@ export declare function getAPI<CustomEnv extends Env>(options: ServerOptions<Cus
50
57
  };
51
58
  outputFormat: "json";
52
59
  status: 500;
60
+ } | {
61
+ input: {
62
+ param: {
63
+ chainId: string;
64
+ };
65
+ };
66
+ output: {
67
+ error: string;
68
+ };
69
+ outputFormat: "json";
70
+ status: 503;
53
71
  } | {
54
72
  input: {
55
73
  param: {
@@ -79,6 +97,19 @@ export declare function getAPI<CustomEnv extends Env>(options: ServerOptions<Cus
79
97
  };
80
98
  outputFormat: "json";
81
99
  status: 400;
100
+ } | {
101
+ input: {
102
+ param: {
103
+ chainId: string;
104
+ } & {
105
+ txHash: string;
106
+ };
107
+ };
108
+ output: {
109
+ error: string;
110
+ };
111
+ outputFormat: "json";
112
+ status: 503;
82
113
  } | {
83
114
  input: {
84
115
  param: {
@@ -116,5 +147,14 @@ export declare function getAPI<CustomEnv extends Env>(options: ServerOptions<Cus
116
147
  status: import("hono/utils/http-status").StatusCode;
117
148
  };
118
149
  };
119
- }, "/", "/claim">;
150
+ } & {
151
+ "/execute": {
152
+ $post: {
153
+ input: {};
154
+ output: {};
155
+ outputFormat: string;
156
+ status: import("hono/utils/http-status").StatusCode;
157
+ };
158
+ };
159
+ }, "/", "/execute">;
120
160
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/api/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,aAAa,EAAC,MAAM,aAAa,CAAC;AAE1C,OAAO,EAIN,GAAG,EAGH,MAAM,WAAW,CAAC;AAkFnB,wBAAgB,MAAM,CAAC,SAAS,SAAS,GAAG,EAC3C,OAAO,EAAE,aAAa,CAAC,SAAS,CAAC;cAED,SAAS;;cAAT,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA0UzC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/api/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,aAAa,EAAC,MAAM,aAAa,CAAC;AAE1C,OAAO,EAGN,GAAG,EAIH,MAAM,WAAW,CAAC;AAuJnB,wBAAgB,MAAM,CAAC,SAAS,SAAS,GAAG,EAC3C,OAAO,EAAE,aAAa,CAAC,SAAS,CAAC;cAED,SAAS;;cAAT,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oBAstBzC"}
@@ -1,10 +1,42 @@
1
1
  import { Hono } from 'hono';
2
2
  import { setup } from '../setup.js';
3
- import { CHAIN_LOCK_TIMEOUT_SECONDS, CLAIM_RETENTION_SECONDS, DEFAULT_CLAIM_COOLDOWN_SECONDS, USED_TOKEN_RETENTION_SECONDS, getNumberEnv, } from '../env.js';
3
+ import { CHAIN_LOCK_TIMEOUT_SECONDS, CLAIM_RETENTION_SECONDS, USED_TOKEN_RETENTION_SECONDS, getBigIntEnv, getCooldowns, } from '../env.js';
4
4
  import { isAddress } from 'viem';
5
5
  import { privateKeyToAccount } from 'viem/accounts';
6
- import { estimateTransferCost, getChainConfig, getPublicClient, getWalletClient, } from '../chains.js';
6
+ import { estimateTransferCost, feePerGas, getChainStateKey, getFeeParams, getPublicClient, getWalletClient, parseChainId, resolveChain, } from '../chains.js';
7
7
  import { hashToken, verifyProsopoCaptcha } from '../captcha.js';
8
+ import { getArbitraryCallsMode, getCallAllowlist, getCallLimits, isCallAllowed, parseCallRequest, planGas, } from '../calls.js';
9
+ /**
10
+ * Burns the captcha token so it cannot be replayed, then verifies it with the
11
+ * provider. Shared by /claim and /execute. Returns null when the caller may
12
+ * proceed. A disabled captcha skips both.
13
+ */
14
+ async function checkCaptcha(params) {
15
+ const { env, storage, token, ip, now } = params;
16
+ if (env.DISABLE_CAPTCHA === 'true') {
17
+ return null;
18
+ }
19
+ const tokenHash = await hashToken(token);
20
+ const fresh = await storage.burnToken(tokenHash, now);
21
+ if (!fresh) {
22
+ return { error: 'Captcha token already used', status: 401 };
23
+ }
24
+ const verification = await verifyProsopoCaptcha(token, env.PROSOPO_SITE_PRIVATE_KEY, {
25
+ failOpen: env.CAPTCHA_FAIL_OPEN === 'true',
26
+ ip: ip || undefined,
27
+ });
28
+ if (!verification.ok) {
29
+ if (verification.reason === 'unavailable') {
30
+ console.error(`captcha unavailable: ${verification.details}`);
31
+ return {
32
+ error: 'Captcha verification is temporarily unavailable, please try again later',
33
+ status: 503,
34
+ };
35
+ }
36
+ return { error: 'Captcha verification failed', status: 401 };
37
+ }
38
+ return null;
39
+ }
8
40
  const TX_HASH_REGEX = /^0x[0-9a-fA-F]{64}$/;
9
41
  /**
10
42
  * Best effort ip of the caller, used as a rate limiting bucket.
@@ -60,16 +92,39 @@ export function getAPI(options) {
60
92
  const config = c.get('config');
61
93
  const env = config.env;
62
94
  const captchaDisabled = env.DISABLE_CAPTCHA === 'true';
63
- return c.json({ captchaDisabled });
95
+ const modeLookup = getArbitraryCallsMode(env);
96
+ if (modeLookup.status === 'invalid') {
97
+ // same answer as /execute gives, rather than quietly reporting 'off'
98
+ // for a mode the operator clearly meant to set
99
+ console.error(`invalid ENABLE_ARBITRARY_CALLS: "${env.ENABLE_ARBITRARY_CALLS}"`);
100
+ return c.json({ error: 'Faucet misconfigured' }, 500);
101
+ }
102
+ const mode = modeLookup.mode;
103
+ // only advertised when enabled, so a faucet that never turns this on
104
+ // answers exactly what it always did
105
+ if (mode === 'off') {
106
+ return c.json({ captchaDisabled });
107
+ }
108
+ // the address a call is signed by is what the user is really lending,
109
+ // so the popup can show it. It is public: every dispensed transaction
110
+ // carries it as the sender.
111
+ let faucetAddress;
112
+ try {
113
+ faucetAddress = privateKeyToAccount(env.FAUCET_PRIVATE_KEY).address;
114
+ }
115
+ catch (err) {
116
+ // a missing or malformed key is reported by the claim path instead
117
+ }
118
+ return c.json({ captchaDisabled, arbitraryCalls: mode, faucetAddress });
64
119
  })
65
120
  .get('/chain/:chainId', async (c) => {
66
121
  const config = c.get('config');
67
122
  const env = config.env;
68
- const chainIdNum = parseInt(c.req.param('chainId'), 10);
69
- if (isNaN(chainIdNum) || chainIdNum <= 0) {
123
+ const chainIdNum = parseChainId(c.req.param('chainId'));
124
+ if (chainIdNum === null) {
70
125
  return c.json({ error: 'Invalid chainId' }, 400);
71
126
  }
72
- const lookup = getChainConfig(env, chainIdNum);
127
+ const lookup = await resolveChain(env, chainIdNum);
73
128
  if (lookup.status === 'not-configured') {
74
129
  return c.json({ error: `Faucet not configured for chain ${chainIdNum}` }, 404);
75
130
  }
@@ -77,29 +132,37 @@ export function getAPI(options) {
77
132
  console.error(`invalid config for chain ${chainIdNum}: ${lookup.details}`);
78
133
  return c.json({ error: `Faucet misconfigured` }, 500);
79
134
  }
135
+ if (lookup.status === 'unreachable') {
136
+ console.error(`could not reach the followed node: ${lookup.details}`);
137
+ return c.json({ error: 'Could not reach the chain rpc' }, 503);
138
+ }
80
139
  // Note: the rpc endpoint is deliberately NOT returned, it is a server
81
140
  // side secret. Clients follow their transaction through /tx instead.
82
141
  return c.json({
83
142
  chainId: chainIdNum,
84
- amount: lookup.config.amount.toString(),
143
+ amount: lookup.chain.config.amount.toString(),
85
144
  });
86
145
  })
87
146
  .get('/tx/:chainId/:txHash', async (c) => {
88
147
  const config = c.get('config');
89
148
  const env = config.env;
90
- const chainIdNum = parseInt(c.req.param('chainId'), 10);
91
- if (isNaN(chainIdNum) || chainIdNum <= 0) {
149
+ const chainIdNum = parseChainId(c.req.param('chainId'));
150
+ if (chainIdNum === null) {
92
151
  return c.json({ error: 'Invalid chainId' }, 400);
93
152
  }
94
153
  const txHash = c.req.param('txHash');
95
154
  if (!TX_HASH_REGEX.test(txHash)) {
96
155
  return c.json({ error: 'Invalid transaction hash' }, 400);
97
156
  }
98
- const lookup = getChainConfig(env, chainIdNum);
157
+ const lookup = await resolveChain(env, chainIdNum);
158
+ if (lookup.status === 'unreachable') {
159
+ console.error(`could not reach the followed node: ${lookup.details}`);
160
+ return c.json({ error: 'Could not reach the chain rpc' }, 503);
161
+ }
99
162
  if (lookup.status !== 'ok') {
100
163
  return c.json({ error: `Faucet not configured for chain ${chainIdNum}` }, 404);
101
164
  }
102
- const publicClient = getPublicClient(lookup.config);
165
+ const publicClient = getPublicClient(lookup.chain.config);
103
166
  try {
104
167
  const receipt = await publicClient.getTransactionReceipt({
105
168
  hash: txHash,
@@ -146,11 +209,11 @@ export function getAPI(options) {
146
209
  if (!isAddress(address)) {
147
210
  return c.json({ error: 'Invalid Ethereum address' }, 400);
148
211
  }
149
- const chainIdNum = parseInt(chainId, 10);
150
- if (isNaN(chainIdNum) || chainIdNum <= 0) {
212
+ const chainIdNum = parseChainId(chainId);
213
+ if (chainIdNum === null) {
151
214
  return c.json({ error: 'Invalid chainId' }, 400);
152
215
  }
153
- const lookup = getChainConfig(env, chainIdNum);
216
+ const lookup = await resolveChain(env, chainIdNum);
154
217
  if (lookup.status === 'not-configured') {
155
218
  return c.json({ error: `Faucet not configured for chain ${chainIdNum}` }, 400);
156
219
  }
@@ -158,42 +221,56 @@ export function getAPI(options) {
158
221
  console.error(`invalid config for chain ${chainIdNum}: ${lookup.details}`);
159
222
  return c.json({ error: 'Faucet misconfigured' }, 500);
160
223
  }
161
- const chainConfig = lookup.config;
224
+ if (lookup.status === 'unreachable') {
225
+ console.error(`could not reach the followed node: ${lookup.details}`);
226
+ return c.json({ error: 'Could not reach the chain rpc' }, 503);
227
+ }
228
+ const chain = lookup.chain;
229
+ const chainConfig = chain.config;
230
+ // ---------------------------------------------------------------
231
+ // 0. the limits this faucet runs under. Parsed up front, before any
232
+ // network work: a typo in one of them is a refusal, never a
233
+ // quietly weaker limit.
234
+ // ---------------------------------------------------------------
235
+ const maxRecipientBalanceEnv = getBigIntEnv(env.MAX_RECIPIENT_BALANCE);
236
+ if (maxRecipientBalanceEnv.status === 'invalid') {
237
+ console.error(`MAX_RECIPIENT_BALANCE is not a wei amount: "${env.MAX_RECIPIENT_BALANCE}"`);
238
+ return c.json({ error: 'Faucet misconfigured' }, 500);
239
+ }
240
+ const maxRecipientBalance = maxRecipientBalanceEnv.status === 'ok'
241
+ ? maxRecipientBalanceEnv.value
242
+ : chainConfig.amount * 10n;
243
+ const cooldowns = getCooldowns(env);
244
+ if (cooldowns.status === 'invalid') {
245
+ console.error(cooldowns.details);
246
+ return c.json({ error: 'Faucet misconfigured' }, 500);
247
+ }
248
+ const { addressCooldown, ipCooldown } = cooldowns;
162
249
  const now = Math.floor(Date.now() / 1000);
163
250
  const ip = getClientIp(c);
164
251
  const normalizedAddress = address.toLowerCase();
165
- const chainIdKey = String(chainIdNum);
252
+ // the key the rate limits and the nonce lock live under: the bare id
253
+ // for a CHAIN_<id> entry, the chain identity for a followed one. Read
254
+ // before the captcha so an unreachable node does not burn the token.
255
+ let chainIdKey;
256
+ try {
257
+ chainIdKey = await getChainStateKey(chain);
258
+ }
259
+ catch (err) {
260
+ console.error('could not read the chain identity', err);
261
+ return c.json({ error: 'Could not reach the chain rpc' }, 503);
262
+ }
166
263
  // ---------------------------------------------------------------
167
264
  // 1. captcha: single use token, then provider verification
168
265
  // ---------------------------------------------------------------
169
- if (!captchaDisabled) {
170
- const tokenHash = await hashToken(token);
171
- const fresh = await storage.burnToken(tokenHash, now);
172
- if (!fresh) {
173
- return c.json({ error: 'Captcha token already used' }, 401);
174
- }
175
- const verification = await verifyProsopoCaptcha(token, secret, {
176
- failOpen: env.CAPTCHA_FAIL_OPEN === 'true',
177
- ip: ip || undefined,
178
- });
179
- if (!verification.ok) {
180
- if (verification.reason === 'unavailable') {
181
- console.error(`captcha unavailable: ${verification.details}`);
182
- return c.json({
183
- error: 'Captcha verification is temporarily unavailable, please try again later',
184
- }, 503);
185
- }
186
- return c.json({ error: 'Captcha verification failed' }, 401);
187
- }
266
+ const refusal = await checkCaptcha({ env, storage, token, ip, now });
267
+ if (refusal) {
268
+ return c.json({ error: refusal.error }, refusal.status);
188
269
  }
189
270
  const publicClient = getPublicClient(chainConfig);
190
271
  // ---------------------------------------------------------------
191
272
  // 2. do not top up an address that already holds enough
192
273
  // ---------------------------------------------------------------
193
- const maxRecipientBalance = env.MAX_RECIPIENT_BALANCE === undefined ||
194
- env.MAX_RECIPIENT_BALANCE === ''
195
- ? chainConfig.amount * 10n
196
- : BigInt(env.MAX_RECIPIENT_BALANCE);
197
274
  if (maxRecipientBalance > 0n) {
198
275
  try {
199
276
  const recipientBalance = await publicClient.getBalance({
@@ -213,8 +290,6 @@ export function getAPI(options) {
213
290
  // ---------------------------------------------------------------
214
291
  // 3. rate limit: atomically reserve a slot for this address / ip
215
292
  // ---------------------------------------------------------------
216
- const addressCooldown = getNumberEnv(env.CLAIM_COOLDOWN_SECONDS, DEFAULT_CLAIM_COOLDOWN_SECONDS);
217
- const ipCooldown = getNumberEnv(env.IP_COOLDOWN_SECONDS, addressCooldown);
218
293
  const claimId = await storage.reserveClaim({
219
294
  chainId: chainIdKey,
220
295
  address: normalizedAddress,
@@ -304,6 +379,285 @@ export function getAPI(options) {
304
379
  const errorMessage = err instanceof Error ? err.message : 'Transaction failed';
305
380
  return abort(errorMessage, 500);
306
381
  }
382
+ })
383
+ /**
384
+ * Executes a caller chosen call, paid for by the faucet.
385
+ *
386
+ * Off unless ENABLE_ARBITRARY_CALLS says otherwise, because this lends the
387
+ * faucet key's authority to whoever passes the captcha. See
388
+ * docs/specs/arbitrary-calls.md for the threat model.
389
+ */
390
+ .post('/execute', async (c) => {
391
+ const config = c.get('config');
392
+ const { env, storage } = config;
393
+ const modeLookup = getArbitraryCallsMode(env);
394
+ if (modeLookup.status === 'invalid') {
395
+ console.error(`invalid ENABLE_ARBITRARY_CALLS: "${env.ENABLE_ARBITRARY_CALLS}"`);
396
+ return c.json({ error: 'Faucet misconfigured' }, 500);
397
+ }
398
+ const mode = modeLookup.mode;
399
+ if (mode === 'off') {
400
+ return c.json({ error: 'Arbitrary calls are not enabled on this faucet' }, 404);
401
+ }
402
+ const captchaDisabled = env.DISABLE_CAPTCHA === 'true';
403
+ const secret = env.PROSOPO_SITE_PRIVATE_KEY;
404
+ if (!captchaDisabled && !secret) {
405
+ return c.json({ error: 'PROSOPO_SITE_PRIVATE_KEY not configured' }, 500);
406
+ }
407
+ const faucetPrivateKey = env.FAUCET_PRIVATE_KEY;
408
+ if (!faucetPrivateKey) {
409
+ return c.json({ error: 'FAUCET_PRIVATE_KEY not configured' }, 500);
410
+ }
411
+ let body;
412
+ try {
413
+ body = await c.req.json();
414
+ }
415
+ catch (err) {
416
+ return c.json({ error: 'Invalid JSON body' }, 400);
417
+ }
418
+ const { token, chainId } = body;
419
+ if (!token && !captchaDisabled) {
420
+ return c.json({ error: 'Missing token' }, 400);
421
+ }
422
+ if (!chainId) {
423
+ return c.json({ error: 'Missing chainId' }, 400);
424
+ }
425
+ const chainIdNum = parseChainId(chainId);
426
+ if (chainIdNum === null) {
427
+ return c.json({ error: 'Invalid chainId' }, 400);
428
+ }
429
+ const parsed = parseCallRequest(body);
430
+ if (parsed.status === 'invalid') {
431
+ return c.json({ error: parsed.error }, 400);
432
+ }
433
+ const { to, data, value } = parsed.call;
434
+ const lookup = await resolveChain(env, chainIdNum);
435
+ if (lookup.status === 'not-configured') {
436
+ return c.json({ error: `Faucet not configured for chain ${chainIdNum}` }, 400);
437
+ }
438
+ if (lookup.status === 'invalid') {
439
+ console.error(`invalid config for chain ${chainIdNum}: ${lookup.details}`);
440
+ return c.json({ error: 'Faucet misconfigured' }, 500);
441
+ }
442
+ if (lookup.status === 'unreachable') {
443
+ console.error(`could not reach the followed node: ${lookup.details}`);
444
+ return c.json({ error: 'Could not reach the chain rpc' }, 503);
445
+ }
446
+ const chain = lookup.chain;
447
+ const chainConfig = chain.config;
448
+ // parsed before any network work, so a typo in a limit is a refusal
449
+ const cooldowns = getCooldowns(env);
450
+ if (cooldowns.status === 'invalid') {
451
+ console.error(cooldowns.details);
452
+ return c.json({ error: 'Faucet misconfigured' }, 500);
453
+ }
454
+ const { addressCooldown, ipCooldown } = cooldowns;
455
+ // ---------------------------------------------------------------
456
+ // 1. is this call permitted at all
457
+ // ---------------------------------------------------------------
458
+ if (mode === 'allowlist') {
459
+ const allowlistLookup = getCallAllowlist(env, chainIdNum);
460
+ if (allowlistLookup.status !== 'ok') {
461
+ console.error(`CALL_ALLOWLIST_${chainIdNum} is ${allowlistLookup.status === 'invalid'
462
+ ? `invalid: ${allowlistLookup.details}`
463
+ : 'not set, every call on this chain is refused'}`);
464
+ return c.json({ error: 'Faucet misconfigured' }, 500);
465
+ }
466
+ if (!isCallAllowed(allowlistLookup.allowlist, to, data)) {
467
+ return c.json({
468
+ error: 'This faucet does not allow that contract and function combination',
469
+ }, 400);
470
+ }
471
+ }
472
+ const now = Math.floor(Date.now() / 1000);
473
+ const ip = getClientIp(c);
474
+ // `to` is a shared contract, so it cannot be a rate limiting key: the ip
475
+ // is the only one this endpoint has. Without it there is no limit at
476
+ // all, so an unknown ip is refused rather than served.
477
+ if (!captchaDisabled && ip === '') {
478
+ console.error('refusing /execute: no client ip, so no rate limit would apply. Put the server behind a proxy that sets X-Forwarded-For.');
479
+ return c.json({
480
+ error: 'This faucet cannot determine your ip, and refuses to execute calls it cannot rate limit',
481
+ }, 503);
482
+ }
483
+ // the key the rate limits and the nonce lock live under: the bare id
484
+ // for a CHAIN_<id> entry, the chain identity for a followed one. Read
485
+ // before the captcha so an unreachable node does not burn the token.
486
+ let chainIdKey;
487
+ try {
488
+ chainIdKey = await getChainStateKey(chain);
489
+ }
490
+ catch (err) {
491
+ console.error('could not read the chain identity', err);
492
+ return c.json({ error: 'Could not reach the chain rpc' }, 503);
493
+ }
494
+ // ---------------------------------------------------------------
495
+ // 2. captcha: single use token, then provider verification
496
+ // ---------------------------------------------------------------
497
+ const refusal = await checkCaptcha({ env, storage, token, ip, now });
498
+ if (refusal) {
499
+ return c.json({ error: refusal.error }, refusal.status);
500
+ }
501
+ // ---------------------------------------------------------------
502
+ // 3. rate limit, on the ip alone. A disabled captcha means localhost,
503
+ // where every account shares one ip, so the bucket is skipped.
504
+ // ---------------------------------------------------------------
505
+ let claimId = null;
506
+ if (!captchaDisabled) {
507
+ // an empty address disables the address bucket, see RemoteSQLStorage
508
+ claimId = await storage.reserveClaim({
509
+ chainId: chainIdKey,
510
+ address: '',
511
+ ip,
512
+ amount: value.toString(),
513
+ now,
514
+ addressCutoff: now,
515
+ ipCutoff: now - ipCooldown,
516
+ });
517
+ if (claimId === null) {
518
+ const hit = await storage.getRateLimitHit({
519
+ chainId: chainIdKey,
520
+ address: '',
521
+ ip,
522
+ now,
523
+ addressCutoff: now,
524
+ ipCutoff: now - ipCooldown,
525
+ addressCooldown,
526
+ ipCooldown,
527
+ });
528
+ return c.json({
529
+ error: `You already used this faucet recently, try again in ${formatDuration(hit.retryAfter)}`,
530
+ retryAfter: hit.retryAfter,
531
+ }, 429, { 'Retry-After': String(hit.retryAfter) });
532
+ }
533
+ }
534
+ // From here on, any failure must give the reservation back.
535
+ const reservedId = claimId;
536
+ const abort = async (message, status) => {
537
+ if (reservedId !== null) {
538
+ await storage.cancelClaim(reservedId).catch((err) => {
539
+ console.error('could not cancel claim reservation', err);
540
+ });
541
+ }
542
+ return c.json({ error: message }, status);
543
+ };
544
+ const publicClient = getPublicClient(chainConfig);
545
+ const account = privateKeyToAccount(faucetPrivateKey);
546
+ // ---------------------------------------------------------------
547
+ // 4. budget: turn a wei ceiling into a gas limit
548
+ // ---------------------------------------------------------------
549
+ // ONE fee reading feeds the budget, the division and the transaction:
550
+ // re-reading would let a bare transfer fail on a fee tick.
551
+ let fees;
552
+ try {
553
+ fees = await getFeeParams(publicClient);
554
+ }
555
+ catch (err) {
556
+ console.error('could not read gas price', err);
557
+ return abort('Could not reach the chain rpc', 503);
558
+ }
559
+ const fee = feePerGas(fees);
560
+ const limitsLookup = getCallLimits(env, chainConfig, fee);
561
+ if (limitsLookup.status === 'invalid') {
562
+ console.error(`invalid call limits: ${limitsLookup.details}`);
563
+ return abort('Faucet misconfigured', 500);
564
+ }
565
+ const limits = limitsLookup.limits;
566
+ if (value > limits.maxValue) {
567
+ return abort(`This faucet sends at most ${limits.maxValue} wei with a call, asked for ${value}`, 400);
568
+ }
569
+ // A revert is free here. Refusing now also avoids broadcasting a call
570
+ // that would run out of gas, which would burn the whole limit.
571
+ let estimated;
572
+ try {
573
+ estimated = await publicClient.estimateGas({
574
+ account,
575
+ to,
576
+ data,
577
+ value,
578
+ });
579
+ }
580
+ catch (err) {
581
+ const details = err instanceof Error && 'shortMessage' in err
582
+ ? String(err.shortMessage)
583
+ : err instanceof Error
584
+ ? err.message
585
+ : 'unknown error';
586
+ return abort(`This call cannot be executed: ${details}`, 400);
587
+ }
588
+ const plan = planGas({ limits, value, estimated, feePerGas: fee });
589
+ if (plan.status === 'does-not-fit') {
590
+ return abort(plan.details, 400);
591
+ }
592
+ // ---------------------------------------------------------------
593
+ // 5. can the faucet still pay the worst case?
594
+ // ---------------------------------------------------------------
595
+ try {
596
+ const faucetBalance = await publicClient.getBalance({
597
+ address: account.address,
598
+ });
599
+ if (faucetBalance < plan.ceiling) {
600
+ console.error(`faucet ${account.address} is out of funds on chain ${chainIdNum}: balance ${faucetBalance}, needs ${plan.ceiling}`);
601
+ return abort('The faucet is temporarily out of funds, please try again later', 503);
602
+ }
603
+ }
604
+ catch (err) {
605
+ console.error('could not check faucet balance', err);
606
+ return abort('Could not reach the chain rpc', 503);
607
+ }
608
+ // ---------------------------------------------------------------
609
+ // 6. serialise sending so concurrent calls cannot reuse a nonce
610
+ // ---------------------------------------------------------------
611
+ const lock = await acquireChainLockWaiting(storage, chainIdKey);
612
+ if (!lock.acquired) {
613
+ return abort('The faucet is busy dispensing other claims, please try again in a few seconds', 503);
614
+ }
615
+ let nonceUsed = null;
616
+ try {
617
+ const pendingNonce = await publicClient.getTransactionCount({
618
+ address: account.address,
619
+ blockTag: 'pending',
620
+ });
621
+ const nonce = lock.lastNonce === null
622
+ ? pendingNonce
623
+ : Math.max(lock.lastNonce + 1, pendingNonce);
624
+ const walletClient = getWalletClient(chainConfig, account);
625
+ // gas and fee are both explicit: the ceiling is only a real bound
626
+ // because the server picked both numbers.
627
+ const txHash = fees.type === 'eip1559'
628
+ ? await walletClient.sendTransaction({
629
+ to,
630
+ data,
631
+ value,
632
+ nonce,
633
+ gas: plan.gasLimit,
634
+ maxFeePerGas: fees.maxFeePerGas,
635
+ maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
636
+ })
637
+ : await walletClient.sendTransaction({
638
+ to,
639
+ data,
640
+ value,
641
+ nonce,
642
+ gas: plan.gasLimit,
643
+ gasPrice: fees.gasPrice,
644
+ });
645
+ nonceUsed = nonce;
646
+ await storage.releaseChainLock(chainIdKey, nonceUsed);
647
+ if (reservedId !== null) {
648
+ await storage.recordClaimTx(reservedId, txHash);
649
+ }
650
+ background(c, storage.cleanup(now - USED_TOKEN_RETENTION_SECONDS, now - CLAIM_RETENTION_SECONDS));
651
+ return c.json({ success: true, txHash });
652
+ }
653
+ catch (err) {
654
+ console.error('Transaction error:', err);
655
+ await storage.releaseChainLock(chainIdKey, nonceUsed).catch((e) => {
656
+ console.error('could not release chain lock', e);
657
+ });
658
+ const errorMessage = err instanceof Error ? err.message : 'Transaction failed';
659
+ return abort(errorMessage, 500);
660
+ }
307
661
  });
308
662
  return app;
309
663
  }