Skip to content

Commit 150ecc8

Browse files
DealAppSeoclaude
andauthored
fix(stake): gasless follow-ups before the flag goes on (review of #1558) (#1568)
- A relay that fails re-reads authorizationState: used (or canceled) answers 202 authorization_used_elsewhere, an unreadable state answers 202 send_not_checked, and only an unused one answers 502 "no USDC moved". A signed authorization can be submitted by anyone and pays the escrow, so a revert can mean the USDC did move. - Refuse with 503 wrong_network unless NETWORK resolves to Base Sepolia: verifyEip3009Local takes the EIP-712 chainId from NETWORK while the escrow sends only on 84532. - The route's catch-all answers a fixed message; the error text goes to the log. - The global 4/min admission budget can be griefed by four funded wallets: stated as a ponytail ceiling with the upgrade options (a decision, not decided here). - escrow-refunder.ts header names all three kinds of send on the escrow's one queue. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent eea6506 commit 150ecc8

5 files changed

Lines changed: 135 additions & 4 deletions

File tree

‎src/routes/v1.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -537,7 +537,10 @@ router.post('/stake/deposit/gasless', async (req: Request, res: Response) => {
537537
const out = await gaslessDeposit(req.body, defaultGaslessDeps());
538538
return res.status(out.status).json(out.body);
539539
} catch (e: any) {
540-
return res.status(500).json({ ok: false, sent: 'unknown', code: 'internal', error: e?.message ?? 'gasless deposit failed' });
540+
// Never the error text: ethers puts the RPC URL, and any key in it, in its messages.
541+
console.error('[stake/deposit/gasless] internal error:', e?.message ?? String(e));
542+
return res.status(500).json({ ok: false, sent: 'unknown', code: 'internal',
543+
error: 'The gasless deposit failed inside the server, so whether anything was sent is not known. Check this authorization on BaseScan before signing a new one.' });
541544
}
542545
});
543546

‎src/services/escrow-refunder.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,16 @@
11
/**
2-
* Escrow refunder — the WITHDRAWAL leg of the verified-deposit escrow model, the
3-
* mirror of deposit-verifier.ts. Broadcasts a real escrow -> builder USDC transfer
4-
* on Base Sepolia so a real stake can actually be withdrawn end-to-end.
2+
* Escrow refunder — every transaction the stake escrow signs, through one queue (oneAtATime, one
3+
* nonce). Three kinds use it:
4+
* - escrowRefund: the WITHDRAWAL leg, the mirror of deposit-verifier.ts. A real escrow -> builder
5+
* USDC transfer on Base Sepolia, so a real stake can be withdrawn end to end.
6+
* - escrowRelayAuthorization: the GASLESS DEPOSIT leg (services/gasless-deposit.ts). The escrow
7+
* submits an owner's signed USDC transferWithAuthorization (owner -> escrow) and pays its gas.
8+
* - agent payouts that share the escrow's signer and so its nonce.
9+
* Until 2026-11-16 this header named only the first, and a reader would not know a keyless route
10+
* can put sends on the same queue.
11+
*
12+
* The invariants below are stated for a refund. A relay checks CHAIN and SIGNER the same way, and
13+
* instead of PAYEE requires the authorization's `to` to BE the escrow.
514
*
615
* FAIL-CLOSED BY DEFAULT. Until STAKE_ESCROW_SIGNER_KEY is set this returns a STUB
716
* (`stub: true`), and stake-vault's withdrawStake refuses on a stub — so a refund is

‎src/services/gasless-deposit.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import { escrowRelayAuthorization, RefundBroadcastUnconfirmed, type Eip3009Autho
3131
import { depositStake, serializeWithdraw, type DepositResult } from './stake-vault';
3232
import { BASE_SEPOLIA_CHAIN_ID } from './testnet-only';
3333
import { BASESCAN_TX, USDC_BASE_SEPOLIA } from './agent-spend';
34+
import { getActiveNetwork } from '../config/network';
3435

3536
export type GaslessMode = 'off' | 'shadow' | 'on';
3637

@@ -59,6 +60,12 @@ export const MIN_GASLESS_DEPOSIT = 1_000_000n;
5960
* DIFFERENT authorizations wait. Without a budget a caller could queue more sends than one signer
6061
* drains and push every withdrawal and payout behind them (Strix on #1558). Process-wide on purpose:
6162
* a per-address budget is bypassed by rotating addresses. A refused deposit is retried by the client.
63+
*
64+
* ponytail: the global budget can be GRIEFED. Four wallets, each with an account and 1 USDC, can hold
65+
* all four slots every minute and keep everyone else at 429; the USDC is theirs again by withdrawal,
66+
* and the escrow pays every gas. The per-payer slot only stops ONE wallet from doing it. Upgrade before
67+
* GASLESS_DEPOSIT_MODE=on for strangers: gate admission on something a rotated wallet cannot make for
68+
* free (account age, a stake already held, or a signed connect), or charge the gas back from the deposit.
6269
*/
6370
export function createGaslessAdmission(maxPerMinute = 4, maxPerPayer = 1): (nowMs: number, payer: string) => boolean {
6471
const recent: Array<{ at: number; payer: string }> = [];
@@ -130,6 +137,17 @@ export async function gaslessDeposit(body: unknown, deps: GaslessDeps): Promise<
130137
if (deps.mode === 'off') return refuse(503, 'gasless_deposit_off', 'Gasless deposits are not enabled on this server. Nothing was sent.');
131138
if (!deps.realStaking) return refuse(503, 'real_staking_off', 'Real staking is not enabled on this server, so a deposit could not be credited. Nothing was sent.');
132139
if (!deps.escrow) return refuse(503, 'escrow_not_configured', 'The stake escrow is not configured on this server. Nothing was sent.');
140+
// verifyEip3009Local takes the EIP-712 chainId from NETWORK (getActiveNetwork); the escrow sends only on
141+
// Base Sepolia (84532). With NETWORK naming another chain, signatures would be checked for that chain.
142+
let signingChainId: number | null = null;
143+
try {
144+
signingChainId = getActiveNetwork().chainId;
145+
} catch {
146+
/* unknown NETWORK: refused below */
147+
}
148+
if (signingChainId !== BASE_SEPOLIA_CHAIN_ID) {
149+
return refuse(503, 'wrong_network', 'This server checks signatures for a chain other than Base Sepolia, so gasless deposits are refused. Nothing was sent.');
150+
}
133151

134152
const b = (body ?? {}) as { authorization?: unknown; signature?: unknown };
135153
const a = parseAuthorization(b.authorization);
@@ -226,6 +244,26 @@ export async function gaslessDeposit(body: unknown, deps: GaslessDeps): Promise<
226244
};
227245
}
228246
logOnly('relay', e);
247+
// A signed authorization can be submitted by anyone, and `to` is the escrow. So a revert here can
248+
// mean another submitter used it first and the USDC DID move. Re-read before saying it did not.
249+
let usedNow: boolean;
250+
try {
251+
usedNow = await deps.chain.authorizationState(a.from, a.nonce);
252+
} catch (e2: unknown) {
253+
logOnly('authorization state after a failed relay', e2);
254+
return {
255+
status: 202,
256+
body: { ok: false, mode: 'on', sent: 'unknown', code: 'send_not_checked', ...plan,
257+
error: "The escrow's submission failed and the authorization's state could not be re-read, so it is not known whether USDC moved. Check this authorization on BaseScan before signing a new one." },
258+
};
259+
}
260+
if (usedNow) {
261+
return {
262+
status: 202,
263+
body: { ok: false, mode: 'on', sent: 'unknown', code: 'authorization_used_elsewhere', ...plan,
264+
error: "The escrow's submission failed, and the chain shows this authorization as used or canceled. If it was used, its USDC reached the escrow from another submitter: find that transaction on BaseScan and claim it with POST /api/v1/stake/deposit. If you canceled it, nothing moved." },
265+
};
266+
}
229267
return refuse(502, 'not_sent', 'The escrow did not submit the deposit, so no USDC moved.');
230268
}
231269
// The USDC has moved. From here every answer carries the tx hash: a credit that throws is not
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* POST /api/v1/stake/deposit/gasless: the route's catch-all answers a fixed message. It used to return
3+
* the thrown error's text, and ethers puts the RPC URL, and any key in it, in its messages (review of
4+
* #1558). The service is mocked to throw such an error; nothing is read from a chain or a database.
5+
*/
6+
import request from 'supertest';
7+
import express from 'express';
8+
9+
jest.mock('../src/db', () => ({
10+
db: { from: jest.fn().mockReturnThis(), select: jest.fn().mockReturnThis(), eq: jest.fn().mockReturnThis(), maybeSingle: jest.fn().mockResolvedValue({ data: null }) },
11+
}));
12+
jest.mock('../src/services/gasless-deposit', () => ({
13+
gaslessDeposit: jest.fn(async () => { throw new Error('missing response https://rpc.example.invalid/v2/NOT-A-REAL-KEY-123'); }),
14+
defaultGaslessDeps: jest.fn(() => ({})),
15+
}));
16+
17+
// eslint-disable-next-line @typescript-eslint/no-var-requires
18+
const v1Router = require('../src/routes/v1').default;
19+
20+
test('an internal throw answers 500 with a fixed message, never the error text', async () => {
21+
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
22+
try {
23+
const app = express();
24+
app.use(express.json());
25+
app.use('/api/v1', v1Router);
26+
const res = await request(app).post('/api/v1/stake/deposit/gasless').send({});
27+
expect(res.status).toBe(500);
28+
expect(res.body).toMatchObject({ ok: false, sent: 'unknown', code: 'internal' });
29+
expect(JSON.stringify(res.body)).not.toMatch(/NOT-A-REAL-KEY-123|rpc\.example|https?:\/\//);
30+
} finally {
31+
spy.mockRestore();
32+
}
33+
});

‎tests/gasless-deposit.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,3 +328,51 @@ describe('GASLESS_DEPOSIT_MODE', () => {
328328
expect(gaslessDepositMode(raw as string | undefined)).toBe(want);
329329
});
330330
});
331+
332+
describe('gasless deposit follow-ups (review of #1558, before the flag goes on)', () => {
333+
beforeAll(() => jest.useFakeTimers({ now: NOW * 1000, doNotFake: ['nextTick', 'setImmediate', 'setTimeout', 'clearTimeout'] }));
334+
afterAll(() => jest.useRealTimers());
335+
let errSpy: jest.SpyInstance;
336+
beforeEach(() => { errSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); });
337+
afterEach(() => errSpy.mockRestore());
338+
339+
test('REVERT: another submitter used the authorization first; the answer is 202 "used elsewhere", never "no USDC moved"', async () => {
340+
const h = harness();
341+
h.deps.relay = async (a) => {
342+
h.usedNonces.add(`${a.from.toLowerCase()}:${a.nonce.toLowerCase()}`); // a front-runner's tx mined first
343+
throw new Error('execution reverted: FiatTokenV2: authorization is used or canceled');
344+
};
345+
const out = await gaslessDeposit(await signed(), h.deps);
346+
expect(out).toMatchObject({ status: 202, body: { code: 'authorization_used_elsewhere', sent: 'unknown' } });
347+
expect(h.credits).toHaveLength(0);
348+
});
349+
350+
test('REVERT: the re-read fails too; the answer is 202 not-checked, never "no USDC moved"', async () => {
351+
const h = harness({ relay: async () => { throw new Error('execution reverted'); } });
352+
let reads = 0;
353+
h.deps.chain.authorizationState = async () => { if (++reads > 2) throw new Error('rpc down'); return false; };
354+
const out = await gaslessDeposit(await signed(), h.deps);
355+
expect(out).toMatchObject({ status: 202, body: { code: 'send_not_checked', sent: 'unknown' } });
356+
});
357+
358+
test('REVERT: the authorization is still unused; then and only then "no USDC moved" (502)', async () => {
359+
const h = harness({ relay: async () => { throw new Error('nonce too low'); } });
360+
expect(await gaslessDeposit(await signed(), h.deps)).toMatchObject({ status: 502, body: { code: 'not_sent', sent: false } });
361+
});
362+
363+
test('NETWORK: a server whose NETWORK is not Base Sepolia refuses before any chain read', async () => {
364+
const prior = process.env.NETWORK;
365+
process.env.NETWORK = 'base';
366+
try {
367+
const h = harness();
368+
h.deps.chain.usdcDomain = async () => { throw new Error('must not be read'); };
369+
const out = await gaslessDeposit(await signed(), h.deps);
370+
expect(out).toMatchObject({ status: 503, body: { code: 'wrong_network', sent: false } });
371+
process.env.NETWORK = 'no-such-network';
372+
expect((await gaslessDeposit(await signed(), h.deps)).body.code).toBe('wrong_network');
373+
expect(h.relayed).toHaveLength(0);
374+
} finally {
375+
if (prior === undefined) delete process.env.NETWORK; else process.env.NETWORK = prior;
376+
}
377+
});
378+
});

0 commit comments

Comments
 (0)