faucet-server-app 0.1.0 → 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.
- package/dist/esm/api/index.d.ts +17 -1
- package/dist/esm/api/index.d.ts.map +1 -1
- package/dist/esm/api/index.js +350 -34
- package/dist/esm/api/index.js.map +1 -1
- package/dist/esm/calls.d.ts +107 -0
- package/dist/esm/calls.d.ts.map +1 -0
- package/dist/esm/calls.js +304 -0
- package/dist/esm/calls.js.map +1 -0
- package/dist/esm/chains.d.ts +581 -550
- package/dist/esm/chains.d.ts.map +1 -1
- package/dist/esm/chains.js +49 -0
- package/dist/esm/chains.js.map +1 -1
- package/dist/esm/config.d.ts +12 -0
- package/dist/esm/config.d.ts.map +1 -0
- package/dist/esm/config.js +28 -0
- package/dist/esm/config.js.map +1 -0
- package/dist/esm/env.d.ts +45 -1
- package/dist/esm/env.d.ts.map +1 -1
- package/dist/esm/env.js +55 -7
- package/dist/esm/env.js.map +1 -1
- package/dist/esm/index.d.ts +39 -0
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +7 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/setup.d.ts.map +1 -1
- package/dist/esm/setup.js +22 -0
- package/dist/esm/setup.js.map +1 -1
- package/dist/esm/storage/RemoteSQLStorage.d.ts.map +1 -1
- package/dist/esm/storage/RemoteSQLStorage.js +11 -4
- package/dist/esm/storage/RemoteSQLStorage.js.map +1 -1
- package/package.json +1 -1
- package/src/api/index.ts +470 -44
- package/src/calls.ts +447 -0
- package/src/chains.ts +65 -0
- package/src/config.ts +33 -0
- package/src/env.ts +82 -9
- package/src/index.ts +25 -2
- package/src/setup.ts +24 -0
- package/src/storage/RemoteSQLStorage.ts +11 -4
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'}
|
|
@@ -85,6 +111,45 @@ export function getWalletClient(
|
|
|
85
111
|
});
|
|
86
112
|
}
|
|
87
113
|
|
|
114
|
+
/**
|
|
115
|
+
* One fee reading, used for the whole of a call: the budget default, the gas
|
|
116
|
+
* limit division and the transaction itself.
|
|
117
|
+
*
|
|
118
|
+
* Reading fees twice would let a bare transfer (whose gas limit lands exactly
|
|
119
|
+
* on the budget boundary) fail on a fee tick, so callers must thread a single
|
|
120
|
+
* FeeParams through rather than re-estimating.
|
|
121
|
+
*/
|
|
122
|
+
export type FeeParams =
|
|
123
|
+
| {type: 'eip1559'; maxFeePerGas: bigint; maxPriorityFeePerGas?: bigint}
|
|
124
|
+
| {type: 'legacy'; gasPrice: bigint};
|
|
125
|
+
|
|
126
|
+
export async function getFeeParams(
|
|
127
|
+
publicClient: ReturnType<typeof getPublicClient>,
|
|
128
|
+
): Promise<FeeParams> {
|
|
129
|
+
try {
|
|
130
|
+
const fees = await publicClient.estimateFeesPerGas();
|
|
131
|
+
if (fees.maxFeePerGas) {
|
|
132
|
+
return {
|
|
133
|
+
type: 'eip1559',
|
|
134
|
+
maxFeePerGas: fees.maxFeePerGas,
|
|
135
|
+
maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
} catch (err) {
|
|
139
|
+
// chain without eip-1559 support, fall through to gas price
|
|
140
|
+
}
|
|
141
|
+
const gasPrice = await publicClient.getGasPrice();
|
|
142
|
+
return {type: 'legacy', gasPrice};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The per gas price a spending ceiling has to be computed against: the most
|
|
147
|
+
* the chain can charge for one unit of gas on this transaction.
|
|
148
|
+
*/
|
|
149
|
+
export function feePerGas(fees: FeeParams): bigint {
|
|
150
|
+
return fees.type === 'eip1559' ? fees.maxFeePerGas : fees.gasPrice;
|
|
151
|
+
}
|
|
152
|
+
|
|
88
153
|
/**
|
|
89
154
|
* Worst case cost of a plain value transfer, used to check the faucet can still
|
|
90
155
|
* pay for the transaction it is about to broadcast.
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import {getBigIntEnv, getCooldowns, type Env} from './env.js';
|
|
2
|
+
import {checkArbitraryCallsConfig, type ConfigIssues} from './calls.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Every configuration check the server can make without touching the network,
|
|
6
|
+
* so a typo in a spending limit stops the process instead of surfacing as a
|
|
7
|
+
* failed claim later.
|
|
8
|
+
*
|
|
9
|
+
* Cloudflare Workers has no boot hook, so there the same problems surface as a
|
|
10
|
+
* 500 plus a console error on the first request that reads them.
|
|
11
|
+
*/
|
|
12
|
+
export function checkConfig(env: Env): ConfigIssues {
|
|
13
|
+
const issues = checkArbitraryCallsConfig(env);
|
|
14
|
+
|
|
15
|
+
// A malformed ceiling used to throw out of BigInt() on every claim, which
|
|
16
|
+
// reached the error handler as an unhandled exception: a 500 with a stack
|
|
17
|
+
// instead of a clear answer, on a faucet that had started up happily.
|
|
18
|
+
const maxRecipientBalance = getBigIntEnv(env.MAX_RECIPIENT_BALANCE);
|
|
19
|
+
if (maxRecipientBalance.status === 'invalid') {
|
|
20
|
+
issues.errors.push(
|
|
21
|
+
`MAX_RECIPIENT_BALANCE must be a wei amount, got "${env.MAX_RECIPIENT_BALANCE}"`,
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// These used to go through parseInt, which partial parses: '1h' meant one
|
|
26
|
+
// second, so a plausible looking typo removed the cooldown almost entirely.
|
|
27
|
+
const cooldowns = getCooldowns(env);
|
|
28
|
+
if (cooldowns.status === 'invalid') {
|
|
29
|
+
issues.errors.push(cooldowns.details);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return issues;
|
|
33
|
+
}
|
package/src/env.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
export type Env = {
|
|
2
|
+
// 'true' includes the cause and stack of an unhandled error in the response.
|
|
3
|
+
// Development only, and set as a flag rather than an env entry: the node cli
|
|
4
|
+
// has --dev, the worker dev script passes --var DEV:true, so it cannot follow
|
|
5
|
+
// you into a deployment.
|
|
2
6
|
DEV?: string;
|
|
3
7
|
PROSOPO_SITE_PRIVATE_KEY?: string;
|
|
4
8
|
FAUCET_PRIVATE_KEY?: string;
|
|
@@ -17,8 +21,19 @@ export type Env = {
|
|
|
17
21
|
// Refuse to top up a recipient already holding this much (in wei).
|
|
18
22
|
// Defaults to 10x the chain amount, set to '0' to disable the check.
|
|
19
23
|
MAX_RECIPIENT_BALANCE?: string;
|
|
24
|
+
// 'off' (default), 'allowlist' or 'unrestricted'. Anything but 'off' lets
|
|
25
|
+
// callers choose what the faucet key signs, see docs/specs/arbitrary-calls.md
|
|
26
|
+
ENABLE_ARBITRARY_CALLS?: string;
|
|
27
|
+
// Absolute gas limit granted to an arbitrary call, whatever the budget says.
|
|
28
|
+
MAX_CALL_GAS?: string;
|
|
20
29
|
// Dynamic env variables: CHAIN_<CHAIN_ID>=<amount>:<rpc_endpoint> for chain config
|
|
21
30
|
[key: `CHAIN_${string}`]: string | undefined;
|
|
31
|
+
// CALL_ALLOWLIST_<CHAIN_ID>=<contract>:<selector>,<selector>;<contract>:...
|
|
32
|
+
[key: `CALL_ALLOWLIST_${string}`]: string | undefined;
|
|
33
|
+
// MAX_CALL_TOTAL_SPEND_<CHAIN_ID>=<wei>, ceiling on value + gas for one call
|
|
34
|
+
[key: `MAX_CALL_TOTAL_SPEND_${string}`]: string | undefined;
|
|
35
|
+
// MAX_CALL_VALUE_<CHAIN_ID>=<wei>, ceiling on the value attached to a call
|
|
36
|
+
[key: `MAX_CALL_VALUE_${string}`]: string | undefined;
|
|
22
37
|
};
|
|
23
38
|
|
|
24
39
|
export const DEFAULT_CORS_ORIGINS = ['https://jolly-roger.eth.limo'];
|
|
@@ -36,18 +51,76 @@ export const CLAIM_RETENTION_SECONDS = 30 * 24 * 60 * 60;
|
|
|
36
51
|
// how long a claim may hold the per chain send lock
|
|
37
52
|
export const CHAIN_LOCK_TIMEOUT_SECONDS = 30;
|
|
38
53
|
|
|
39
|
-
|
|
54
|
+
/**
|
|
55
|
+
* Parses a non-negative integer, refusing anything else.
|
|
56
|
+
*
|
|
57
|
+
* Deliberately not parseInt: that partial parses, so CLAIM_COOLDOWN_SECONDS=1h
|
|
58
|
+
* used to mean ONE SECOND rather than the 86400 default. A typo in a limit has
|
|
59
|
+
* to be refused, not silently turned into a much weaker limit.
|
|
60
|
+
*/
|
|
61
|
+
export function getIntEnv(
|
|
40
62
|
value: string | undefined,
|
|
41
|
-
|
|
42
|
-
)
|
|
43
|
-
|
|
44
|
-
return defaultValue;
|
|
63
|
+
): {status: 'unset'} | {status: 'ok'; value: number} | {status: 'invalid'} {
|
|
64
|
+
if (value === undefined || value.trim() === '') {
|
|
65
|
+
return {status: 'unset'};
|
|
45
66
|
}
|
|
46
|
-
const
|
|
47
|
-
if (
|
|
48
|
-
return
|
|
67
|
+
const trimmed = value.trim();
|
|
68
|
+
if (!/^[0-9]+$/.test(trimmed)) {
|
|
69
|
+
return {status: 'invalid'};
|
|
49
70
|
}
|
|
50
|
-
|
|
71
|
+
const parsed = Number(trimmed);
|
|
72
|
+
if (!Number.isSafeInteger(parsed)) {
|
|
73
|
+
return {status: 'invalid'};
|
|
74
|
+
}
|
|
75
|
+
return {status: 'ok', value: parsed};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export type Cooldowns =
|
|
79
|
+
| {status: 'ok'; addressCooldown: number; ipCooldown: number}
|
|
80
|
+
| {status: 'invalid'; details: string};
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The two rate limiting windows. The ip window defaults to the address one, so
|
|
84
|
+
* they are resolved together.
|
|
85
|
+
*/
|
|
86
|
+
export function getCooldowns(env: Env): Cooldowns {
|
|
87
|
+
const claim = getIntEnv(env.CLAIM_COOLDOWN_SECONDS);
|
|
88
|
+
if (claim.status === 'invalid') {
|
|
89
|
+
return {
|
|
90
|
+
status: 'invalid',
|
|
91
|
+
details: `CLAIM_COOLDOWN_SECONDS must be a whole number of seconds, got "${env.CLAIM_COOLDOWN_SECONDS}"`,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
const addressCooldown =
|
|
95
|
+
claim.status === 'ok' ? claim.value : DEFAULT_CLAIM_COOLDOWN_SECONDS;
|
|
96
|
+
|
|
97
|
+
const ip = getIntEnv(env.IP_COOLDOWN_SECONDS);
|
|
98
|
+
if (ip.status === 'invalid') {
|
|
99
|
+
return {
|
|
100
|
+
status: 'invalid',
|
|
101
|
+
details: `IP_COOLDOWN_SECONDS must be a whole number of seconds, got "${env.IP_COOLDOWN_SECONDS}"`,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
const ipCooldown = ip.status === 'ok' ? ip.value : addressCooldown;
|
|
105
|
+
|
|
106
|
+
return {status: 'ok', addressCooldown, ipCooldown};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Parses a wei amount, refusing a malformed value instead of falling back:
|
|
111
|
+
* every caller here is a spending limit and a typo must not silently widen it.
|
|
112
|
+
*/
|
|
113
|
+
export function getBigIntEnv(
|
|
114
|
+
value: string | undefined,
|
|
115
|
+
): {status: 'unset'} | {status: 'ok'; value: bigint} | {status: 'invalid'} {
|
|
116
|
+
if (value === undefined || value.trim() === '') {
|
|
117
|
+
return {status: 'unset'};
|
|
118
|
+
}
|
|
119
|
+
const trimmed = value.trim();
|
|
120
|
+
if (!/^[0-9]+$/.test(trimmed)) {
|
|
121
|
+
return {status: 'invalid'};
|
|
122
|
+
}
|
|
123
|
+
return {status: 'ok', value: BigInt(trimmed)};
|
|
51
124
|
}
|
|
52
125
|
|
|
53
126
|
export function getCorsOrigins(env: Env): string[] | '*' {
|