Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/routes/v1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,10 @@ router.post('/stake/deposit/gasless', async (req: Request, res: Response) => {
const out = await gaslessDeposit(req.body, defaultGaslessDeps());
return res.status(out.status).json(out.body);
} catch (e: any) {
return res.status(500).json({ ok: false, sent: 'unknown', code: 'internal', error: e?.message ?? 'gasless deposit failed' });
// Never the error text: ethers puts the RPC URL, and any key in it, in its messages.
console.error('[stake/deposit/gasless] internal error:', e?.message ?? String(e));
return res.status(500).json({ ok: false, sent: 'unknown', code: 'internal',
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.' });
}
});

Expand Down
15 changes: 12 additions & 3 deletions src/services/escrow-refunder.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
/**
* Escrow refunder — the WITHDRAWAL leg of the verified-deposit escrow model, the
* mirror of deposit-verifier.ts. Broadcasts a real escrow -> builder USDC transfer
* on Base Sepolia so a real stake can actually be withdrawn end-to-end.
* Escrow refunder — every transaction the stake escrow signs, through one queue (oneAtATime, one
* nonce). Three kinds use it:
* - escrowRefund: the WITHDRAWAL leg, the mirror of deposit-verifier.ts. A real escrow -> builder
* USDC transfer on Base Sepolia, so a real stake can be withdrawn end to end.
* - escrowRelayAuthorization: the GASLESS DEPOSIT leg (services/gasless-deposit.ts). The escrow
* submits an owner's signed USDC transferWithAuthorization (owner -> escrow) and pays its gas.
* - agent payouts that share the escrow's signer and so its nonce.
* Until 2026-11-16 this header named only the first, and a reader would not know a keyless route
* can put sends on the same queue.
*
* The invariants below are stated for a refund. A relay checks CHAIN and SIGNER the same way, and
* instead of PAYEE requires the authorization's `to` to BE the escrow.
*
* FAIL-CLOSED BY DEFAULT. Until STAKE_ESCROW_SIGNER_KEY is set this returns a STUB
* (`stub: true`), and stake-vault's withdrawStake refuses on a stub — so a refund is
Expand Down
38 changes: 38 additions & 0 deletions src/services/gasless-deposit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { escrowRelayAuthorization, RefundBroadcastUnconfirmed, type Eip3009Autho
import { depositStake, serializeWithdraw, type DepositResult } from './stake-vault';
import { BASE_SEPOLIA_CHAIN_ID } from './testnet-only';
import { BASESCAN_TX, USDC_BASE_SEPOLIA } from './agent-spend';
import { getActiveNetwork } from '../config/network';

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

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

const b = (body ?? {}) as { authorization?: unknown; signature?: unknown };
const a = parseAuthorization(b.authorization);
Expand Down Expand Up @@ -226,6 +244,26 @@ export async function gaslessDeposit(body: unknown, deps: GaslessDeps): Promise<
};
}
logOnly('relay', e);
// A signed authorization can be submitted by anyone, and `to` is the escrow. So a revert here can
// mean another submitter used it first and the USDC DID move. Re-read before saying it did not.
let usedNow: boolean;
try {
usedNow = await deps.chain.authorizationState(a.from, a.nonce);
} catch (e2: unknown) {
logOnly('authorization state after a failed relay', e2);
return {
status: 202,
body: { ok: false, mode: 'on', sent: 'unknown', code: 'send_not_checked', ...plan,
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." },
};
}
if (usedNow) {
return {
status: 202,
body: { ok: false, mode: 'on', sent: 'unknown', code: 'authorization_used_elsewhere', ...plan,
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." },
};
}
return refuse(502, 'not_sent', 'The escrow did not submit the deposit, so no USDC moved.');
}
// The USDC has moved. From here every answer carries the tx hash: a credit that throws is not
Expand Down
33 changes: 33 additions & 0 deletions tests/gasless-deposit-route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* POST /api/v1/stake/deposit/gasless: the route's catch-all answers a fixed message. It used to return
* the thrown error's text, and ethers puts the RPC URL, and any key in it, in its messages (review of
* #1558). The service is mocked to throw such an error; nothing is read from a chain or a database.
*/
import request from 'supertest';
import express from 'express';

jest.mock('../src/db', () => ({
db: { from: jest.fn().mockReturnThis(), select: jest.fn().mockReturnThis(), eq: jest.fn().mockReturnThis(), maybeSingle: jest.fn().mockResolvedValue({ data: null }) },
}));
jest.mock('../src/services/gasless-deposit', () => ({
gaslessDeposit: jest.fn(async () => { throw new Error('missing response https://rpc.example.invalid/v2/NOT-A-REAL-KEY-123'); }),
defaultGaslessDeps: jest.fn(() => ({})),
}));

// eslint-disable-next-line @typescript-eslint/no-var-requires
const v1Router = require('../src/routes/v1').default;

test('an internal throw answers 500 with a fixed message, never the error text', async () => {
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
try {
const app = express();
app.use(express.json());
app.use('/api/v1', v1Router);
const res = await request(app).post('/api/v1/stake/deposit/gasless').send({});
expect(res.status).toBe(500);
expect(res.body).toMatchObject({ ok: false, sent: 'unknown', code: 'internal' });
expect(JSON.stringify(res.body)).not.toMatch(/NOT-A-REAL-KEY-123|rpc\.example|https?:\/\//);
} finally {
spy.mockRestore();
}
});
48 changes: 48 additions & 0 deletions tests/gasless-deposit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,3 +328,51 @@ describe('GASLESS_DEPOSIT_MODE', () => {
expect(gaslessDepositMode(raw as string | undefined)).toBe(want);
});
});

describe('gasless deposit follow-ups (review of #1558, before the flag goes on)', () => {
beforeAll(() => jest.useFakeTimers({ now: NOW * 1000, doNotFake: ['nextTick', 'setImmediate', 'setTimeout', 'clearTimeout'] }));
afterAll(() => jest.useRealTimers());
let errSpy: jest.SpyInstance;
beforeEach(() => { errSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); });
afterEach(() => errSpy.mockRestore());

test('REVERT: another submitter used the authorization first; the answer is 202 "used elsewhere", never "no USDC moved"', async () => {
const h = harness();
h.deps.relay = async (a) => {
h.usedNonces.add(`${a.from.toLowerCase()}:${a.nonce.toLowerCase()}`); // a front-runner's tx mined first
throw new Error('execution reverted: FiatTokenV2: authorization is used or canceled');
};
const out = await gaslessDeposit(await signed(), h.deps);
expect(out).toMatchObject({ status: 202, body: { code: 'authorization_used_elsewhere', sent: 'unknown' } });
expect(h.credits).toHaveLength(0);
});

test('REVERT: the re-read fails too; the answer is 202 not-checked, never "no USDC moved"', async () => {
const h = harness({ relay: async () => { throw new Error('execution reverted'); } });
let reads = 0;
h.deps.chain.authorizationState = async () => { if (++reads > 2) throw new Error('rpc down'); return false; };
const out = await gaslessDeposit(await signed(), h.deps);
expect(out).toMatchObject({ status: 202, body: { code: 'send_not_checked', sent: 'unknown' } });
});

test('REVERT: the authorization is still unused; then and only then "no USDC moved" (502)', async () => {
const h = harness({ relay: async () => { throw new Error('nonce too low'); } });
expect(await gaslessDeposit(await signed(), h.deps)).toMatchObject({ status: 502, body: { code: 'not_sent', sent: false } });
});

test('NETWORK: a server whose NETWORK is not Base Sepolia refuses before any chain read', async () => {
const prior = process.env.NETWORK;
process.env.NETWORK = 'base';
try {
const h = harness();
h.deps.chain.usdcDomain = async () => { throw new Error('must not be read'); };
const out = await gaslessDeposit(await signed(), h.deps);
expect(out).toMatchObject({ status: 503, body: { code: 'wrong_network', sent: false } });
process.env.NETWORK = 'no-such-network';
expect((await gaslessDeposit(await signed(), h.deps)).body.code).toBe('wrong_network');
expect(h.relayed).toHaveLength(0);
} finally {
if (prior === undefined) delete process.env.NETWORK; else process.env.NETWORK = prior;
}
});
});
Loading