faucet-server-app 0.0.6 → 0.2.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 (52) hide show
  1. package/dist/esm/api/index.d.ts +51 -16
  2. package/dist/esm/api/index.d.ts.map +1 -1
  3. package/dist/esm/api/index.js +567 -79
  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/captcha.d.ts +28 -0
  10. package/dist/esm/captcha.d.ts.map +1 -0
  11. package/dist/esm/captcha.js +58 -0
  12. package/dist/esm/captcha.js.map +1 -0
  13. package/dist/esm/chains.d.ts +17552 -0
  14. package/dist/esm/chains.d.ts.map +1 -0
  15. package/dist/esm/chains.js +137 -0
  16. package/dist/esm/chains.js.map +1 -0
  17. package/dist/esm/config.d.ts +12 -0
  18. package/dist/esm/config.d.ts.map +1 -0
  19. package/dist/esm/config.js +28 -0
  20. package/dist/esm/config.js.map +1 -0
  21. package/dist/esm/env.d.ts +56 -0
  22. package/dist/esm/env.d.ts.map +1 -1
  23. package/dist/esm/env.js +81 -1
  24. package/dist/esm/env.js.map +1 -1
  25. package/dist/esm/index.d.ts +135 -42
  26. package/dist/esm/index.d.ts.map +1 -1
  27. package/dist/esm/index.js +39 -16
  28. package/dist/esm/index.js.map +1 -1
  29. package/dist/esm/schema/ts/db.sql.d.ts +1 -1
  30. package/dist/esm/schema/ts/db.sql.d.ts.map +1 -1
  31. package/dist/esm/schema/ts/db.sql.js +25 -4
  32. package/dist/esm/schema/ts/db.sql.js.map +1 -1
  33. package/dist/esm/setup.d.ts +2 -0
  34. package/dist/esm/setup.d.ts.map +1 -1
  35. package/dist/esm/setup.js +25 -7
  36. package/dist/esm/setup.js.map +1 -1
  37. package/dist/esm/storage/RemoteSQLStorage.d.ts +49 -0
  38. package/dist/esm/storage/RemoteSQLStorage.d.ts.map +1 -0
  39. package/dist/esm/storage/RemoteSQLStorage.js +158 -0
  40. package/dist/esm/storage/RemoteSQLStorage.js.map +1 -0
  41. package/package.json +1 -1
  42. package/src/api/index.ts +752 -105
  43. package/src/calls.ts +447 -0
  44. package/src/captcha.ts +92 -0
  45. package/src/chains.ts +175 -0
  46. package/src/config.ts +33 -0
  47. package/src/env.ts +129 -0
  48. package/src/index.ts +60 -18
  49. package/src/schema/sql/db.sql +25 -4
  50. package/src/schema/ts/db.sql.ts +25 -4
  51. package/src/setup.ts +28 -11
  52. package/src/storage/RemoteSQLStorage.ts +252 -0
package/src/api/index.ts CHANGED
@@ -1,23 +1,34 @@
1
- import {Hono} from 'hono';
1
+ import {Context, Hono} from 'hono';
2
2
  import {ServerOptions} from '../types.js';
3
3
  import {setup} from '../setup.js';
4
- import {Env} from '../env.js';
5
4
  import {
6
- createWalletClient,
7
- http,
8
- isAddress,
9
- parseEther,
10
- type Hex,
11
- type Address,
12
- } from 'viem';
5
+ CHAIN_LOCK_TIMEOUT_SECONDS,
6
+ CLAIM_RETENTION_SECONDS,
7
+ Env,
8
+ USED_TOKEN_RETENTION_SECONDS,
9
+ getBigIntEnv,
10
+ getCooldowns,
11
+ } from '../env.js';
12
+ import {isAddress, type Hex, type Address} from 'viem';
13
13
  import {privateKeyToAccount} from 'viem/accounts';
14
-
15
- const PROSOPO_VERIFY_ENDPOINT = 'https://api.prosopo.io/siteverify';
16
-
17
- type VerifyResponse = {
18
- verified: boolean;
19
- [key: string]: unknown;
20
- };
14
+ import {
15
+ estimateTransferCost,
16
+ feePerGas,
17
+ getChainConfig,
18
+ getFeeParams,
19
+ getPublicClient,
20
+ getWalletClient,
21
+ parseChainId,
22
+ } from '../chains.js';
23
+ import {hashToken, verifyProsopoCaptcha} from '../captcha.js';
24
+ import {
25
+ getArbitraryCallsMode,
26
+ getCallAllowlist,
27
+ getCallLimits,
28
+ isCallAllowed,
29
+ parseCallRequest,
30
+ planGas,
31
+ } from '../calls.js';
21
32
 
22
33
  type ClaimRequest = {
23
34
  token: string;
@@ -25,41 +36,126 @@ type ClaimRequest = {
25
36
  address: string;
26
37
  };
27
38
 
28
- async function verifyProsopoCaptcha(
29
- token: string,
30
- secret: string,
31
- ): Promise<boolean> {
32
- const body = {
33
- token,
34
- secret,
35
- };
39
+ type ExecuteRequest = {
40
+ token: string;
41
+ chainId: string;
42
+ to: string;
43
+ data?: string;
44
+ value?: string;
45
+ };
46
+
47
+ // A refusal, kept as data so shared checks can be reused across endpoints
48
+ // without fighting hono's response typing.
49
+ type Refusal = {error: string; status: 401 | 500 | 503};
50
+
51
+ /**
52
+ * Burns the captcha token so it cannot be replayed, then verifies it with the
53
+ * provider. Shared by /claim and /execute. Returns null when the caller may
54
+ * proceed. A disabled captcha skips both.
55
+ */
56
+ async function checkCaptcha(params: {
57
+ env: Env;
58
+ storage: {burnToken: (hash: string, now: number) => Promise<boolean>};
59
+ token: string;
60
+ ip: string;
61
+ now: number;
62
+ }): Promise<Refusal | null> {
63
+ const {env, storage, token, ip, now} = params;
64
+ if (env.DISABLE_CAPTCHA === 'true') {
65
+ return null;
66
+ }
67
+
68
+ const tokenHash = await hashToken(token);
69
+ const fresh = await storage.burnToken(tokenHash, now);
70
+ if (!fresh) {
71
+ return {error: 'Captcha token already used', status: 401};
72
+ }
36
73
 
37
- const response = await fetch(PROSOPO_VERIFY_ENDPOINT, {
38
- method: 'POST',
39
- headers: {
40
- 'Content-Type': 'application/json',
74
+ const verification = await verifyProsopoCaptcha(
75
+ token,
76
+ env.PROSOPO_SITE_PRIVATE_KEY!,
77
+ {
78
+ failOpen: env.CAPTCHA_FAIL_OPEN === 'true',
79
+ ip: ip || undefined,
41
80
  },
42
- body: JSON.stringify(body),
43
- });
81
+ );
82
+ if (!verification.ok) {
83
+ if (verification.reason === 'unavailable') {
84
+ console.error(`captcha unavailable: ${verification.details}`);
85
+ return {
86
+ error:
87
+ 'Captcha verification is temporarily unavailable, please try again later',
88
+ status: 503,
89
+ };
90
+ }
91
+ return {error: 'Captcha verification failed', status: 401};
92
+ }
93
+ return null;
94
+ }
44
95
 
45
- const result = (await response.json()) as VerifyResponse;
46
- return result.verified === true;
96
+ const TX_HASH_REGEX = /^0x[0-9a-fA-F]{64}$/;
97
+
98
+ /**
99
+ * Best effort ip of the caller, used as a rate limiting bucket.
100
+ * Returns '' when the server sits behind no proxy that tells us: in that case
101
+ * the ip bucket is skipped entirely rather than lumping every user together.
102
+ */
103
+ function getClientIp(c: Context): string {
104
+ const headers = ['cf-connecting-ip', 'x-real-ip', 'x-forwarded-for'];
105
+ for (const header of headers) {
106
+ const value = c.req.header(header);
107
+ if (value) {
108
+ // x-forwarded-for is a list, the left most entry is the client
109
+ const ip = value.split(',')[0].trim();
110
+ if (ip) {
111
+ return ip;
112
+ }
113
+ }
114
+ }
115
+ return '';
47
116
  }
48
117
 
49
- function parseChainConfig(
50
- configValue: string,
51
- ): {amount: string; rpcUrl: string} | null {
52
- // Format: <amount>:<rpc_endpoint>
53
- const colonIndex = configValue.indexOf(':');
54
- if (colonIndex === -1) {
55
- return null;
118
+ // Waits for the per chain send lock instead of turning the caller away: a
119
+ // dispense takes a few hundred milliseconds, so concurrent claims queue rather
120
+ // than fail. Gives up after LOCK_WAIT_MS so a request never hangs.
121
+ const LOCK_WAIT_MS = 12000;
122
+ const LOCK_RETRY_INTERVAL_MS = 300;
123
+
124
+ async function acquireChainLockWaiting(
125
+ storage: {
126
+ acquireChainLock: (
127
+ chainId: string,
128
+ now: number,
129
+ lockedUntil: number,
130
+ ) => Promise<{acquired: boolean; lastNonce: number | null}>;
131
+ },
132
+ chainId: string,
133
+ ): Promise<{acquired: boolean; lastNonce: number | null}> {
134
+ const deadline = Date.now() + LOCK_WAIT_MS;
135
+ for (;;) {
136
+ const now = Math.floor(Date.now() / 1000);
137
+ const lock = await storage.acquireChainLock(
138
+ chainId,
139
+ now,
140
+ now + CHAIN_LOCK_TIMEOUT_SECONDS,
141
+ );
142
+ if (lock.acquired || Date.now() >= deadline) {
143
+ return lock;
144
+ }
145
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_INTERVAL_MS));
56
146
  }
57
- const amount = configValue.substring(0, colonIndex);
58
- const rpcUrl = configValue.substring(colonIndex + 1);
59
- if (!amount || !rpcUrl) {
60
- return null;
147
+ }
148
+
149
+ // Runs a promise outside of the response path, on platforms that support it.
150
+ function background(c: Context, promise: Promise<unknown>): void {
151
+ const safe = promise.catch((err) => {
152
+ console.error('background task failed', err);
153
+ });
154
+ try {
155
+ c.executionCtx.waitUntil(safe);
156
+ } catch (err) {
157
+ // no execution context (node), the promise just runs on its own
61
158
  }
62
- return {amount, rpcUrl};
63
159
  }
64
160
 
65
161
  export function getAPI<CustomEnv extends Env>(
@@ -71,147 +167,698 @@ export function getAPI<CustomEnv extends Env>(
71
167
  const config = c.get('config');
72
168
  const env = config.env;
73
169
  const captchaDisabled = env.DISABLE_CAPTCHA === 'true';
74
- return c.json({captchaDisabled});
170
+ const modeLookup = getArbitraryCallsMode(env);
171
+ if (modeLookup.status === 'invalid') {
172
+ // same answer as /execute gives, rather than quietly reporting 'off'
173
+ // for a mode the operator clearly meant to set
174
+ console.error(
175
+ `invalid ENABLE_ARBITRARY_CALLS: "${env.ENABLE_ARBITRARY_CALLS}"`,
176
+ );
177
+ return c.json({error: 'Faucet misconfigured'}, 500);
178
+ }
179
+ const mode = modeLookup.mode;
180
+ // only advertised when enabled, so a faucet that never turns this on
181
+ // answers exactly what it always did
182
+ if (mode === 'off') {
183
+ return c.json({captchaDisabled});
184
+ }
185
+ // the address a call is signed by is what the user is really lending,
186
+ // so the popup can show it. It is public: every dispensed transaction
187
+ // carries it as the sender.
188
+ let faucetAddress: string | undefined;
189
+ try {
190
+ faucetAddress = privateKeyToAccount(
191
+ env.FAUCET_PRIVATE_KEY as Hex,
192
+ ).address;
193
+ } catch (err) {
194
+ // a missing or malformed key is reported by the claim path instead
195
+ }
196
+ return c.json({captchaDisabled, arbitraryCalls: mode, faucetAddress});
75
197
  })
76
198
  .get('/chain/:chainId', async (c) => {
77
199
  const config = c.get('config');
78
200
  const env = config.env;
79
- const chainId = c.req.param('chainId');
80
201
 
81
- // Validate chainId
82
- const chainIdNum = parseInt(chainId, 10);
83
- if (isNaN(chainIdNum) || chainIdNum <= 0) {
202
+ const chainIdNum = parseChainId(c.req.param('chainId'));
203
+ if (chainIdNum === null) {
84
204
  return c.json({error: 'Invalid chainId'}, 400);
85
205
  }
86
206
 
87
- // Check for chain-specific config
88
- const chainConfigKey = `CHAIN_${chainId}` as `CHAIN_${string}`;
89
- const chainConfigValue = env[chainConfigKey];
90
-
91
- if (!chainConfigValue) {
207
+ const lookup = getChainConfig(env, chainIdNum);
208
+ if (lookup.status === 'not-configured') {
92
209
  return c.json(
93
- {error: `Faucet not configured for chain ${chainId}`},
210
+ {error: `Faucet not configured for chain ${chainIdNum}`},
94
211
  404,
95
212
  );
96
213
  }
214
+ if (lookup.status === 'invalid') {
215
+ console.error(
216
+ `invalid config for chain ${chainIdNum}: ${lookup.details}`,
217
+ );
218
+ return c.json({error: `Faucet misconfigured`}, 500);
219
+ }
220
+
221
+ // Note: the rpc endpoint is deliberately NOT returned, it is a server
222
+ // side secret. Clients follow their transaction through /tx instead.
223
+ return c.json({
224
+ chainId: chainIdNum,
225
+ amount: lookup.config.amount.toString(),
226
+ });
227
+ })
228
+ .get('/tx/:chainId/:txHash', async (c) => {
229
+ const config = c.get('config');
230
+ const env = config.env;
231
+
232
+ const chainIdNum = parseChainId(c.req.param('chainId'));
233
+ if (chainIdNum === null) {
234
+ return c.json({error: 'Invalid chainId'}, 400);
235
+ }
97
236
 
98
- const chainConfig = parseChainConfig(chainConfigValue);
99
- if (!chainConfig) {
237
+ const txHash = c.req.param('txHash');
238
+ if (!TX_HASH_REGEX.test(txHash)) {
239
+ return c.json({error: 'Invalid transaction hash'}, 400);
240
+ }
241
+
242
+ const lookup = getChainConfig(env, chainIdNum);
243
+ if (lookup.status !== 'ok') {
100
244
  return c.json(
101
- {error: `Invalid chain config for chain ${chainId}`},
102
- 500,
245
+ {error: `Faucet not configured for chain ${chainIdNum}`},
246
+ 404,
103
247
  );
104
248
  }
105
249
 
106
- return c.json({rpcUrl: chainConfig.rpcUrl, chainId: chainIdNum});
250
+ const publicClient = getPublicClient(lookup.config);
251
+ try {
252
+ const receipt = await publicClient.getTransactionReceipt({
253
+ hash: txHash as Hex,
254
+ });
255
+ return c.json({
256
+ status: receipt.status === 'success' ? 'success' : 'failed',
257
+ blockNumber: receipt.blockNumber.toString(),
258
+ });
259
+ } catch (err) {
260
+ // viem throws when the receipt is not available yet
261
+ return c.json({status: 'pending'});
262
+ }
107
263
  })
108
264
  .post('/claim', async (c) => {
109
265
  const config = c.get('config');
110
- const env = config.env;
266
+ const {env, storage} = config;
111
267
 
112
- // Check if captcha is disabled (for localhost development)
113
268
  const captchaDisabled = env.DISABLE_CAPTCHA === 'true';
114
-
115
- // Validate PROSOPO secret (only required if captcha is enabled)
116
269
  const secret = env.PROSOPO_SITE_PRIVATE_KEY;
117
270
  if (!captchaDisabled && !secret) {
118
271
  return c.json({error: 'PROSOPO_SITE_PRIVATE_KEY not configured'}, 500);
119
272
  }
120
273
 
121
- // Validate FAUCET_PRIVATE_KEY
122
274
  const faucetPrivateKey = env.FAUCET_PRIVATE_KEY;
123
275
  if (!faucetPrivateKey) {
124
276
  return c.json({error: 'FAUCET_PRIVATE_KEY not configured'}, 500);
125
277
  }
126
278
 
127
- const body = await c.req.json<ClaimRequest>();
279
+ let body: ClaimRequest;
280
+ try {
281
+ body = await c.req.json<ClaimRequest>();
282
+ } catch (err) {
283
+ return c.json({error: 'Invalid JSON body'}, 400);
284
+ }
128
285
  const {token, chainId, address} = body;
129
286
 
130
- // Validate required fields
131
287
  if (!token) {
132
288
  return c.json({error: 'Missing token'}, 400);
133
289
  }
134
-
135
290
  if (!chainId) {
136
291
  return c.json({error: 'Missing chainId'}, 400);
137
292
  }
138
-
139
293
  if (!address) {
140
294
  return c.json({error: 'Missing address'}, 400);
141
295
  }
142
-
143
- // Validate address format
144
296
  if (!isAddress(address)) {
145
297
  return c.json({error: 'Invalid Ethereum address'}, 400);
146
298
  }
147
299
 
148
- // Parse chainId
149
- const chainIdNum = parseInt(chainId, 10);
150
- if (isNaN(chainIdNum) || chainIdNum <= 0) {
300
+ const chainIdNum = parseChainId(chainId);
301
+ if (chainIdNum === null) {
151
302
  return c.json({error: 'Invalid chainId'}, 400);
152
303
  }
153
304
 
154
- // Check for chain-specific config (format: <amount>:<rpc_endpoint>)
155
- const chainConfigKey = `CHAIN_${chainId}` as `CHAIN_${string}`;
156
- const chainConfigValue = env[chainConfigKey];
157
-
158
- if (!chainConfigValue) {
305
+ const lookup = getChainConfig(env, chainIdNum);
306
+ if (lookup.status === 'not-configured') {
159
307
  return c.json(
160
- {error: `Faucet not configured for chain ${chainId}`},
308
+ {error: `Faucet not configured for chain ${chainIdNum}`},
161
309
  400,
162
310
  );
163
311
  }
312
+ if (lookup.status === 'invalid') {
313
+ console.error(
314
+ `invalid config for chain ${chainIdNum}: ${lookup.details}`,
315
+ );
316
+ return c.json({error: 'Faucet misconfigured'}, 500);
317
+ }
318
+ const chainConfig = lookup.config;
319
+
320
+ // ---------------------------------------------------------------
321
+ // 0. the limits this faucet runs under. Parsed up front, before any
322
+ // network work: a typo in one of them is a refusal, never a
323
+ // quietly weaker limit.
324
+ // ---------------------------------------------------------------
325
+ const maxRecipientBalanceEnv = getBigIntEnv(env.MAX_RECIPIENT_BALANCE);
326
+ if (maxRecipientBalanceEnv.status === 'invalid') {
327
+ console.error(
328
+ `MAX_RECIPIENT_BALANCE is not a wei amount: "${env.MAX_RECIPIENT_BALANCE}"`,
329
+ );
330
+ return c.json({error: 'Faucet misconfigured'}, 500);
331
+ }
332
+ const maxRecipientBalance =
333
+ maxRecipientBalanceEnv.status === 'ok'
334
+ ? maxRecipientBalanceEnv.value
335
+ : chainConfig.amount * 10n;
336
+
337
+ const cooldowns = getCooldowns(env);
338
+ if (cooldowns.status === 'invalid') {
339
+ console.error(cooldowns.details);
340
+ return c.json({error: 'Faucet misconfigured'}, 500);
341
+ }
342
+ const {addressCooldown, ipCooldown} = cooldowns;
343
+
344
+ const now = Math.floor(Date.now() / 1000);
345
+ const ip = getClientIp(c);
346
+ const normalizedAddress = address.toLowerCase();
347
+ const chainIdKey = String(chainIdNum);
348
+
349
+ // ---------------------------------------------------------------
350
+ // 1. captcha: single use token, then provider verification
351
+ // ---------------------------------------------------------------
352
+ const refusal = await checkCaptcha({env, storage, token, ip, now});
353
+ if (refusal) {
354
+ return c.json({error: refusal.error}, refusal.status);
355
+ }
356
+
357
+ const publicClient = getPublicClient(chainConfig);
358
+
359
+ // ---------------------------------------------------------------
360
+ // 2. do not top up an address that already holds enough
361
+ // ---------------------------------------------------------------
362
+ if (maxRecipientBalance > 0n) {
363
+ try {
364
+ const recipientBalance = await publicClient.getBalance({
365
+ address: address as Address,
366
+ });
367
+ if (recipientBalance >= maxRecipientBalance) {
368
+ return c.json(
369
+ {
370
+ error:
371
+ 'This address already holds enough funds on this chain, the faucet is for empty accounts',
372
+ },
373
+ 400,
374
+ );
375
+ }
376
+ } catch (err) {
377
+ console.error('could not read recipient balance', err);
378
+ return c.json({error: 'Could not reach the chain rpc'}, 503);
379
+ }
380
+ }
164
381
 
165
- const chainConfig = parseChainConfig(chainConfigValue);
166
- if (!chainConfig) {
382
+ // ---------------------------------------------------------------
383
+ // 3. rate limit: atomically reserve a slot for this address / ip
384
+ // ---------------------------------------------------------------
385
+ const claimId = await storage.reserveClaim({
386
+ chainId: chainIdKey,
387
+ address: normalizedAddress,
388
+ ip,
389
+ amount: chainConfig.amount.toString(),
390
+ now,
391
+ addressCutoff: now - addressCooldown,
392
+ ipCutoff: now - ipCooldown,
393
+ });
394
+
395
+ if (claimId === null) {
396
+ const hit = await storage.getRateLimitHit({
397
+ chainId: chainIdKey,
398
+ address: normalizedAddress,
399
+ ip,
400
+ now,
401
+ addressCutoff: now - addressCooldown,
402
+ ipCutoff: now - ipCooldown,
403
+ addressCooldown,
404
+ ipCooldown,
405
+ });
406
+ const subject = hit.reason === 'address' ? 'This address' : 'You';
167
407
  return c.json(
168
408
  {
169
- error: `Invalid chain config format for chain ${chainId}. Expected: <amount>:<rpc_endpoint>`,
409
+ error: `${subject} already claimed recently, please wait ${formatDuration(
410
+ hit.retryAfter,
411
+ )}`,
412
+ retryAfter: hit.retryAfter,
170
413
  },
171
- 500,
414
+ 429,
415
+ {'Retry-After': String(hit.retryAfter)},
172
416
  );
173
417
  }
174
418
 
175
- // Verify captcha (skip if disabled for localhost development)
176
- if (!captchaDisabled) {
177
- const verified = await verifyProsopoCaptcha(token, secret!);
419
+ // From here on, any failure must give the reservation back.
420
+ const abort = async (
421
+ message: string,
422
+ status: 400 | 500 | 503,
423
+ ): Promise<Response> => {
424
+ await storage.cancelClaim(claimId).catch((err) => {
425
+ console.error('could not cancel claim reservation', err);
426
+ });
427
+ return c.json({error: message}, status);
428
+ };
429
+
430
+ const account = privateKeyToAccount(faucetPrivateKey as Hex);
178
431
 
179
- if (!verified) {
180
- return c.json({error: 'Captcha verification failed'}, 401);
432
+ // ---------------------------------------------------------------
433
+ // 4. can the faucet still pay?
434
+ // ---------------------------------------------------------------
435
+ try {
436
+ const faucetBalance = await publicClient.getBalance({
437
+ address: account.address,
438
+ });
439
+ const gasCost = await estimateTransferCost(publicClient);
440
+ if (faucetBalance < chainConfig.amount + gasCost) {
441
+ console.error(
442
+ `faucet ${account.address} is out of funds on chain ${chainIdNum}: balance ${faucetBalance}, needs ${
443
+ chainConfig.amount + gasCost
444
+ }`,
445
+ );
446
+ return abort(
447
+ 'The faucet is temporarily out of funds, please try again later',
448
+ 503,
449
+ );
181
450
  }
451
+ } catch (err) {
452
+ console.error('could not check faucet balance', err);
453
+ return abort('Could not reach the chain rpc', 503);
454
+ }
455
+
456
+ // ---------------------------------------------------------------
457
+ // 5. serialise sending so concurrent claims cannot reuse a nonce
458
+ // ---------------------------------------------------------------
459
+ const lock = await acquireChainLockWaiting(storage, chainIdKey);
460
+ if (!lock.acquired) {
461
+ return abort(
462
+ 'The faucet is busy dispensing other claims, please try again in a few seconds',
463
+ 503,
464
+ );
182
465
  }
183
466
 
467
+ let nonceUsed: number | null = null;
184
468
  try {
185
- // Create wallet client and send transaction
186
- const account = privateKeyToAccount(faucetPrivateKey as Hex);
187
- const {amount, rpcUrl} = chainConfig;
469
+ const pendingNonce = await publicClient.getTransactionCount({
470
+ address: account.address,
471
+ blockTag: 'pending',
472
+ });
473
+ // the chain is the source of truth, our own counter only guards
474
+ // against two claims reading the same pending nonce
475
+ const nonce =
476
+ lock.lastNonce === null
477
+ ? pendingNonce
478
+ : Math.max(lock.lastNonce + 1, pendingNonce);
479
+
480
+ const walletClient = getWalletClient(chainConfig, account);
481
+ const txHash = await walletClient.sendTransaction({
482
+ to: address as Address,
483
+ value: chainConfig.amount,
484
+ nonce,
485
+ });
486
+ nonceUsed = nonce;
188
487
 
189
- const walletClient = createWalletClient({
190
- account,
191
- chain: {
192
- id: chainIdNum,
193
- name: `Chain ${chainIdNum}`,
194
- nativeCurrency: {name: 'ETH', symbol: 'ETH', decimals: 18},
195
- rpcUrls: {
196
- default: {http: [rpcUrl]},
488
+ await storage.releaseChainLock(chainIdKey, nonceUsed);
489
+ await storage.recordClaimTx(claimId, txHash);
490
+
491
+ background(
492
+ c,
493
+ storage.cleanup(
494
+ now - USED_TOKEN_RETENTION_SECONDS,
495
+ now - CLAIM_RETENTION_SECONDS,
496
+ ),
497
+ );
498
+
499
+ return c.json({success: true, txHash});
500
+ } catch (err) {
501
+ console.error('Transaction error:', err);
502
+ await storage.releaseChainLock(chainIdKey, nonceUsed).catch((e) => {
503
+ console.error('could not release chain lock', e);
504
+ });
505
+ const errorMessage =
506
+ err instanceof Error ? err.message : 'Transaction failed';
507
+ return abort(errorMessage, 500);
508
+ }
509
+ })
510
+ /**
511
+ * Executes a caller chosen call, paid for by the faucet.
512
+ *
513
+ * Off unless ENABLE_ARBITRARY_CALLS says otherwise, because this lends the
514
+ * faucet key's authority to whoever passes the captcha. See
515
+ * docs/specs/arbitrary-calls.md for the threat model.
516
+ */
517
+ .post('/execute', async (c) => {
518
+ const config = c.get('config');
519
+ const {env, storage} = config;
520
+
521
+ const modeLookup = getArbitraryCallsMode(env);
522
+ if (modeLookup.status === 'invalid') {
523
+ console.error(
524
+ `invalid ENABLE_ARBITRARY_CALLS: "${env.ENABLE_ARBITRARY_CALLS}"`,
525
+ );
526
+ return c.json({error: 'Faucet misconfigured'}, 500);
527
+ }
528
+ const mode = modeLookup.mode;
529
+ if (mode === 'off') {
530
+ return c.json(
531
+ {error: 'Arbitrary calls are not enabled on this faucet'},
532
+ 404,
533
+ );
534
+ }
535
+
536
+ const captchaDisabled = env.DISABLE_CAPTCHA === 'true';
537
+ const secret = env.PROSOPO_SITE_PRIVATE_KEY;
538
+ if (!captchaDisabled && !secret) {
539
+ return c.json({error: 'PROSOPO_SITE_PRIVATE_KEY not configured'}, 500);
540
+ }
541
+
542
+ const faucetPrivateKey = env.FAUCET_PRIVATE_KEY;
543
+ if (!faucetPrivateKey) {
544
+ return c.json({error: 'FAUCET_PRIVATE_KEY not configured'}, 500);
545
+ }
546
+
547
+ let body: ExecuteRequest;
548
+ try {
549
+ body = await c.req.json<ExecuteRequest>();
550
+ } catch (err) {
551
+ return c.json({error: 'Invalid JSON body'}, 400);
552
+ }
553
+ const {token, chainId} = body;
554
+
555
+ if (!token && !captchaDisabled) {
556
+ return c.json({error: 'Missing token'}, 400);
557
+ }
558
+ if (!chainId) {
559
+ return c.json({error: 'Missing chainId'}, 400);
560
+ }
561
+ const chainIdNum = parseChainId(chainId);
562
+ if (chainIdNum === null) {
563
+ return c.json({error: 'Invalid chainId'}, 400);
564
+ }
565
+
566
+ const parsed = parseCallRequest(body);
567
+ if (parsed.status === 'invalid') {
568
+ return c.json({error: parsed.error}, 400);
569
+ }
570
+ const {to, data, value} = parsed.call;
571
+
572
+ const lookup = getChainConfig(env, chainIdNum);
573
+ if (lookup.status === 'not-configured') {
574
+ return c.json(
575
+ {error: `Faucet not configured for chain ${chainIdNum}`},
576
+ 400,
577
+ );
578
+ }
579
+ if (lookup.status === 'invalid') {
580
+ console.error(
581
+ `invalid config for chain ${chainIdNum}: ${lookup.details}`,
582
+ );
583
+ return c.json({error: 'Faucet misconfigured'}, 500);
584
+ }
585
+ const chainConfig = lookup.config;
586
+
587
+ // parsed before any network work, so a typo in a limit is a refusal
588
+ const cooldowns = getCooldowns(env);
589
+ if (cooldowns.status === 'invalid') {
590
+ console.error(cooldowns.details);
591
+ return c.json({error: 'Faucet misconfigured'}, 500);
592
+ }
593
+ const {addressCooldown, ipCooldown} = cooldowns;
594
+
595
+ // ---------------------------------------------------------------
596
+ // 1. is this call permitted at all
597
+ // ---------------------------------------------------------------
598
+ if (mode === 'allowlist') {
599
+ const allowlistLookup = getCallAllowlist(env, chainIdNum);
600
+ if (allowlistLookup.status !== 'ok') {
601
+ console.error(
602
+ `CALL_ALLOWLIST_${chainIdNum} is ${
603
+ allowlistLookup.status === 'invalid'
604
+ ? `invalid: ${allowlistLookup.details}`
605
+ : 'not set, every call on this chain is refused'
606
+ }`,
607
+ );
608
+ return c.json({error: 'Faucet misconfigured'}, 500);
609
+ }
610
+ if (!isCallAllowed(allowlistLookup.allowlist, to, data)) {
611
+ return c.json(
612
+ {
613
+ error:
614
+ 'This faucet does not allow that contract and function combination',
197
615
  },
616
+ 400,
617
+ );
618
+ }
619
+ }
620
+
621
+ const now = Math.floor(Date.now() / 1000);
622
+ const ip = getClientIp(c);
623
+ const chainIdKey = String(chainIdNum);
624
+
625
+ // `to` is a shared contract, so it cannot be a rate limiting key: the ip
626
+ // is the only one this endpoint has. Without it there is no limit at
627
+ // all, so an unknown ip is refused rather than served.
628
+ if (!captchaDisabled && ip === '') {
629
+ console.error(
630
+ 'refusing /execute: no client ip, so no rate limit would apply. Put the server behind a proxy that sets X-Forwarded-For.',
631
+ );
632
+ return c.json(
633
+ {
634
+ error:
635
+ 'This faucet cannot determine your ip, and refuses to execute calls it cannot rate limit',
198
636
  },
199
- transport: http(rpcUrl),
637
+ 503,
638
+ );
639
+ }
640
+
641
+ // ---------------------------------------------------------------
642
+ // 2. captcha: single use token, then provider verification
643
+ // ---------------------------------------------------------------
644
+ const refusal = await checkCaptcha({env, storage, token, ip, now});
645
+ if (refusal) {
646
+ return c.json({error: refusal.error}, refusal.status);
647
+ }
648
+
649
+ // ---------------------------------------------------------------
650
+ // 3. rate limit, on the ip alone. A disabled captcha means localhost,
651
+ // where every account shares one ip, so the bucket is skipped.
652
+ // ---------------------------------------------------------------
653
+ let claimId: number | null = null;
654
+ if (!captchaDisabled) {
655
+ // an empty address disables the address bucket, see RemoteSQLStorage
656
+ claimId = await storage.reserveClaim({
657
+ chainId: chainIdKey,
658
+ address: '',
659
+ ip,
660
+ amount: value.toString(),
661
+ now,
662
+ addressCutoff: now,
663
+ ipCutoff: now - ipCooldown,
200
664
  });
665
+ if (claimId === null) {
666
+ const hit = await storage.getRateLimitHit({
667
+ chainId: chainIdKey,
668
+ address: '',
669
+ ip,
670
+ now,
671
+ addressCutoff: now,
672
+ ipCutoff: now - ipCooldown,
673
+ addressCooldown,
674
+ ipCooldown,
675
+ });
676
+ return c.json(
677
+ {
678
+ error: `You already used this faucet recently, try again in ${formatDuration(
679
+ hit.retryAfter,
680
+ )}`,
681
+ retryAfter: hit.retryAfter,
682
+ },
683
+ 429,
684
+ {'Retry-After': String(hit.retryAfter)},
685
+ );
686
+ }
687
+ }
201
688
 
202
- const txHash = await walletClient.sendTransaction({
203
- to: address as Address,
204
- value: BigInt(amount),
689
+ // From here on, any failure must give the reservation back.
690
+ const reservedId = claimId;
691
+ const abort = async (
692
+ message: string,
693
+ status: 400 | 500 | 503,
694
+ ): Promise<Response> => {
695
+ if (reservedId !== null) {
696
+ await storage.cancelClaim(reservedId).catch((err) => {
697
+ console.error('could not cancel claim reservation', err);
698
+ });
699
+ }
700
+ return c.json({error: message}, status);
701
+ };
702
+
703
+ const publicClient = getPublicClient(chainConfig);
704
+ const account = privateKeyToAccount(faucetPrivateKey as Hex);
705
+
706
+ // ---------------------------------------------------------------
707
+ // 4. budget: turn a wei ceiling into a gas limit
708
+ // ---------------------------------------------------------------
709
+ // ONE fee reading feeds the budget, the division and the transaction:
710
+ // re-reading would let a bare transfer fail on a fee tick.
711
+ let fees;
712
+ try {
713
+ fees = await getFeeParams(publicClient);
714
+ } catch (err) {
715
+ console.error('could not read gas price', err);
716
+ return abort('Could not reach the chain rpc', 503);
717
+ }
718
+ const fee = feePerGas(fees);
719
+
720
+ const limitsLookup = getCallLimits(env, chainConfig, fee);
721
+ if (limitsLookup.status === 'invalid') {
722
+ console.error(`invalid call limits: ${limitsLookup.details}`);
723
+ return abort('Faucet misconfigured', 500);
724
+ }
725
+ const limits = limitsLookup.limits;
726
+
727
+ if (value > limits.maxValue) {
728
+ return abort(
729
+ `This faucet sends at most ${limits.maxValue} wei with a call, asked for ${value}`,
730
+ 400,
731
+ );
732
+ }
733
+
734
+ // A revert is free here. Refusing now also avoids broadcasting a call
735
+ // that would run out of gas, which would burn the whole limit.
736
+ let estimated: bigint;
737
+ try {
738
+ estimated = await publicClient.estimateGas({
739
+ account,
740
+ to,
741
+ data,
742
+ value,
205
743
  });
744
+ } catch (err) {
745
+ const details =
746
+ err instanceof Error && 'shortMessage' in err
747
+ ? String((err as {shortMessage: unknown}).shortMessage)
748
+ : err instanceof Error
749
+ ? err.message
750
+ : 'unknown error';
751
+ return abort(`This call cannot be executed: ${details}`, 400);
752
+ }
753
+
754
+ const plan = planGas({limits, value, estimated, feePerGas: fee});
755
+ if (plan.status === 'does-not-fit') {
756
+ return abort(plan.details, 400);
757
+ }
758
+
759
+ // ---------------------------------------------------------------
760
+ // 5. can the faucet still pay the worst case?
761
+ // ---------------------------------------------------------------
762
+ try {
763
+ const faucetBalance = await publicClient.getBalance({
764
+ address: account.address,
765
+ });
766
+ if (faucetBalance < plan.ceiling) {
767
+ console.error(
768
+ `faucet ${account.address} is out of funds on chain ${chainIdNum}: balance ${faucetBalance}, needs ${plan.ceiling}`,
769
+ );
770
+ return abort(
771
+ 'The faucet is temporarily out of funds, please try again later',
772
+ 503,
773
+ );
774
+ }
775
+ } catch (err) {
776
+ console.error('could not check faucet balance', err);
777
+ return abort('Could not reach the chain rpc', 503);
778
+ }
779
+
780
+ // ---------------------------------------------------------------
781
+ // 6. serialise sending so concurrent calls cannot reuse a nonce
782
+ // ---------------------------------------------------------------
783
+ const lock = await acquireChainLockWaiting(storage, chainIdKey);
784
+ if (!lock.acquired) {
785
+ return abort(
786
+ 'The faucet is busy dispensing other claims, please try again in a few seconds',
787
+ 503,
788
+ );
789
+ }
790
+
791
+ let nonceUsed: number | null = null;
792
+ try {
793
+ const pendingNonce = await publicClient.getTransactionCount({
794
+ address: account.address,
795
+ blockTag: 'pending',
796
+ });
797
+ const nonce =
798
+ lock.lastNonce === null
799
+ ? pendingNonce
800
+ : Math.max(lock.lastNonce + 1, pendingNonce);
801
+
802
+ const walletClient = getWalletClient(chainConfig, account);
803
+ // gas and fee are both explicit: the ceiling is only a real bound
804
+ // because the server picked both numbers.
805
+ const txHash =
806
+ fees.type === 'eip1559'
807
+ ? await walletClient.sendTransaction({
808
+ to,
809
+ data,
810
+ value,
811
+ nonce,
812
+ gas: plan.gasLimit,
813
+ maxFeePerGas: fees.maxFeePerGas,
814
+ maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
815
+ })
816
+ : await walletClient.sendTransaction({
817
+ to,
818
+ data,
819
+ value,
820
+ nonce,
821
+ gas: plan.gasLimit,
822
+ gasPrice: fees.gasPrice,
823
+ });
824
+ nonceUsed = nonce;
825
+
826
+ await storage.releaseChainLock(chainIdKey, nonceUsed);
827
+ if (reservedId !== null) {
828
+ await storage.recordClaimTx(reservedId, txHash);
829
+ }
830
+
831
+ background(
832
+ c,
833
+ storage.cleanup(
834
+ now - USED_TOKEN_RETENTION_SECONDS,
835
+ now - CLAIM_RETENTION_SECONDS,
836
+ ),
837
+ );
206
838
 
207
839
  return c.json({success: true, txHash});
208
840
  } catch (err) {
209
841
  console.error('Transaction error:', err);
842
+ await storage.releaseChainLock(chainIdKey, nonceUsed).catch((e) => {
843
+ console.error('could not release chain lock', e);
844
+ });
210
845
  const errorMessage =
211
846
  err instanceof Error ? err.message : 'Transaction failed';
212
- return c.json({error: errorMessage}, 500);
847
+ return abort(errorMessage, 500);
213
848
  }
214
849
  });
215
850
 
216
851
  return app;
217
852
  }
853
+
854
+ function formatDuration(seconds: number): string {
855
+ if (seconds < 60) {
856
+ return `${seconds} second${seconds === 1 ? '' : 's'}`;
857
+ }
858
+ const minutes = Math.ceil(seconds / 60);
859
+ if (minutes < 60) {
860
+ return `${minutes} minute${minutes === 1 ? '' : 's'}`;
861
+ }
862
+ const hours = Math.ceil(minutes / 60);
863
+ return `${hours} hour${hours === 1 ? '' : 's'}`;
864
+ }