faucet-server-app 0.0.5 → 0.1.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 +34 -15
- package/dist/esm/api/index.d.ts.map +1 -1
- package/dist/esm/api/index.js +247 -75
- package/dist/esm/api/index.js.map +1 -1
- package/dist/esm/captcha.d.ts +28 -0
- package/dist/esm/captcha.d.ts.map +1 -0
- package/dist/esm/captcha.js +58 -0
- package/dist/esm/captcha.js.map +1 -0
- package/dist/esm/chains.d.ts +17521 -0
- package/dist/esm/chains.d.ts.map +1 -0
- package/dist/esm/chains.js +88 -0
- package/dist/esm/chains.js.map +1 -0
- package/dist/esm/env.d.ts +12 -0
- package/dist/esm/env.d.ts.map +1 -1
- package/dist/esm/env.js +33 -1
- package/dist/esm/env.js.map +1 -1
- package/dist/esm/index.d.ts +97 -43
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +32 -14
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/schema/ts/db.sql.d.ts +1 -1
- package/dist/esm/schema/ts/db.sql.d.ts.map +1 -1
- package/dist/esm/schema/ts/db.sql.js +25 -4
- package/dist/esm/schema/ts/db.sql.js.map +1 -1
- package/dist/esm/setup.d.ts +2 -0
- package/dist/esm/setup.d.ts.map +1 -1
- package/dist/esm/setup.js +3 -7
- package/dist/esm/setup.js.map +1 -1
- package/dist/esm/storage/RemoteSQLStorage.d.ts +49 -0
- package/dist/esm/storage/RemoteSQLStorage.d.ts.map +1 -0
- package/dist/esm/storage/RemoteSQLStorage.js +151 -0
- package/dist/esm/storage/RemoteSQLStorage.js.map +1 -0
- package/package.json +1 -1
- package/src/api/index.ts +327 -106
- package/src/captcha.ts +92 -0
- package/src/chains.ts +110 -0
- package/src/env.ts +56 -0
- package/src/index.ts +35 -16
- package/src/schema/sql/db.sql +25 -4
- package/src/schema/ts/db.sql.ts +25 -4
- package/src/setup.ts +4 -11
- package/src/storage/RemoteSQLStorage.ts +245 -0
package/src/chains.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import {createPublicClient, createWalletClient, http, type Chain} from 'viem';
|
|
2
|
+
import type {PrivateKeyAccount} from 'viem/accounts';
|
|
3
|
+
import {Env} from './env.js';
|
|
4
|
+
|
|
5
|
+
export type ChainConfig = {
|
|
6
|
+
chainId: number;
|
|
7
|
+
amount: bigint;
|
|
8
|
+
rpcUrl: string;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export type ChainConfigLookup =
|
|
12
|
+
| {status: 'ok'; config: ChainConfig}
|
|
13
|
+
| {status: 'not-configured'}
|
|
14
|
+
| {status: 'invalid'; details: string};
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Chains are configured as CHAIN_<CHAIN_ID>=<amount_in_wei>:<rpc_endpoint>.
|
|
18
|
+
*
|
|
19
|
+
* The rpc endpoint is a SERVER side secret: it usually embeds an api key and is
|
|
20
|
+
* never returned to clients.
|
|
21
|
+
*/
|
|
22
|
+
export function getChainConfig(env: Env, chainId: number): ChainConfigLookup {
|
|
23
|
+
const key = `CHAIN_${chainId}` as `CHAIN_${string}`;
|
|
24
|
+
const value = env[key];
|
|
25
|
+
if (!value) {
|
|
26
|
+
return {status: 'not-configured'};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const colonIndex = value.indexOf(':');
|
|
30
|
+
if (colonIndex === -1) {
|
|
31
|
+
return {
|
|
32
|
+
status: 'invalid',
|
|
33
|
+
details: `expected <amount>:<rpc_endpoint>, got no separator`,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
const amountStr = value.substring(0, colonIndex).trim();
|
|
37
|
+
const rpcUrl = value.substring(colonIndex + 1).trim();
|
|
38
|
+
if (!amountStr || !rpcUrl) {
|
|
39
|
+
return {
|
|
40
|
+
status: 'invalid',
|
|
41
|
+
details: `expected <amount>:<rpc_endpoint>`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
let amount: bigint;
|
|
46
|
+
try {
|
|
47
|
+
amount = BigInt(amountStr);
|
|
48
|
+
} catch (err) {
|
|
49
|
+
return {
|
|
50
|
+
status: 'invalid',
|
|
51
|
+
details: `amount "${amountStr}" is not a number`,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
if (amount <= 0n) {
|
|
55
|
+
return {status: 'invalid', details: `amount must be greater than zero`};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return {status: 'ok', config: {chainId, amount, rpcUrl}};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function getViemChain(config: ChainConfig): Chain {
|
|
62
|
+
return {
|
|
63
|
+
id: config.chainId,
|
|
64
|
+
name: `Chain ${config.chainId}`,
|
|
65
|
+
nativeCurrency: {name: 'ETH', symbol: 'ETH', decimals: 18},
|
|
66
|
+
rpcUrls: {default: {http: [config.rpcUrl]}},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function getPublicClient(config: ChainConfig) {
|
|
71
|
+
return createPublicClient({
|
|
72
|
+
chain: getViemChain(config),
|
|
73
|
+
transport: http(config.rpcUrl),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function getWalletClient(
|
|
78
|
+
config: ChainConfig,
|
|
79
|
+
account: PrivateKeyAccount,
|
|
80
|
+
) {
|
|
81
|
+
return createWalletClient({
|
|
82
|
+
account,
|
|
83
|
+
chain: getViemChain(config),
|
|
84
|
+
transport: http(config.rpcUrl),
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Worst case cost of a plain value transfer, used to check the faucet can still
|
|
90
|
+
* pay for the transaction it is about to broadcast.
|
|
91
|
+
*/
|
|
92
|
+
export async function estimateTransferCost(
|
|
93
|
+
publicClient: ReturnType<typeof getPublicClient>,
|
|
94
|
+
): Promise<bigint> {
|
|
95
|
+
const gasLimit = 21000n;
|
|
96
|
+
try {
|
|
97
|
+
const fees = await publicClient.estimateFeesPerGas();
|
|
98
|
+
if (fees.maxFeePerGas) {
|
|
99
|
+
return gasLimit * fees.maxFeePerGas;
|
|
100
|
+
}
|
|
101
|
+
} catch (err) {
|
|
102
|
+
// chain without eip-1559 support, fall through to gas price
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
const gasPrice = await publicClient.getGasPrice();
|
|
106
|
+
return gasLimit * gasPrice;
|
|
107
|
+
} catch (err) {
|
|
108
|
+
return 0n;
|
|
109
|
+
}
|
|
110
|
+
}
|
package/src/env.ts
CHANGED
|
@@ -4,6 +4,62 @@ export type Env = {
|
|
|
4
4
|
FAUCET_PRIVATE_KEY?: string;
|
|
5
5
|
// Set to 'true' to disable captcha verification (useful for localhost development)
|
|
6
6
|
DISABLE_CAPTCHA?: string;
|
|
7
|
+
// Set to 'true' to keep dispensing when the captcha provider is unreachable.
|
|
8
|
+
// Default is to fail closed: an unreachable provider means no funds go out.
|
|
9
|
+
CAPTCHA_FAIL_OPEN?: string;
|
|
10
|
+
// Comma separated list of origins allowed to call the API cross-origin,
|
|
11
|
+
// or '*' to allow any. Defaults to DEFAULT_CORS_ORIGINS.
|
|
12
|
+
CORS_ORIGINS?: string;
|
|
13
|
+
// Cooldown in seconds between two claims for the same address (default: 1 day)
|
|
14
|
+
CLAIM_COOLDOWN_SECONDS?: string;
|
|
15
|
+
// Cooldown in seconds between two claims from the same ip (default: CLAIM_COOLDOWN_SECONDS)
|
|
16
|
+
IP_COOLDOWN_SECONDS?: string;
|
|
17
|
+
// Refuse to top up a recipient already holding this much (in wei).
|
|
18
|
+
// Defaults to 10x the chain amount, set to '0' to disable the check.
|
|
19
|
+
MAX_RECIPIENT_BALANCE?: string;
|
|
7
20
|
// Dynamic env variables: CHAIN_<CHAIN_ID>=<amount>:<rpc_endpoint> for chain config
|
|
8
21
|
[key: `CHAIN_${string}`]: string | undefined;
|
|
9
22
|
};
|
|
23
|
+
|
|
24
|
+
export const DEFAULT_CORS_ORIGINS = ['https://jolly-roger.eth.limo'];
|
|
25
|
+
|
|
26
|
+
// one day
|
|
27
|
+
export const DEFAULT_CLAIM_COOLDOWN_SECONDS = 24 * 60 * 60;
|
|
28
|
+
|
|
29
|
+
// how long a captcha token stays burnt before being garbage collected.
|
|
30
|
+
// Prosopo tokens are short lived, an hour is plenty to block replays.
|
|
31
|
+
export const USED_TOKEN_RETENTION_SECONDS = 60 * 60;
|
|
32
|
+
|
|
33
|
+
// how long claim history is kept around, past every plausible cooldown
|
|
34
|
+
export const CLAIM_RETENTION_SECONDS = 30 * 24 * 60 * 60;
|
|
35
|
+
|
|
36
|
+
// how long a claim may hold the per chain send lock
|
|
37
|
+
export const CHAIN_LOCK_TIMEOUT_SECONDS = 30;
|
|
38
|
+
|
|
39
|
+
export function getNumberEnv(
|
|
40
|
+
value: string | undefined,
|
|
41
|
+
defaultValue: number,
|
|
42
|
+
): number {
|
|
43
|
+
if (value === undefined || value === '') {
|
|
44
|
+
return defaultValue;
|
|
45
|
+
}
|
|
46
|
+
const parsed = parseInt(value, 10);
|
|
47
|
+
if (isNaN(parsed) || parsed < 0) {
|
|
48
|
+
return defaultValue;
|
|
49
|
+
}
|
|
50
|
+
return parsed;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function getCorsOrigins(env: Env): string[] | '*' {
|
|
54
|
+
const configured = env.CORS_ORIGINS;
|
|
55
|
+
if (configured === undefined || configured.trim() === '') {
|
|
56
|
+
return DEFAULT_CORS_ORIGINS;
|
|
57
|
+
}
|
|
58
|
+
if (configured.trim() === '*') {
|
|
59
|
+
return '*';
|
|
60
|
+
}
|
|
61
|
+
return configured
|
|
62
|
+
.split(',')
|
|
63
|
+
.map((v) => v.trim())
|
|
64
|
+
.filter((v) => v.length > 0);
|
|
65
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -3,26 +3,23 @@ import {cors} from 'hono/cors';
|
|
|
3
3
|
import {ServerOptions} from './types.js';
|
|
4
4
|
import {hc} from 'hono/client';
|
|
5
5
|
import {HTTPException} from 'hono/http-exception';
|
|
6
|
-
import {Env} from './env.js';
|
|
6
|
+
import {Env, getCorsOrigins} from './env.js';
|
|
7
7
|
import {getAPI} from './api/index.js';
|
|
8
|
+
import {RemoteSQL} from 'remote-sql';
|
|
9
|
+
import {RemoteSQLStorage} from './storage/RemoteSQLStorage.js';
|
|
8
10
|
|
|
9
11
|
export type {Env};
|
|
12
|
+
export {RemoteSQLStorage};
|
|
13
|
+
export {verifyProsopoCaptcha} from './captcha.js';
|
|
14
|
+
export type {CaptchaVerification} from './captcha.js';
|
|
15
|
+
export {DEFAULT_CORS_ORIGINS, DEFAULT_CLAIM_COOLDOWN_SECONDS} from './env.js';
|
|
10
16
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
'Upgrade-Insecure-Requests',
|
|
18
|
-
'Content-Type',
|
|
19
|
-
'SIGNATURE',
|
|
20
|
-
],
|
|
21
|
-
allowMethods: ['POST', 'GET', 'HEAD', 'OPTIONS'],
|
|
22
|
-
exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],
|
|
23
|
-
maxAge: 600,
|
|
24
|
-
credentials: true,
|
|
25
|
-
});
|
|
17
|
+
/**
|
|
18
|
+
* Creates the tables the faucet needs. Idempotent, safe to call on every boot.
|
|
19
|
+
*/
|
|
20
|
+
export async function setupDB(db: RemoteSQL): Promise<void> {
|
|
21
|
+
await new RemoteSQLStorage(db).setup();
|
|
22
|
+
}
|
|
26
23
|
|
|
27
24
|
export function createServer<CustomEnv extends Env>(
|
|
28
25
|
options: ServerOptions<CustomEnv>,
|
|
@@ -31,6 +28,28 @@ export function createServer<CustomEnv extends Env>(
|
|
|
31
28
|
|
|
32
29
|
const api = getAPI(options);
|
|
33
30
|
|
|
31
|
+
// The frontend is served from the same origin as the api, so this only
|
|
32
|
+
// controls which OTHER sites may drive the faucet from a browser.
|
|
33
|
+
const corsSetup = cors({
|
|
34
|
+
origin: (origin, c) => {
|
|
35
|
+
const allowed = getCorsOrigins(options.getEnv(c as any));
|
|
36
|
+
if (allowed === '*') {
|
|
37
|
+
return origin || '*';
|
|
38
|
+
}
|
|
39
|
+
return allowed.includes(origin) ? origin : null;
|
|
40
|
+
},
|
|
41
|
+
allowHeaders: [
|
|
42
|
+
'X-Custom-Header',
|
|
43
|
+
'Upgrade-Insecure-Requests',
|
|
44
|
+
'Content-Type',
|
|
45
|
+
'SIGNATURE',
|
|
46
|
+
],
|
|
47
|
+
allowMethods: ['POST', 'GET', 'HEAD', 'OPTIONS'],
|
|
48
|
+
exposeHeaders: ['Content-Length', 'X-Kuma-Revision', 'Retry-After'],
|
|
49
|
+
maxAge: 600,
|
|
50
|
+
credentials: true,
|
|
51
|
+
});
|
|
52
|
+
|
|
34
53
|
return app
|
|
35
54
|
.use('/api/*', corsSetup)
|
|
36
55
|
.route('/api/', api)
|
package/src/schema/sql/db.sql
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
|
-
CREATE TABLE IF NOT EXISTS
|
|
2
|
-
id
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
CREATE TABLE IF NOT EXISTS Claims (
|
|
2
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
chain_id TEXT NOT NULL,
|
|
4
|
+
address TEXT NOT NULL,
|
|
5
|
+
ip TEXT NOT NULL DEFAULT '',
|
|
6
|
+
amount TEXT NOT NULL,
|
|
7
|
+
tx_hash TEXT,
|
|
8
|
+
claimed_at INTEGER NOT NULL
|
|
5
9
|
);
|
|
10
|
+
|
|
11
|
+
CREATE INDEX IF NOT EXISTS idx_claims_address ON Claims (chain_id, address, claimed_at);
|
|
12
|
+
|
|
13
|
+
CREATE INDEX IF NOT EXISTS idx_claims_ip ON Claims (chain_id, ip, claimed_at);
|
|
14
|
+
|
|
15
|
+
CREATE TABLE IF NOT EXISTS ChainLocks (
|
|
16
|
+
chain_id TEXT PRIMARY KEY,
|
|
17
|
+
locked_until INTEGER NOT NULL DEFAULT 0,
|
|
18
|
+
last_nonce INTEGER
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
CREATE TABLE IF NOT EXISTS UsedTokens (
|
|
22
|
+
token_hash TEXT PRIMARY KEY,
|
|
23
|
+
used_at INTEGER NOT NULL
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
CREATE INDEX IF NOT EXISTS idx_used_tokens_used_at ON UsedTokens (used_at);
|
package/src/schema/ts/db.sql.ts
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
|
-
export default `CREATE TABLE IF NOT EXISTS
|
|
2
|
-
id
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
export default `CREATE TABLE IF NOT EXISTS Claims (
|
|
2
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
chain_id TEXT NOT NULL,
|
|
4
|
+
address TEXT NOT NULL,
|
|
5
|
+
ip TEXT NOT NULL DEFAULT '',
|
|
6
|
+
amount TEXT NOT NULL,
|
|
7
|
+
tx_hash TEXT,
|
|
8
|
+
claimed_at INTEGER NOT NULL
|
|
5
9
|
);
|
|
10
|
+
|
|
11
|
+
CREATE INDEX IF NOT EXISTS idx_claims_address ON Claims (chain_id, address, claimed_at);
|
|
12
|
+
|
|
13
|
+
CREATE INDEX IF NOT EXISTS idx_claims_ip ON Claims (chain_id, ip, claimed_at);
|
|
14
|
+
|
|
15
|
+
CREATE TABLE IF NOT EXISTS ChainLocks (
|
|
16
|
+
chain_id TEXT PRIMARY KEY,
|
|
17
|
+
locked_until INTEGER NOT NULL DEFAULT 0,
|
|
18
|
+
last_nonce INTEGER
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
CREATE TABLE IF NOT EXISTS UsedTokens (
|
|
22
|
+
token_hash TEXT PRIMARY KEY,
|
|
23
|
+
used_at INTEGER NOT NULL
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
CREATE INDEX IF NOT EXISTS idx_used_tokens_used_at ON UsedTokens (used_at);
|
|
6
27
|
`
|
package/src/setup.ts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import {MiddlewareHandler} from 'hono/types';
|
|
2
2
|
import {ServerOptions} from './types.js';
|
|
3
3
|
import {Env} from './env.js';
|
|
4
|
-
|
|
4
|
+
import {RemoteSQLStorage} from './storage/RemoteSQLStorage.js';
|
|
5
5
|
|
|
6
6
|
export type SetupOptions<CustomEnv extends Env> = {
|
|
7
7
|
serverOptions: ServerOptions<CustomEnv>;
|
|
8
8
|
};
|
|
9
9
|
|
|
10
10
|
export type Config<CustomEnv extends Env> = {
|
|
11
|
-
|
|
11
|
+
storage: RemoteSQLStorage;
|
|
12
12
|
env: CustomEnv;
|
|
13
13
|
};
|
|
14
14
|
|
|
@@ -25,21 +25,14 @@ export function setup<CustomEnv extends Env>(
|
|
|
25
25
|
|
|
26
26
|
return async (c, next) => {
|
|
27
27
|
const env = getEnv(c);
|
|
28
|
-
|
|
29
28
|
const db = getDB(c);
|
|
30
|
-
|
|
31
|
-
// const storage = new RemoteSQLStorage(db);
|
|
29
|
+
const storage = new RemoteSQLStorage(db);
|
|
32
30
|
|
|
33
31
|
c.set('config', {
|
|
34
|
-
|
|
32
|
+
storage,
|
|
35
33
|
env,
|
|
36
34
|
});
|
|
37
35
|
|
|
38
|
-
// // auto setup
|
|
39
|
-
// if (c.req.query('_initDB') == 'true') {
|
|
40
|
-
// await storage.setup();
|
|
41
|
-
// }
|
|
42
|
-
|
|
43
36
|
return next();
|
|
44
37
|
};
|
|
45
38
|
}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import {RemoteSQL} from 'remote-sql';
|
|
2
|
+
import schema from '../schema/ts/db.sql.js';
|
|
3
|
+
|
|
4
|
+
export type ClaimRow = {
|
|
5
|
+
id: number;
|
|
6
|
+
chain_id: string;
|
|
7
|
+
address: string;
|
|
8
|
+
ip: string;
|
|
9
|
+
amount: string;
|
|
10
|
+
tx_hash: string | null;
|
|
11
|
+
claimed_at: number;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export type ChainLockAcquisition = {
|
|
15
|
+
acquired: boolean;
|
|
16
|
+
// last nonce this faucet is known to have used on that chain, if any
|
|
17
|
+
lastNonce: number | null;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export type RateLimitHit = {
|
|
21
|
+
// which bucket was hit
|
|
22
|
+
reason: 'address' | 'ip';
|
|
23
|
+
// seconds the caller has to wait before trying again
|
|
24
|
+
retryAfter: number;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// A statement chunk that only contains comments cannot be executed on its own.
|
|
28
|
+
function isExecutable(statement: string): boolean {
|
|
29
|
+
return statement
|
|
30
|
+
.split('\n')
|
|
31
|
+
.some((line) => line.trim().length > 0 && !line.trim().startsWith('--'));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class RemoteSQLStorage {
|
|
35
|
+
constructor(protected db: RemoteSQL) {}
|
|
36
|
+
|
|
37
|
+
// ------------------------------------------------------------------------
|
|
38
|
+
// schema
|
|
39
|
+
// ------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
// Idempotent: every statement in db.sql is a CREATE ... IF NOT EXISTS.
|
|
42
|
+
async setup(): Promise<void> {
|
|
43
|
+
const statements = schema
|
|
44
|
+
.split(';')
|
|
45
|
+
.map((v) => v.trim())
|
|
46
|
+
.filter((v) => v.length > 0 && isExecutable(v))
|
|
47
|
+
.map((v) => this.db.prepare(`${v};`));
|
|
48
|
+
await this.db.batch(statements);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// ------------------------------------------------------------------------
|
|
52
|
+
// captcha token replay protection
|
|
53
|
+
// ------------------------------------------------------------------------
|
|
54
|
+
|
|
55
|
+
// Burns a captcha token. Returns false when that token was already used,
|
|
56
|
+
// which means the request is a replay of an earlier successful verification.
|
|
57
|
+
async burnToken(tokenHash: string, now: number): Promise<boolean> {
|
|
58
|
+
const {results} = await this.db
|
|
59
|
+
.prepare(
|
|
60
|
+
`INSERT INTO UsedTokens (token_hash, used_at) VALUES (?, ?)
|
|
61
|
+
ON CONFLICT (token_hash) DO NOTHING
|
|
62
|
+
RETURNING token_hash;`,
|
|
63
|
+
)
|
|
64
|
+
.bind(tokenHash, now)
|
|
65
|
+
.all<{token_hash: string}>();
|
|
66
|
+
return results.length > 0;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ------------------------------------------------------------------------
|
|
70
|
+
// rate limiting
|
|
71
|
+
// ------------------------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
// Atomically reserves a claim slot: the row is only inserted when no recent
|
|
74
|
+
// claim exists for that address or that ip. A single INSERT ... SELECT
|
|
75
|
+
// WHERE NOT EXISTS statement is atomic in SQLite, so two concurrent requests
|
|
76
|
+
// cannot both reserve. An empty `ip` disables the ip bucket.
|
|
77
|
+
async reserveClaim(params: {
|
|
78
|
+
chainId: string;
|
|
79
|
+
address: string;
|
|
80
|
+
ip: string;
|
|
81
|
+
amount: string;
|
|
82
|
+
now: number;
|
|
83
|
+
addressCutoff: number;
|
|
84
|
+
ipCutoff: number;
|
|
85
|
+
}): Promise<number | null> {
|
|
86
|
+
const {chainId, address, ip, amount, now, addressCutoff, ipCutoff} = params;
|
|
87
|
+
const {results} = await this.db
|
|
88
|
+
.prepare(
|
|
89
|
+
`INSERT INTO Claims (chain_id, address, ip, amount, claimed_at)
|
|
90
|
+
SELECT ?, ?, ?, ?, ?
|
|
91
|
+
WHERE NOT EXISTS (
|
|
92
|
+
SELECT 1 FROM Claims
|
|
93
|
+
WHERE chain_id = ?
|
|
94
|
+
AND (
|
|
95
|
+
(address = ? AND claimed_at > ?)
|
|
96
|
+
OR (ip <> '' AND ip = ? AND claimed_at > ?)
|
|
97
|
+
)
|
|
98
|
+
)
|
|
99
|
+
RETURNING id;`,
|
|
100
|
+
)
|
|
101
|
+
.bind(
|
|
102
|
+
chainId,
|
|
103
|
+
address,
|
|
104
|
+
ip,
|
|
105
|
+
amount,
|
|
106
|
+
now,
|
|
107
|
+
chainId,
|
|
108
|
+
address,
|
|
109
|
+
addressCutoff,
|
|
110
|
+
ip,
|
|
111
|
+
ipCutoff,
|
|
112
|
+
)
|
|
113
|
+
.all<{id: number}>();
|
|
114
|
+
if (results.length === 0) {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
return results[0].id;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Only called when reserveClaim returned null, to explain why.
|
|
121
|
+
async getRateLimitHit(params: {
|
|
122
|
+
chainId: string;
|
|
123
|
+
address: string;
|
|
124
|
+
ip: string;
|
|
125
|
+
now: number;
|
|
126
|
+
addressCutoff: number;
|
|
127
|
+
ipCutoff: number;
|
|
128
|
+
addressCooldown: number;
|
|
129
|
+
ipCooldown: number;
|
|
130
|
+
}): Promise<RateLimitHit> {
|
|
131
|
+
const {
|
|
132
|
+
chainId,
|
|
133
|
+
address,
|
|
134
|
+
ip,
|
|
135
|
+
now,
|
|
136
|
+
addressCutoff,
|
|
137
|
+
ipCutoff,
|
|
138
|
+
addressCooldown,
|
|
139
|
+
ipCooldown,
|
|
140
|
+
} = params;
|
|
141
|
+
const {results} = await this.db
|
|
142
|
+
.prepare(
|
|
143
|
+
`SELECT address, ip, claimed_at FROM Claims
|
|
144
|
+
WHERE chain_id = ?
|
|
145
|
+
AND (
|
|
146
|
+
(address = ? AND claimed_at > ?)
|
|
147
|
+
OR (ip <> '' AND ip = ? AND claimed_at > ?)
|
|
148
|
+
)
|
|
149
|
+
ORDER BY claimed_at DESC LIMIT 1;`,
|
|
150
|
+
)
|
|
151
|
+
.bind(chainId, address, addressCutoff, ip, ipCutoff)
|
|
152
|
+
.all<{address: string; ip: string; claimed_at: number}>();
|
|
153
|
+
|
|
154
|
+
if (results.length === 0) {
|
|
155
|
+
// the offending claim expired between the two queries, ask for an immediate retry
|
|
156
|
+
return {reason: 'address', retryAfter: 1};
|
|
157
|
+
}
|
|
158
|
+
const row = results[0];
|
|
159
|
+
const matchedAddress = row.address === address;
|
|
160
|
+
const cooldown = matchedAddress ? addressCooldown : ipCooldown;
|
|
161
|
+
const retryAfter = Math.max(1, row.claimed_at + cooldown - now);
|
|
162
|
+
return {reason: matchedAddress ? 'address' : 'ip', retryAfter};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Releases a reservation when the claim ended up not being dispensed.
|
|
166
|
+
async cancelClaim(id: number): Promise<void> {
|
|
167
|
+
await this.db.prepare(`DELETE FROM Claims WHERE id = ?;`).bind(id).all();
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async recordClaimTx(id: number, txHash: string): Promise<void> {
|
|
171
|
+
await this.db
|
|
172
|
+
.prepare(`UPDATE Claims SET tx_hash = ? WHERE id = ?;`)
|
|
173
|
+
.bind(txHash, id)
|
|
174
|
+
.all();
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ------------------------------------------------------------------------
|
|
178
|
+
// per chain send lock (nonce serialisation)
|
|
179
|
+
// ------------------------------------------------------------------------
|
|
180
|
+
|
|
181
|
+
// Takes the per chain lock so only one claim at a time picks a nonce.
|
|
182
|
+
// The lock is time boxed, so a crashed request cannot wedge the faucet.
|
|
183
|
+
async acquireChainLock(
|
|
184
|
+
chainId: string,
|
|
185
|
+
now: number,
|
|
186
|
+
lockedUntil: number,
|
|
187
|
+
): Promise<ChainLockAcquisition> {
|
|
188
|
+
await this.db
|
|
189
|
+
.prepare(
|
|
190
|
+
`INSERT INTO ChainLocks (chain_id, locked_until, last_nonce)
|
|
191
|
+
VALUES (?, 0, NULL)
|
|
192
|
+
ON CONFLICT (chain_id) DO NOTHING;`,
|
|
193
|
+
)
|
|
194
|
+
.bind(chainId)
|
|
195
|
+
.all();
|
|
196
|
+
|
|
197
|
+
const {results} = await this.db
|
|
198
|
+
.prepare(
|
|
199
|
+
`UPDATE ChainLocks SET locked_until = ?
|
|
200
|
+
WHERE chain_id = ? AND locked_until < ?
|
|
201
|
+
RETURNING last_nonce;`,
|
|
202
|
+
)
|
|
203
|
+
.bind(lockedUntil, chainId, now)
|
|
204
|
+
.all<{last_nonce: number | null}>();
|
|
205
|
+
|
|
206
|
+
if (results.length === 0) {
|
|
207
|
+
return {acquired: false, lastNonce: null};
|
|
208
|
+
}
|
|
209
|
+
return {acquired: true, lastNonce: results[0].last_nonce ?? null};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async releaseChainLock(
|
|
213
|
+
chainId: string,
|
|
214
|
+
nonceUsed?: number | null,
|
|
215
|
+
): Promise<void> {
|
|
216
|
+
if (typeof nonceUsed === 'number') {
|
|
217
|
+
await this.db
|
|
218
|
+
.prepare(
|
|
219
|
+
`UPDATE ChainLocks SET locked_until = 0, last_nonce = ? WHERE chain_id = ?;`,
|
|
220
|
+
)
|
|
221
|
+
.bind(nonceUsed, chainId)
|
|
222
|
+
.all();
|
|
223
|
+
} else {
|
|
224
|
+
await this.db
|
|
225
|
+
.prepare(`UPDATE ChainLocks SET locked_until = 0 WHERE chain_id = ?;`)
|
|
226
|
+
.bind(chainId)
|
|
227
|
+
.all();
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ------------------------------------------------------------------------
|
|
232
|
+
// housekeeping
|
|
233
|
+
// ------------------------------------------------------------------------
|
|
234
|
+
|
|
235
|
+
async cleanup(tokenCutoff: number, claimCutoff: number): Promise<void> {
|
|
236
|
+
await this.db.batch([
|
|
237
|
+
this.db
|
|
238
|
+
.prepare(`DELETE FROM UsedTokens WHERE used_at < ?;`)
|
|
239
|
+
.bind(tokenCutoff),
|
|
240
|
+
this.db
|
|
241
|
+
.prepare(`DELETE FROM Claims WHERE claimed_at < ?;`)
|
|
242
|
+
.bind(claimCutoff),
|
|
243
|
+
]);
|
|
244
|
+
}
|
|
245
|
+
}
|