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/calls.ts ADDED
@@ -0,0 +1,447 @@
1
+ import {isAddress, type Address, type Hex} from 'viem';
2
+ import {privateKeyToAccount} from 'viem/accounts';
3
+ import {getBigIntEnv, type Env} from './env.js';
4
+ import {parseChainId, type ChainConfig} from './chains.js';
5
+
6
+ /**
7
+ * Arbitrary call execution, see docs/specs/arbitrary-calls.md.
8
+ *
9
+ * Anything other than 'off' lets a caller choose what the faucet key signs,
10
+ * which is a different power from dispensing a fixed amount. Everything in
11
+ * this module exists to bound it.
12
+ */
13
+ export type ArbitraryCallsMode = 'off' | 'allowlist' | 'unrestricted';
14
+
15
+ // gas a plain value transfer costs, the yardstick the default budget uses
16
+ export const SIMPLE_TRANSFER_GAS = 21000n;
17
+
18
+ // absolute rail, so a budget divided by a tiny L2 gas price cannot hand out a
19
+ // gas limit past the block limit
20
+ export const DEFAULT_MAX_CALL_GAS = 2_000_000n;
21
+
22
+ // gas granted on top of the estimate, as a percentage. Without it every call
23
+ // is sent with the maximum the budget allows, which a target that burns gas
24
+ // conditionally would happily spend.
25
+ export const GAS_BUFFER_PERCENT = 125n;
26
+
27
+ export function getArbitraryCallsMode(
28
+ env: Env,
29
+ ): {status: 'ok'; mode: ArbitraryCallsMode} | {status: 'invalid'} {
30
+ const raw = env.ENABLE_ARBITRARY_CALLS;
31
+ if (raw === undefined || raw.trim() === '') {
32
+ return {status: 'ok', mode: 'off'};
33
+ }
34
+ const value = raw.trim();
35
+ if (value === 'off' || value === 'allowlist' || value === 'unrestricted') {
36
+ return {status: 'ok', mode: value};
37
+ }
38
+ return {status: 'invalid'};
39
+ }
40
+
41
+ // ---------------------------------------------------------------------------
42
+ // allow-list
43
+ // ---------------------------------------------------------------------------
44
+
45
+ // contract -> set of 4 byte selectors. A contract with no selector is refused
46
+ // at parse time: allow-listing a whole contract is what makes `transfer` on a
47
+ // token reachable, which defeats the point.
48
+ export type CallAllowlist = Map<string, Set<string>>;
49
+
50
+ export type AllowlistLookup =
51
+ | {status: 'ok'; allowlist: CallAllowlist}
52
+ | {status: 'not-configured'}
53
+ | {status: 'invalid'; details: string};
54
+
55
+ const SELECTOR_REGEX = /^0x[0-9a-f]{8}$/;
56
+
57
+ /**
58
+ * CALL_ALLOWLIST_<CHAIN_ID>=<contract>:<selector>,<selector>;<contract>:<selector>
59
+ */
60
+ export function getCallAllowlist(env: Env, chainId: number): AllowlistLookup {
61
+ const key = `CALL_ALLOWLIST_${chainId}` as `CALL_ALLOWLIST_${string}`;
62
+ const value = env[key];
63
+ if (!value || value.trim() === '') {
64
+ return {status: 'not-configured'};
65
+ }
66
+
67
+ const allowlist: CallAllowlist = new Map();
68
+ for (const rawEntry of value.split(';')) {
69
+ const entry = rawEntry.trim();
70
+ if (entry === '') {
71
+ continue;
72
+ }
73
+ const colonIndex = entry.indexOf(':');
74
+ if (colonIndex === -1) {
75
+ return {
76
+ status: 'invalid',
77
+ details: `entry "${entry}" has no selector, expected <contract>:<selector>[,<selector>]`,
78
+ };
79
+ }
80
+ const contract = entry.substring(0, colonIndex).trim().toLowerCase();
81
+ if (!isAddress(contract)) {
82
+ return {status: 'invalid', details: `"${contract}" is not an address`};
83
+ }
84
+ const selectors = entry
85
+ .substring(colonIndex + 1)
86
+ .split(',')
87
+ .map((v) => v.trim().toLowerCase())
88
+ .filter((v) => v !== '');
89
+ if (selectors.length === 0) {
90
+ return {
91
+ status: 'invalid',
92
+ details: `contract ${contract} has no selector`,
93
+ };
94
+ }
95
+ for (const selector of selectors) {
96
+ if (!SELECTOR_REGEX.test(selector)) {
97
+ return {
98
+ status: 'invalid',
99
+ details: `"${selector}" is not a 4 byte selector`,
100
+ };
101
+ }
102
+ }
103
+ const existing = allowlist.get(contract);
104
+ if (existing) {
105
+ for (const selector of selectors) {
106
+ existing.add(selector);
107
+ }
108
+ } else {
109
+ allowlist.set(contract, new Set(selectors));
110
+ }
111
+ }
112
+
113
+ if (allowlist.size === 0) {
114
+ return {status: 'not-configured'};
115
+ }
116
+ return {status: 'ok', allowlist};
117
+ }
118
+
119
+ export function selectorOf(data: Hex): string | null {
120
+ // '0x' + 8 hex chars
121
+ if (data.length < 10) {
122
+ return null;
123
+ }
124
+ return data.substring(0, 10).toLowerCase();
125
+ }
126
+
127
+ export function isCallAllowed(
128
+ allowlist: CallAllowlist,
129
+ to: Address,
130
+ data: Hex,
131
+ ): boolean {
132
+ const selectors = allowlist.get(to.toLowerCase());
133
+ if (!selectors) {
134
+ return false;
135
+ }
136
+ const selector = selectorOf(data);
137
+ if (selector === null) {
138
+ // a call with no selector is a plain transfer, which /api/claim does
139
+ return false;
140
+ }
141
+ return selectors.has(selector);
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // budget
146
+ // ---------------------------------------------------------------------------
147
+
148
+ export type CallLimits = {
149
+ // ceiling on value + gasLimit * feePerGas for one call
150
+ totalSpend: bigint;
151
+ // ceiling on the value attached to the call
152
+ maxValue: bigint;
153
+ // absolute gas rail
154
+ maxGas: bigint;
155
+ };
156
+
157
+ export type CallLimitsLookup =
158
+ | {status: 'ok'; limits: CallLimits}
159
+ | {status: 'invalid'; details: string};
160
+
161
+ /**
162
+ * Defaults make an arbitrary call cost the faucet exactly what the claim it
163
+ * replaces would have cost: `amount` plus the gas of a plain transfer. So
164
+ * turning the feature on does not change the worst case spend per request.
165
+ *
166
+ * `feePerGas` must be the SAME fee reading used to derive the gas limit and to
167
+ * send the transaction, otherwise a bare transfer (which lands exactly on the
168
+ * boundary) can fail on a fee tick.
169
+ */
170
+ export function getCallLimits(
171
+ env: Env,
172
+ chainConfig: ChainConfig,
173
+ feePerGas: bigint,
174
+ ): CallLimitsLookup {
175
+ const chainId = chainConfig.chainId;
176
+
177
+ const totalSpendEnv = getBigIntEnv(
178
+ env[`MAX_CALL_TOTAL_SPEND_${chainId}` as `MAX_CALL_TOTAL_SPEND_${string}`],
179
+ );
180
+ if (totalSpendEnv.status === 'invalid') {
181
+ return {
182
+ status: 'invalid',
183
+ details: `MAX_CALL_TOTAL_SPEND_${chainId} is not a wei amount`,
184
+ };
185
+ }
186
+ const maxValueEnv = getBigIntEnv(
187
+ env[`MAX_CALL_VALUE_${chainId}` as `MAX_CALL_VALUE_${string}`],
188
+ );
189
+ if (maxValueEnv.status === 'invalid') {
190
+ return {
191
+ status: 'invalid',
192
+ details: `MAX_CALL_VALUE_${chainId} is not a wei amount`,
193
+ };
194
+ }
195
+ const maxGasEnv = getBigIntEnv(env.MAX_CALL_GAS);
196
+ if (maxGasEnv.status === 'invalid') {
197
+ return {status: 'invalid', details: `MAX_CALL_GAS is not a number`};
198
+ }
199
+ if (maxGasEnv.status === 'ok' && maxGasEnv.value === 0n) {
200
+ return {
201
+ status: 'invalid',
202
+ details: `MAX_CALL_GAS must be greater than zero`,
203
+ };
204
+ }
205
+
206
+ return {
207
+ status: 'ok',
208
+ limits: {
209
+ totalSpend:
210
+ totalSpendEnv.status === 'ok'
211
+ ? totalSpendEnv.value
212
+ : chainConfig.amount + SIMPLE_TRANSFER_GAS * feePerGas,
213
+ maxValue:
214
+ maxValueEnv.status === 'ok' ? maxValueEnv.value : chainConfig.amount,
215
+ maxGas:
216
+ maxGasEnv.status === 'ok' ? maxGasEnv.value : DEFAULT_MAX_CALL_GAS,
217
+ },
218
+ };
219
+ }
220
+
221
+ export type GasPlan =
222
+ | {status: 'ok'; gasLimit: bigint; ceiling: bigint}
223
+ | {status: 'does-not-fit'; details: string};
224
+
225
+ /**
226
+ * Turns a wei budget into a gas limit, which is the only thing the evm can
227
+ * actually be told.
228
+ *
229
+ * The `gasLimit < estimated` refusal is not a nicety: an out of gas revert
230
+ * consumes the WHOLE gas limit, so sending a call that cannot fit does not
231
+ * save the budget, it guarantees spending it for nothing.
232
+ */
233
+ export function planGas(params: {
234
+ limits: CallLimits;
235
+ value: bigint;
236
+ estimated: bigint;
237
+ feePerGas: bigint;
238
+ }): GasPlan {
239
+ const {limits, value, estimated, feePerGas} = params;
240
+
241
+ const budgetForGas = limits.totalSpend - value;
242
+ if (budgetForGas <= 0n) {
243
+ return {
244
+ status: 'does-not-fit',
245
+ details: `the value alone (${value} wei) uses the whole ${limits.totalSpend} wei budget, leaving nothing for gas`,
246
+ };
247
+ }
248
+
249
+ // a chain reporting a zero fee cannot bound gas by budget, the rail does it
250
+ const budgetRail = feePerGas > 0n ? budgetForGas / feePerGas : limits.maxGas;
251
+ const bufferRail = (estimated * GAS_BUFFER_PERCENT) / 100n;
252
+
253
+ let gasLimit = limits.maxGas;
254
+ if (budgetRail < gasLimit) {
255
+ gasLimit = budgetRail;
256
+ }
257
+ if (bufferRail < gasLimit) {
258
+ gasLimit = bufferRail;
259
+ }
260
+
261
+ if (gasLimit < estimated) {
262
+ return {
263
+ status: 'does-not-fit',
264
+ details: `this call needs ${estimated} gas but the faucet budget only allows ${gasLimit} at the current gas price`,
265
+ };
266
+ }
267
+
268
+ return {status: 'ok', gasLimit, ceiling: value + gasLimit * feePerGas};
269
+ }
270
+
271
+ // ---------------------------------------------------------------------------
272
+ // request validation
273
+ // ---------------------------------------------------------------------------
274
+
275
+ const DATA_REGEX = /^0x([0-9a-fA-F]{2})*$/;
276
+ const DECIMAL_REGEX = /^[0-9]+$/;
277
+
278
+ export type ParsedCall = {to: Address; data: Hex; value: bigint};
279
+
280
+ export function parseCallRequest(body: {
281
+ to?: unknown;
282
+ data?: unknown;
283
+ value?: unknown;
284
+ }): {status: 'ok'; call: ParsedCall} | {status: 'invalid'; error: string} {
285
+ const {to, data, value} = body;
286
+
287
+ if (typeof to !== 'string' || to === '') {
288
+ return {status: 'invalid', error: 'Missing to'};
289
+ }
290
+ if (!isAddress(to)) {
291
+ return {status: 'invalid', error: 'Invalid to address'};
292
+ }
293
+
294
+ const dataValue = data === undefined || data === null ? '0x' : data;
295
+ if (typeof dataValue !== 'string' || !DATA_REGEX.test(dataValue)) {
296
+ return {status: 'invalid', error: 'Invalid data, expected a hex string'};
297
+ }
298
+
299
+ let parsedValue = 0n;
300
+ if (value !== undefined && value !== null && value !== '') {
301
+ if (typeof value !== 'string' || !DECIMAL_REGEX.test(value)) {
302
+ return {
303
+ status: 'invalid',
304
+ error: 'Invalid value, expected a decimal wei string',
305
+ };
306
+ }
307
+ parsedValue = BigInt(value);
308
+ }
309
+
310
+ return {
311
+ status: 'ok',
312
+ call: {to: to as Address, data: dataValue as Hex, value: parsedValue},
313
+ };
314
+ }
315
+
316
+ // ---------------------------------------------------------------------------
317
+ // configuration validation, for boot time
318
+ // ---------------------------------------------------------------------------
319
+
320
+ export type ConfigIssues = {
321
+ errors: string[];
322
+ warnings: string[];
323
+ // one line per fact worth seeing in the first screen of the log
324
+ info: string[];
325
+ };
326
+
327
+ /**
328
+ * Called at boot by the node cli. Cloudflare Workers has no boot hook, so the
329
+ * same problems surface there as a 500 on the endpoint plus a console error.
330
+ */
331
+ export function checkArbitraryCallsConfig(env: Env): ConfigIssues {
332
+ const errors: string[] = [];
333
+ const warnings: string[] = [];
334
+ const info: string[] = [];
335
+
336
+ const modeLookup = getArbitraryCallsMode(env);
337
+ if (modeLookup.status === 'invalid') {
338
+ errors.push(
339
+ `ENABLE_ARBITRARY_CALLS must be 'off', 'allowlist' or 'unrestricted', got "${env.ENABLE_ARBITRARY_CALLS}"`,
340
+ );
341
+ return {errors, warnings, info};
342
+ }
343
+ const mode = modeLookup.mode;
344
+ if (mode === 'off') {
345
+ return {errors, warnings, info};
346
+ }
347
+
348
+ const chainIds: number[] = [];
349
+ for (const key of Object.keys(env)) {
350
+ if (key.startsWith('CHAIN_')) {
351
+ // strict, so CHAIN_1_TEST does not register itself as chain 1
352
+ const chainId = parseChainId(key.substring('CHAIN_'.length));
353
+ if (chainId !== null) {
354
+ chainIds.push(chainId);
355
+ }
356
+ }
357
+ }
358
+
359
+ if (mode === 'allowlist') {
360
+ for (const chainId of chainIds) {
361
+ const lookup = getCallAllowlist(env, chainId);
362
+ if (lookup.status === 'not-configured') {
363
+ errors.push(
364
+ `ENABLE_ARBITRARY_CALLS=allowlist but CALL_ALLOWLIST_${chainId} is not set: every call on chain ${chainId} would be refused`,
365
+ );
366
+ } else if (lookup.status === 'invalid') {
367
+ errors.push(`CALL_ALLOWLIST_${chainId} is invalid: ${lookup.details}`);
368
+ }
369
+ }
370
+ }
371
+
372
+ // One warning per distinct fact, so that the dangerous combination reads as
373
+ // one loud line rather than three overlapping ones.
374
+ const captchaOff = env.DISABLE_CAPTCHA === 'true';
375
+ if (mode === 'unrestricted' && captchaOff) {
376
+ warnings.push(
377
+ `arbitrary calls are UNRESTRICTED and captcha is DISABLED: anyone who can reach this server can make the faucet key call any contract with any calldata, with no rate limit. Never do this outside localhost. That key must hold no ERC20, hold no role, and have granted no approval, now or ever.`,
378
+ );
379
+ } else if (mode === 'unrestricted') {
380
+ warnings.push(
381
+ `arbitrary calls are UNRESTRICTED: anyone passing the captcha can make the faucet key call any contract with any calldata. That key must hold no ERC20, hold no role, and have granted no approval, now or ever.`,
382
+ );
383
+ } else if (captchaOff) {
384
+ warnings.push(
385
+ `captcha is disabled, so /api/execute applies NO rate limit at all (the ip cooldown is the only one it has)`,
386
+ );
387
+ }
388
+
389
+ // The posture in one screen, so a dangerous configuration is impossible to
390
+ // miss in the first lines of the log.
391
+ info.push(
392
+ `arbitrary calls: ${mode}, captcha: ${
393
+ captchaOff ? 'DISABLED' : 'enabled'
394
+ }, rate limit: ${captchaOff ? 'NONE' : 'ip only'}`,
395
+ );
396
+ // the address whose authority is being lent out, which is the thing an
397
+ // operator most needs to recognise in the log
398
+ try {
399
+ const account = privateKeyToAccount(env.FAUCET_PRIVATE_KEY as Hex);
400
+ info.push(` calls are signed by: ${account.address}`);
401
+ } catch (err) {
402
+ info.push(` calls are signed by: <FAUCET_PRIVATE_KEY missing or invalid>`);
403
+ }
404
+ const maxGas = getBigIntEnv(env.MAX_CALL_GAS);
405
+ info.push(
406
+ ` max gas per call: ${
407
+ maxGas.status === 'ok' ? maxGas.value : DEFAULT_MAX_CALL_GAS
408
+ }`,
409
+ );
410
+ for (const chainId of chainIds.sort((a, b) => a - b)) {
411
+ const totalSpend = getBigIntEnv(
412
+ env[
413
+ `MAX_CALL_TOTAL_SPEND_${chainId}` as `MAX_CALL_TOTAL_SPEND_${string}`
414
+ ],
415
+ );
416
+ const maxValue = getBigIntEnv(
417
+ env[`MAX_CALL_VALUE_${chainId}` as `MAX_CALL_VALUE_${string}`],
418
+ );
419
+ // the default is not a constant: it tracks the gas price, so that a call
420
+ // can never cost more than the claim it replaces
421
+ info.push(
422
+ ` chain ${chainId}: spend at most ${
423
+ totalSpend.status === 'ok'
424
+ ? `${totalSpend.value} wei`
425
+ : `amount + ${SIMPLE_TRANSFER_GAS} * gas price (default, varies)`
426
+ } per call, of which at most ${
427
+ maxValue.status === 'ok' ? `${maxValue.value} wei` : 'amount (default)'
428
+ } as value${
429
+ mode === 'allowlist' ? `, ${describeAllowlist(env, chainId)}` : ''
430
+ }`,
431
+ );
432
+ }
433
+
434
+ return {errors, warnings, info};
435
+ }
436
+
437
+ function describeAllowlist(env: Env, chainId: number): string {
438
+ const lookup = getCallAllowlist(env, chainId);
439
+ if (lookup.status !== 'ok') {
440
+ return 'no allow-list';
441
+ }
442
+ let selectors = 0;
443
+ for (const set of lookup.allowlist.values()) {
444
+ selectors += set.size;
445
+ }
446
+ return `${selectors} selector(s) on ${lookup.allowlist.size} contract(s)`;
447
+ }
package/src/chains.ts CHANGED
@@ -8,6 +8,32 @@ export type ChainConfig = {
8
8
  rpcUrl: string;
9
9
  };
10
10
 
11
+ /**
12
+ * A chain id, from a url segment, a json body or a CHAIN_<id> variable name.
13
+ *
14
+ * Strict for the same reason the limits are: parseInt partial parses, so
15
+ * '31337x' used to resolve to chain 31337, and a CHAIN_1_TEST variable used to
16
+ * register itself as chain 1. Numbers are accepted as well as strings, because
17
+ * a json body may carry either.
18
+ */
19
+ export function parseChainId(value: unknown): number | null {
20
+ if (typeof value === 'number') {
21
+ return Number.isSafeInteger(value) && value > 0 ? value : null;
22
+ }
23
+ if (typeof value !== 'string') {
24
+ return null;
25
+ }
26
+ const trimmed = value.trim();
27
+ if (!/^[0-9]+$/.test(trimmed)) {
28
+ return null;
29
+ }
30
+ const parsed = Number(trimmed);
31
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) {
32
+ return null;
33
+ }
34
+ return parsed;
35
+ }
36
+
11
37
  export type ChainConfigLookup =
12
38
  | {status: 'ok'; config: ChainConfig}
13
39
  | {status: 'not-configured'}
@@ -25,7 +51,22 @@ export function getChainConfig(env: Env, chainId: number): ChainConfigLookup {
25
51
  if (!value) {
26
52
  return {status: 'not-configured'};
27
53
  }
54
+ const parsed = parseChainEntry(value);
55
+ if (parsed.status !== 'ok') {
56
+ return parsed;
57
+ }
58
+ return {status: 'ok', config: {chainId, ...parsed.entry}};
59
+ }
28
60
 
61
+ export type ChainEntry = {amount: bigint; rpcUrl: string};
62
+
63
+ /**
64
+ * Parses the `<amount_in_wei>:<rpc_endpoint>` value shared by CHAIN_<id> and
65
+ * CHAIN_FROM_NODE.
66
+ */
67
+ export function parseChainEntry(
68
+ value: string,
69
+ ): {status: 'ok'; entry: ChainEntry} | {status: 'invalid'; details: string} {
29
70
  const colonIndex = value.indexOf(':');
30
71
  if (colonIndex === -1) {
31
72
  return {
@@ -55,7 +96,129 @@ export function getChainConfig(env: Env, chainId: number): ChainConfigLookup {
55
96
  return {status: 'invalid', details: `amount must be greater than zero`};
56
97
  }
57
98
 
58
- return {status: 'ok', config: {chainId, amount, rpcUrl}};
99
+ return {status: 'ok', entry: {amount, rpcUrl}};
100
+ }
101
+
102
+ /**
103
+ * CHAIN_FROM_NODE=<amount_in_wei>:<rpc_endpoint>: a chain whose id is whatever
104
+ * the node at that endpoint reports, for a local dev chain whose id is chosen
105
+ * when it starts. See docs/specs/follow-the-dev-chain.md.
106
+ */
107
+ export function getFollowedChainEntry(
108
+ env: Env,
109
+ ):
110
+ | {status: 'ok'; entry: ChainEntry}
111
+ | {status: 'not-configured'}
112
+ | {status: 'invalid'; details: string} {
113
+ const value = env.CHAIN_FROM_NODE;
114
+ if (value === undefined || value.trim() === '') {
115
+ return {status: 'not-configured'};
116
+ }
117
+ return parseChainEntry(value);
118
+ }
119
+
120
+ // A local node answers in milliseconds; failing fast keeps a request for an id
121
+ // the faucet does not serve from hanging on a node that is down.
122
+ const FOLLOW_TIMEOUT_MS = 5000;
123
+
124
+ /**
125
+ * Asks the followed node for its chain id. No cache: the node can be restarted
126
+ * under a new id at any time, and a stale id would send a claim to a chain
127
+ * that is not the one the caller named.
128
+ */
129
+ export async function readFollowedChainId(entry: ChainEntry): Promise<number> {
130
+ return getFollowClient(entry.rpcUrl).getChainId();
131
+ }
132
+
133
+ function getFollowClient(rpcUrl: string) {
134
+ return createPublicClient({
135
+ transport: http(rpcUrl, {retryCount: 0, timeout: FOLLOW_TIMEOUT_MS}),
136
+ });
137
+ }
138
+
139
+ export type ResolvedChain = {
140
+ config: ChainConfig;
141
+ // true when the chain is served through CHAIN_FROM_NODE: its state is then
142
+ // keyed by chain identity, see getChainStateKey
143
+ followed: boolean;
144
+ };
145
+
146
+ export type ChainLookup =
147
+ | {status: 'ok'; chain: ResolvedChain}
148
+ | {status: 'not-configured'}
149
+ | {status: 'invalid'; details: string}
150
+ | {status: 'unreachable'; details: string};
151
+
152
+ /**
153
+ * The chain a request names: a CHAIN_<id> line first (explicit configuration
154
+ * beats discovery), else the followed node when it reports that id.
155
+ */
156
+ export async function resolveChain(
157
+ env: Env,
158
+ chainId: number,
159
+ ): Promise<ChainLookup> {
160
+ const configured = getChainConfig(env, chainId);
161
+ if (configured.status === 'ok') {
162
+ return {
163
+ status: 'ok',
164
+ chain: {config: configured.config, followed: false},
165
+ };
166
+ }
167
+ if (configured.status === 'invalid') {
168
+ return configured;
169
+ }
170
+
171
+ const followed = getFollowedChainEntry(env);
172
+ if (followed.status === 'not-configured') {
173
+ return {status: 'not-configured'};
174
+ }
175
+ if (followed.status === 'invalid') {
176
+ return {
177
+ status: 'invalid',
178
+ details: `CHAIN_FROM_NODE: ${followed.details}`,
179
+ };
180
+ }
181
+
182
+ let nodeChainId: number;
183
+ try {
184
+ nodeChainId = await readFollowedChainId(followed.entry);
185
+ } catch (err) {
186
+ return {
187
+ status: 'unreachable',
188
+ details: err instanceof Error ? err.message : String(err),
189
+ };
190
+ }
191
+ if (nodeChainId !== chainId) {
192
+ return {status: 'not-configured'};
193
+ }
194
+ return {
195
+ status: 'ok',
196
+ chain: {config: {chainId, ...followed.entry}, followed: true},
197
+ };
198
+ }
199
+
200
+ /**
201
+ * The key a chain's rows (Claims, ChainLocks) are stored under.
202
+ *
203
+ * A CHAIN_<id> entry keeps the bare id, as it always has. A followed chain is
204
+ * keyed by its identity, the id AND block 0's hash: a dev chain can be reset
205
+ * on the same id, and its rate limits and above all its last nonce must not
206
+ * carry over (a nonce from the old chain would be one the new chain never
207
+ * reaches). Read on EVERY request, before the lock and before the nonce: a
208
+ * cached hash would still be the old chain's on the first claim after a reset.
209
+ */
210
+ export async function getChainStateKey(chain: ResolvedChain): Promise<string> {
211
+ const id = String(chain.config.chainId);
212
+ if (!chain.followed) {
213
+ return id;
214
+ }
215
+ const genesis = await getFollowClient(chain.config.rpcUrl).getBlock({
216
+ blockNumber: 0n,
217
+ });
218
+ if (!genesis.hash) {
219
+ throw new Error('the node returned no hash for block 0');
220
+ }
221
+ return `${id}:${genesis.hash.toLowerCase()}`;
59
222
  }
60
223
 
61
224
  export function getViemChain(config: ChainConfig): Chain {
@@ -85,6 +248,45 @@ export function getWalletClient(
85
248
  });
86
249
  }
87
250
 
251
+ /**
252
+ * One fee reading, used for the whole of a call: the budget default, the gas
253
+ * limit division and the transaction itself.
254
+ *
255
+ * Reading fees twice would let a bare transfer (whose gas limit lands exactly
256
+ * on the budget boundary) fail on a fee tick, so callers must thread a single
257
+ * FeeParams through rather than re-estimating.
258
+ */
259
+ export type FeeParams =
260
+ | {type: 'eip1559'; maxFeePerGas: bigint; maxPriorityFeePerGas?: bigint}
261
+ | {type: 'legacy'; gasPrice: bigint};
262
+
263
+ export async function getFeeParams(
264
+ publicClient: ReturnType<typeof getPublicClient>,
265
+ ): Promise<FeeParams> {
266
+ try {
267
+ const fees = await publicClient.estimateFeesPerGas();
268
+ if (fees.maxFeePerGas) {
269
+ return {
270
+ type: 'eip1559',
271
+ maxFeePerGas: fees.maxFeePerGas,
272
+ maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
273
+ };
274
+ }
275
+ } catch (err) {
276
+ // chain without eip-1559 support, fall through to gas price
277
+ }
278
+ const gasPrice = await publicClient.getGasPrice();
279
+ return {type: 'legacy', gasPrice};
280
+ }
281
+
282
+ /**
283
+ * The per gas price a spending ceiling has to be computed against: the most
284
+ * the chain can charge for one unit of gas on this transaction.
285
+ */
286
+ export function feePerGas(fees: FeeParams): bigint {
287
+ return fees.type === 'eip1559' ? fees.maxFeePerGas : fees.gasPrice;
288
+ }
289
+
88
290
  /**
89
291
  * Worst case cost of a plain value transfer, used to check the faucet can still
90
292
  * pay for the transaction it is about to broadcast.