diff --git a/src/config/known-env-vars.generated.ts b/src/config/known-env-vars.generated.ts index 3feeb7c3..4bcb503a 100644 --- a/src/config/known-env-vars.generated.ts +++ b/src/config/known-env-vars.generated.ts @@ -153,6 +153,7 @@ FIREWORKS_API_KEY FREE_TIER_DAILY_CAP_DEFAULT FREE_TIER_QUOTA_SHADOW_ENABLED FULL_ACCOUNT_JWT_SECRET +GASLESS_DEPOSIT_MODE GATE_PROVISIONS_ACCOUNT GEMINI_API_KEY GITHUB_STEP_SUMMARY diff --git a/src/middleware/auth.ts b/src/middleware/auth.ts index 1617b59d..62df0a2c 100644 --- a/src/middleware/auth.ts +++ b/src/middleware/auth.ts @@ -176,6 +176,10 @@ export const authMiddleware = async (req: Request, res: Response, next: NextFunc // signature for real). It is NOT unauthenticated. /stake/withdraw is not on // this list and stays API-key gated. if (req.method === 'POST' && req.path === '/api/v1/stake/deposit') return next(); + // Gasless deposit (EIP-3009): authorized by the owner's own signature over the transfer, checked in + // services/gasless-deposit.ts before the escrow sends anything. A newcomer has no API key. Off by + // default (GASLESS_DEPOSIT_MODE), and then it refuses without reading or sending. + if (req.method === 'POST' && req.path === '/api/v1/stake/deposit/gasless') return next(); // Read-only: returns the exact text to sign. Reveals nothing, authorizes nothing. if (req.method === 'GET' && req.path === '/api/v1/stake/deposit/message') return next(); // Read-only escrow config/funding health. Reveals only the escrow ADDRESS, its diff --git a/src/ops/flag-registry.ts b/src/ops/flag-registry.ts index 72a8ff66..bcacf23d 100644 --- a/src/ops/flag-registry.ts +++ b/src/ops/flag-registry.ts @@ -57,6 +57,7 @@ ENGINE_WORKERS_ENABLED EXECUTION_FLOOR_ENABLED EXPERIMENTAL_REPID_MODE FREE_TIER_QUOTA_SHADOW_ENABLED +GASLESS_DEPOSIT_MODE GROUNDING_MODE HAL_CHRONIC_FLAG_ENABLED HAL_DECISION_MODE diff --git a/src/routes/v1.ts b/src/routes/v1.ts index 2d1416b5..70584930 100644 --- a/src/routes/v1.ts +++ b/src/routes/v1.ts @@ -524,6 +524,23 @@ router.get('/stake/deposit/message', (req: Request, res: Response) => { }); }); +/** + * POST /stake/deposit/gasless { authorization, signature } — deposit stake with no ETH (R3, 2026-11-16). + * The owner signs a USDC transferWithAuthorization (EIP-3009) to the stake escrow; the escrow submits + * it and pays the gas; the stake is credited by depositStake's verified path. Keyless on purpose: the + * signature IS the authorization, and only the wallet's owner can make it (auth.ts bypass list). + * GASLESS_DEPOSIT_MODE: off (default, refused) | shadow (checks only, nothing sent) | on. + */ +router.post('/stake/deposit/gasless', async (req: Request, res: Response) => { + const { gaslessDeposit, defaultGaslessDeps } = require('../services/gasless-deposit') as typeof import('../services/gasless-deposit'); + try { + 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' }); + } +}); + router.post('/stake/deposit', async (req: Request, res: Response) => { let { builder_address, amount, tx_hash, signature } = req.body ?? {}; if (!builder_address || !amount) return res.status(400).json({ error: 'builder_address and amount required' }); diff --git a/src/services/escrow-refunder.ts b/src/services/escrow-refunder.ts index 33a78d70..51f4c098 100644 --- a/src/services/escrow-refunder.ts +++ b/src/services/escrow-refunder.ts @@ -144,7 +144,11 @@ export function refundWaitFailure(e: unknown, txHash: string): Error | { txHash: return new RefundBroadcastUnconfirmed(txHash, e instanceof Error ? e.message.split('\n')[0] ?? '' : String(e)); } -const ERC20_ABI = ['function transfer(address to, uint256 value) returns (bool)']; +const ERC20_ABI = [ + 'function transfer(address to, uint256 value) returns (bool)', + // EIP-3009, FiatToken v2 (Base Sepolia USDC answers version() = "2"). The v,r,s form is in every v2. + 'function transferWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s)', +]; const ERC20_BALANCE_ABI = ['function balanceOf(address owner) view returns (uint256)']; /** The chain write, abstracted so tests exercise the guard logic without a live chain. */ @@ -183,7 +187,16 @@ function refused(amount: bigint, to: string | undefined, note: string): RefundIn * The real escrow -> builder send. Refuses unless the chain is Base Sepolia and the * signer IS the escrow address. Throws on any failure so escrowRefund fails closed. */ -async function realSender(to: string, amount: bigint): Promise<{ txHash: string }> { +function realSender(to: string, amount: bigint): Promise<{ txHash: string }> { + return escrowCall((usdc) => usdc.getFunction('transfer').populateTransaction(to, amount)); +} + +/** + * Every escrow transaction goes through here: the refund, the stake payout, and the gasless-deposit + * relay. Same guards for each (Base Sepolia only, signer == escrow, signed before broadcast, outcome + * decided only by proof). Messages say "refund" because this began as the refund path. + */ +async function escrowCall(build: (usdc: ethers.Contract) => Promise): Promise<{ txHash: string }> { if (!config.stakeEscrowSignerKey) throw new Error('escrow signer not configured'); if (!config.stakeEscrowAddress) throw new Error('STAKE_ESCROW_ADDRESS not configured'); const provider = new ethers.JsonRpcProvider(config.baseSepoliaRpc); @@ -202,7 +215,7 @@ async function realSender(to: string, amount: bigint): Promise<{ txHash: string // and the refund could still land (Grok r8 on #1550). Anything that fails BEFORE the broadcast // (building the transaction, a gas estimate that reverts) still means nothing was sent. // getFunction returns a defined ContractMethod (satisfies noUncheckedIndexedAccess). - const unsigned = await wallet.populateTransaction(await usdc.getFunction('transfer').populateTransaction(to, amount)); + const unsigned = await wallet.populateTransaction(await build(usdc)); const signed = await wallet.signTransaction(unsigned); const hash = ethers.Transaction.from(signed).hash; if (!hash) throw new Error('refusing: could not derive the refund tx hash before broadcast'); @@ -422,3 +435,44 @@ export async function escrowRefund( return refused(amount, to, `escrow refund failed: ${msg}`); } } + +/** An EIP-3009 transferWithAuthorization the owner signed. Values are decimal strings or 0x hex. */ +export interface Eip3009Authorization { + from: string; + to: string; + value: string; + validAfter: string; + validBefore: string; + nonce: string; +} + +export type AuthorizationRelay = (a: Eip3009Authorization, signature: string) => Promise<{ txHash: string }>; +let relay: AuthorizationRelay | null = null; + +/** Test seam: inject a fake relay. Call with undefined to reset to the real one. */ +export function __setAuthorizationRelay(r?: AuthorizationRelay | null): void { + relay = r ?? null; +} + +/** + * GASLESS DEPOSIT: the escrow submits an owner's signed transferWithAuthorization (owner -> escrow) + * and pays its gas, so the owner needs no ETH. The USDC contract checks the signature, the time + * window and the nonce; this only adds what it would not: the payee must BE the escrow, and the + * send shares the escrow's one-at-a-time queue (one nonce). Throws on failure; a broadcast whose + * outcome is unknown throws RefundBroadcastUnconfirmed with the hash. Callers check everything + * first (services/gasless-deposit.ts), so a revert here is a race, not the normal refusal. + */ +export async function escrowRelayAuthorization(a: Eip3009Authorization, signature: string): Promise<{ txHash: string }> { + if (!config.stakeEscrowSignerKey || !config.stakeEscrowAddress) throw new Error('escrow signer not configured'); + if (!isAddress(a.to) || !eqAddr(a.to, config.stakeEscrowAddress)) throw new Error('refusing: the authorization does not pay the escrow'); + const sig = ethers.Signature.from(signature); + const send: AuthorizationRelay = + relay ?? + (() => + escrowCall((usdc) => + usdc + .getFunction('transferWithAuthorization') + .populateTransaction(a.from, a.to, a.value, a.validAfter, a.validBefore, a.nonce, sig.v, sig.r, sig.s), + )); + return oneAtATime(() => send(a, signature)); +} diff --git a/src/services/gasless-deposit.ts b/src/services/gasless-deposit.ts new file mode 100644 index 00000000..57cc2aca --- /dev/null +++ b/src/services/gasless-deposit.ts @@ -0,0 +1,317 @@ +/** + * GASLESS OWNER DEPOSIT (EIP-3009), R3 2026-11-16. Flag GASLESS_DEPOSIT_MODE: off (default) | shadow | on. + * + * WHY. A newcomer has testnet USDC and no ETH, and a plain ERC-20 transfer needs gas. The owner + * instead SIGNS a USDC `transferWithAuthorization` (from = their wallet, to = the stake escrow) in + * their wallet: a signature, no transaction, no gas. The engine checks it, the escrow submits it and + * pays the gas, and the stake is credited (ONBOARDING_FRICTION_LOG stop 4). + * + * NOTHING HERE IS A SECOND VERIFIER. The signature, time window and recipient are checked by + * verifyEip3009Local (x402-resilient.ts, the x402 path), against USDC's name and version read from + * the chain and matched to its DOMAIN_SEPARATOR (resolveAndVerifyDomain). The send is the escrow's + * guarded path (escrow-refunder.ts escrowRelayAuthorization). The credit is depositStake's verified + * path (stake-vault.ts): the same on-chain Transfer check, exact-amount rule and one-credit-per-tx + * rule every real deposit gets. What this file adds is the order, and the refusals that must come + * BEFORE the escrow spends gas: + * - the authorization must pay the escrow, exactly, for a positive amount; + * - it must not expire within MIN_WINDOW_S (it would revert after the escrow paid gas); + * - the payer must have an account here, or the USDC would arrive with nobody to credit; + * - the nonce must be unused on chain (replay), and the payer must hold the amount. + * + * MODES. off: refused, nothing read or sent. shadow: every check runs and the answer says what WOULD + * be submitted; nothing is sent. on: submitted, then credited. Any other value is off (a typo in a + * money control sends nothing). + */ +import { ethers } from 'ethers'; +import { config } from '../config'; +import { db } from '../db'; +import { verifyEip3009Local } from './x402-resilient'; +import { resolveAndVerifyDomain } from './x402-outbound-client'; +import { escrowRelayAuthorization, RefundBroadcastUnconfirmed, type Eip3009Authorization } from './escrow-refunder'; +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'; + +export type GaslessMode = 'off' | 'shadow' | 'on'; + +export function gaslessDepositMode(raw: string | undefined = process.env.GASLESS_DEPOSIT_MODE): GaslessMode { + const v = (raw ?? '').trim().toLowerCase(); + if (v === 'shadow' || v === 'on') return v; + if (v !== '' && v !== 'off') console.error(`[gasless-deposit] GASLESS_DEPOSIT_MODE=${JSON.stringify(raw)} is not off, shadow or on: off (fail closed).`); + return 'off'; +} + +/** An authorization must stay valid at least this long, so it cannot expire while the escrow's tx mines. */ +export const MIN_WINDOW_S = 120; + +/** + * Smallest gasless deposit, in micro-USDC. Every accepted authorization makes the escrow sign, + * broadcast and confirm a transaction whose gas it pays, on a keyless route where the caller picks + * the amount, so dust is refused before anything is sent (Strix on #1558). 1 USDC is the E2E's own + * stake and far above the L2 gas it triggers. + */ +export const MIN_GASLESS_DEPOSIT = 1_000_000n; + +/** + * Admission budget for the escrow's send queue from this keyless route. The escrow sends one + * transaction at a time (escrow-refunder.ts oneAtATime), refunds and agent payouts queue on the same + * chain, and each send holds it until mined; the per-authorization lock below never makes two + * 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. + */ +export function createGaslessAdmission(maxPerMinute = 4, maxPerPayer = 1): (nowMs: number, payer: string) => boolean { + const recent: Array<{ at: number; payer: string }> = []; + return (nowMs, payer) => { + while (recent.length > 0 && nowMs - recent[0]!.at >= 60_000) recent.shift(); + if (recent.length >= maxPerMinute) return false; + // A per-payer bound ON TOP of the global one (Strix on #1558): one wallet can no longer spend the + // whole minute's budget on concurrent deposits the escrow then refuses. Rotating wallets still + // meets the global cap, and each wallet needs an account here and the USDC it signs for. + const wallet = payer.toLowerCase(); + if (recent.filter((r) => r.payer === wallet).length >= maxPerPayer) return false; + recent.push({ at: nowMs, payer: wallet }); + return true; + }; +} + +export interface GaslessChain { + authorizationState(authorizer: string, nonce: string): Promise; + balanceOf(owner: string): Promise; + usdcDomain(): Promise<{ name: string; version: string }>; +} + +export interface GaslessDeps { + mode: GaslessMode; + escrow: string | null; + usdc: string; + realStaking: boolean; + chain: GaslessChain; + accountOf(wallet: string): Promise; + relay(a: Eip3009Authorization, signature: string): Promise<{ txHash: string }>; + credit(wallet: string, amount: bigint, txHash: string): Promise; + now(): number; + /** Admission to the escrow's send queue; see createGaslessAdmission. */ + admit(nowMs: number, payer: string): boolean; +} + +export interface GaslessAnswer { + status: number; + body: Record; +} + +const UINT = /^(0|[1-9][0-9]{0,77}|0x[0-9a-fA-F]{1,64})$/; +const NONCE = /^0x[0-9a-fA-F]{64}$/; +const SIG = /^0x[0-9a-fA-F]{130}$/; + +/** + * A chain, DB or relay error goes to the server log, never into an answer (Strix on #1559 found the + * class): ethers puts the request URL in its messages, and a provider URL can carry an API key. + */ +function logOnly(where: string, e: unknown): void { + console.error(`[gasless-deposit] ${where}:`, (e as Error)?.message ?? String(e)); +} + +function parseAuthorization(raw: unknown): Eip3009Authorization | null { + const a = raw as Record | null; + if (!a || typeof a !== 'object') return null; + const str = (k: string) => (typeof a[k] === 'string' || typeof a[k] === 'number' ? String(a[k]) : ''); + const out = { from: str('from'), to: str('to'), value: str('value'), validAfter: str('validAfter'), validBefore: str('validBefore'), nonce: str('nonce') }; + if (!ethers.isAddress(out.from) || !ethers.isAddress(out.to)) return null; + if (![out.value, out.validAfter, out.validBefore].every((v) => UINT.test(v)) || !NONCE.test(out.nonce)) return null; + return out; +} + +export async function gaslessDeposit(body: unknown, deps: GaslessDeps): Promise { + const refuse = (status: number, code: string, error: string, extra: Record = {}): GaslessAnswer => ({ + status, + body: { ok: false, mode: deps.mode, sent: false, code, error, ...extra }, + }); + 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.'); + + const b = (body ?? {}) as { authorization?: unknown; signature?: unknown }; + const a = parseAuthorization(b.authorization); + const signature = typeof b.signature === 'string' ? b.signature : ''; + if (!a || !SIG.test(signature)) { + return refuse(400, 'bad_authorization', 'Send { authorization: { from, to, value, validAfter, validBefore, nonce }, signature } for a USDC transferWithAuthorization. Nothing was sent.'); + } + const value = BigInt(a.value); + if (value < MIN_GASLESS_DEPOSIT) { + return refuse(400, 'bad_amount', `The amount must be at least ${MIN_GASLESS_DEPOSIT} micro-USDC (1 USDC). Nothing was sent.`); + } + if (a.to.toLowerCase() !== deps.escrow.toLowerCase()) { + return refuse(400, 'wrong_recipient', `The authorization must pay the stake escrow ${ethers.getAddress(deps.escrow)}. Nothing was sent.`); + } + const now = deps.now(); + if (BigInt(a.validBefore) <= BigInt(now)) return refuse(400, 'expired', 'This authorization has expired. Sign a new one. Nothing was sent.'); + if (BigInt(a.validBefore) < BigInt(now + MIN_WINDOW_S)) { + return refuse(400, 'expires_too_soon', `This authorization expires in under ${MIN_WINDOW_S} s, so it could expire before it is mined. Sign one valid for longer. Nothing was sent.`); + } + + let domain: { name: string; version: string }; + try { + domain = await deps.chain.usdcDomain(); + } catch (e: unknown) { + logOnly('usdc domain read', e); + return refuse(503, 'not_checked', "Could not read USDC's signing domain from the chain, so the signature was not checked. Nothing was sent."); + } + // verifyEip3009Local takes an x402 payment header (base64 JSON) and requirements; reuse it as is. + const header = Buffer.from(JSON.stringify({ authorization: a, signature })).toString('base64'); + const checked = await verifyEip3009Local(header, { + scheme: 'exact', + network: 'base-sepolia', + maxAmountRequired: value.toString(), + asset: deps.usdc, + payTo: deps.escrow, + resource: 'stake-deposit', + mimeType: 'application/json', + maxTimeoutSeconds: 0, + extra: domain, + }); + if (!checked.valid) return refuse(400, 'bad_signature', `The authorization did not verify: ${checked.reason}. Nothing was sent.`); + + let account: string | null; + try { + account = await deps.accountOf(a.from); + } catch (e: unknown) { + logOnly('account lookup', e); + return refuse(503, 'not_checked', 'Could not read whether this wallet has an account. Nothing was sent.'); + } + if (!account) { + return refuse(404, 'no_account', 'This wallet has no account here, so the deposit would have nobody to credit. Connect the wallet first (POST /api/v1/account/connect). Nothing was sent.'); + } + + let used: boolean; + let balance: bigint; + try { + [used, balance] = await Promise.all([deps.chain.authorizationState(a.from, a.nonce), deps.chain.balanceOf(a.from)]); + } catch (e: unknown) { + logOnly('authorization state / balance read', e); + return refuse(503, 'not_checked', "Could not read the authorization's state from the chain. Nothing was sent."); + } + if (used) return refuse(409, 'authorization_used', 'This authorization (its nonce) has already been used on chain. Nothing was sent again.'); + if (balance < value) return refuse(400, 'insufficient_balance', 'The wallet holds less USDC than this authorization moves. Nothing was sent.'); + + const plan = { from: ethers.getAddress(a.from), to: ethers.getAddress(a.to), amount_micro_usdc: value.toString(), account_id: account, gas_paid_by: 'escrow' }; + if (deps.mode === 'shadow') { + return { status: 200, body: { ok: true, mode: 'shadow', sent: false, would_submit: true, ...plan, note: 'Shadow mode: every check passed and nothing was sent.' } }; + } + + // One submission per authorization at a time in this process; the chain refuses a second use anyway. + return serializeWithdraw(`gasless:${a.from.toLowerCase()}:${a.nonce.toLowerCase()}`, async (): Promise => { + try { + if (await deps.chain.authorizationState(a.from, a.nonce)) { + return refuse(409, 'authorization_used', 'This authorization (its nonce) has already been used on chain. Nothing was sent again.'); + } + } catch (e: unknown) { + logOnly('authorization state re-read', e); + return refuse(503, 'not_checked', "Could not re-read the authorization's state. Nothing was sent."); + } + // Admission AFTER every refusal, the in-lock re-check included, so a refused deposit never takes a + // slot (Grok r3 on #1558). The escrow's send queue is shared with refunds and payouts. + if (!deps.admit(now * 1000, a.from)) { + return refuse(429, 'escrow_busy', 'Too many gasless deposits are being submitted right now, so this one was not queued. Nothing was sent; retry in a minute.'); + } + let txHash: string; + try { + ({ txHash } = await deps.relay(a, signature)); + } catch (e: unknown) { + if (e instanceof RefundBroadcastUnconfirmed) { + return { + status: 202, + body: { ok: false, mode: 'on', sent: 'unknown', code: 'sent_unconfirmed', tx_hash: e.txHash, basescan_url: `${BASESCAN_TX}${e.txHash}`, ...plan, + error: 'The escrow broadcast the deposit but could not confirm it. Check the tx; once it is mined, claim it with POST /api/v1/stake/deposit and this tx_hash.' }, + }; + } + logOnly('relay', e); + 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 + // "not sent", and a 500 without the hash would leave the owner nothing to claim with. + let credited: DepositResult; + try { + credited = await deps.credit(a.from, value, txHash); + } catch (e: unknown) { + logOnly(`credit of ${txHash}`, e); + return { + status: 202, + body: { ok: false, mode: 'on', sent: true, code: 'credit_not_checked', tx_hash: txHash, basescan_url: `${BASESCAN_TX}${txHash}`, ...plan, + error: 'The USDC reached the escrow, and the credit could not be confirmed. Claim it with POST /api/v1/stake/deposit and this tx_hash; a transfer already credited is refused as a duplicate, never credited twice.' }, + }; + } + if (!credited.ok) { + // depositStake's error can carry verifyDeposit's raw RPC text, so it is logged, not returned. + console.error(`[gasless-deposit] credit of ${txHash} refused:`, credited.error ?? 'unknown'); + return { + status: 202, + body: { ok: false, mode: 'on', sent: true, code: 'sent_not_credited', tx_hash: txHash, basescan_url: `${BASESCAN_TX}${txHash}`, ...plan, + error: 'The USDC reached the escrow, and the credit did not go through (for example, not enough confirmations yet). Claim it with POST /api/v1/stake/deposit and this tx_hash.' }, + }; + } + return { + status: 201, + body: { ok: true, mode: 'on', sent: true, tx_hash: txHash, basescan_url: `${BASESCAN_TX}${txHash}`, ...plan, total_active_stake: credited.total_active_stake }, + }; + }); +} + +const AUTH_STATE_ABI = [ + 'function authorizationState(address authorizer, bytes32 nonce) view returns (bool)', + 'function balanceOf(address owner) view returns (uint256)', +]; + +/** The live chain reads, Base Sepolia only. */ +export function rpcGaslessChain(rpcUrl: string = config.baseSepoliaRpc, usdc: string = config.usdcTokenAddress): GaslessChain { + const provider = new ethers.JsonRpcProvider(rpcUrl); + const token = new ethers.Contract(usdc, AUTH_STATE_ABI, provider); + const onBaseSepolia = async () => { + const net = await provider.getNetwork(); + if (Number(net.chainId) !== BASE_SEPOLIA_CHAIN_ID) throw new Error(`chain ${net.chainId} is not Base Sepolia`); + }; + return { + async authorizationState(authorizer, nonce) { + await onBaseSepolia(); + return (await token.getFunction('authorizationState')(authorizer, nonce)) as boolean; + }, + async balanceOf(owner) { + await onBaseSepolia(); + return (await token.getFunction('balanceOf')(owner)) as bigint; + }, + async usdcDomain() { + await onBaseSepolia(); + const d = await resolveAndVerifyDomain(usdc, BASE_SEPOLIA_CHAIN_ID, provider); + return { name: d.name, version: d.version }; + }, + }; +} + +async function accountOfWallet(wallet: string): Promise { + if (!/^0x[0-9a-fA-F]{40}$/.test(wallet)) return null; + const { data, error } = await db.from('builders').select('id').ilike('address', wallet).limit(2); + if (error) throw new Error(error.message); + const rows = (data ?? []) as Array<{ id: string }>; + if (rows.length > 1) throw new Error('more than one account matches this wallet'); + return rows[0] ? String(rows[0].id) : null; +} + +let chainSingleton: GaslessChain | null = null; +const admission = createGaslessAdmission(); + +/** Production wiring. */ +export function defaultGaslessDeps(): GaslessDeps { + const { configuredEscrowAddress } = require('./escrow-refunder') as typeof import('./escrow-refunder'); + return { + mode: gaslessDepositMode(), + escrow: configuredEscrowAddress(), + usdc: config.usdcTokenAddress || USDC_BASE_SEPOLIA, + realStaking: config.realStakingEnabled, + chain: (chainSingleton ??= rpcGaslessChain()), + accountOf: accountOfWallet, + relay: escrowRelayAuthorization, + credit: depositStake, + now: () => Math.floor(Date.now() / 1000), + admit: admission, + }; +} diff --git a/tests/escrow-relay-authorization.test.ts b/tests/escrow-relay-authorization.test.ts new file mode 100644 index 00000000..80c7c42a --- /dev/null +++ b/tests/escrow-relay-authorization.test.ts @@ -0,0 +1,72 @@ +/** + * R3: escrowRelayAuthorization, the escrow's submit of an owner-signed EIP-3009 transfer. Its own + * guards: no signer key → refuses; a payee other than the escrow → refuses before any send; and it + * shares the escrow's one-at-a-time queue with refunds (one nonce). The real send is never reached: + * the relay seam replaces it. + */ +const mockConfig = { + stakeEscrowSignerKey: null as string | null, + stakeEscrowAddress: '0x1111111111111111111111111111111111111111', + usdcTokenAddress: '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + baseSepoliaRpc: 'http://localhost:0', + stakeMinConfirmations: 1, +}; +jest.mock('../src/config', () => ({ config: mockConfig })); + +import { escrowRelayAuthorization, __setAuthorizationRelay, __setEscrowSender, escrowRefund, type Eip3009Authorization } from '../src/services/escrow-refunder'; + +const SIG = '0x' + '11'.repeat(32) + '22'.repeat(32) + '1b'; +const auth = (to = mockConfig.stakeEscrowAddress): Eip3009Authorization => ({ + from: '0x' + '33'.repeat(20), to, value: '1000000', validAfter: '0', validBefore: '9999999999', nonce: '0x' + '44'.repeat(32), +}); + +afterEach(() => { + mockConfig.stakeEscrowSignerKey = null; + __setAuthorizationRelay(); + __setEscrowSender(); +}); + +test('no signer key: refuses, and the relay is never called', async () => { + const relay = jest.fn(); + __setAuthorizationRelay(relay); + await expect(escrowRelayAuthorization(auth(), SIG)).rejects.toThrow(/not configured/); + expect(relay).not.toHaveBeenCalled(); +}); + +test('a payee other than the escrow: refuses before any send', async () => { + mockConfig.stakeEscrowSignerKey = 'k'.repeat(10); + const relay = jest.fn(); + __setAuthorizationRelay(relay); + await expect(escrowRelayAuthorization(auth('0x' + '55'.repeat(20)), SIG)).rejects.toThrow(/does not pay the escrow/); + expect(relay).not.toHaveBeenCalled(); +}); + +test('configured, paying the escrow: relayed, and returns the tx hash', async () => { + mockConfig.stakeEscrowSignerKey = 'k'.repeat(10); + __setAuthorizationRelay(async () => ({ txHash: '0x' + 'ab'.repeat(32) })); + await expect(escrowRelayAuthorization(auth(), SIG)).resolves.toEqual({ txHash: '0x' + 'ab'.repeat(32) }); +}); + +test('shares the escrow queue with refunds: a refund started first finishes before the relay starts', async () => { + mockConfig.stakeEscrowSignerKey = 'k'.repeat(10); + const order: string[] = []; + let release!: () => void; + __setEscrowSender(async () => { + order.push('refund:start'); + await new Promise((r) => (release = r)); + order.push('refund:end'); + return { txHash: '0x' + 'cd'.repeat(32) }; + }); + __setAuthorizationRelay(async () => { + order.push('relay'); + return { txHash: '0x' + 'ab'.repeat(32) }; + }); + const refund = escrowRefund('b', 1n, '0x' + '66'.repeat(20)); + await new Promise((r) => setImmediate(r)); + const relayed = escrowRelayAuthorization(auth(), SIG); + await new Promise((r) => setImmediate(r)); + expect(order).toEqual(['refund:start']); + release(); + await Promise.all([refund, relayed]); + expect(order).toEqual(['refund:start', 'refund:end', 'relay']); +}); diff --git a/tests/gasless-deposit-auth.test.ts b/tests/gasless-deposit-auth.test.ts new file mode 100644 index 00000000..1c211f0b --- /dev/null +++ b/tests/gasless-deposit-auth.test.ts @@ -0,0 +1,28 @@ +/** + * R3: POST /api/v1/stake/deposit/gasless is keyless, because a newcomer has no API key and the + * owner's EIP-3009 signature is the authorization (checked in services/gasless-deposit.ts). The + * bypass is method-gated and exact-path; this pins both, and a control proves the guard can fail. + */ +import { authMiddleware } from '../src/middleware/auth'; + +jest.mock('../src/db', () => ({ db: { from: () => ({}) } })); +jest.mock('../src/auth/api-keys', () => ({ validateAgentApiKey: jest.fn() })); +jest.mock('../src/engine/agent-log', () => ({ logAgentEvent: jest.fn() })); + +async function passesKeyless(method: string, path: string): Promise { + const req: any = { method, path, headers: {}, query: {}, body: {} }; + const res: any = { statusCode: 0, status(c: number) { this.statusCode = c; return this; }, json() { return this; } }; + const next = jest.fn(); + await authMiddleware(req, res, next); + return next.mock.calls.length === 1 && res.statusCode === 0; +} + +test('POST /api/v1/stake/deposit/gasless reaches the route without a key', async () => { + expect(await passesKeyless('POST', '/api/v1/stake/deposit/gasless')).toBe(true); +}); + +test('only that method and that exact path', async () => { + expect(await passesKeyless('GET', '/api/v1/stake/deposit/gasless')).toBe(false); + expect(await passesKeyless('POST', '/api/v1/stake/deposit/gasless/x')).toBe(false); + expect(await passesKeyless('POST', '/api/v1/stake/withdraw')).toBe(false); +}); diff --git a/tests/gasless-deposit.test.ts b/tests/gasless-deposit.test.ts new file mode 100644 index 00000000..11e85a12 --- /dev/null +++ b/tests/gasless-deposit.test.ts @@ -0,0 +1,330 @@ +/** + * R3 (2026-11-16): gasless owner deposit via USDC EIP-3009 transferWithAuthorization. + * + * Real EIP-712 signatures from a throwaway wallet made in this test (ethers.Wallet.createRandom), over + * the same domain the live check uses (Base Sepolia USDC, name "USDC", version "2"). The chain, the + * relay and the credit are fakes, so nothing is read from or sent to a chain. The fake chain keeps a + * nonce set the way the USDC contract does, so replay is tested against "used on chain", not a flag. + */ +import { ethers } from 'ethers'; +import { gaslessDeposit, gaslessDepositMode, createGaslessAdmission, MIN_GASLESS_DEPOSIT, MIN_WINDOW_S, type GaslessDeps } from '../src/services/gasless-deposit'; +import { RefundBroadcastUnconfirmed, type Eip3009Authorization } from '../src/services/escrow-refunder'; + +const USDC = '0x036CbD53842c5426634e7929541eC2318f3dCF7e'; +const ESCROW = ethers.getAddress('0x' + 'e5'.repeat(20)); +const NOW = 1_800_000_000; +const DOMAIN = { name: 'USDC', version: '2', chainId: 84532, verifyingContract: USDC }; +const TYPES = { + TransferWithAuthorization: [ + { name: 'from', type: 'address' }, + { name: 'to', type: 'address' }, + { name: 'value', type: 'uint256' }, + { name: 'validAfter', type: 'uint256' }, + { name: 'validBefore', type: 'uint256' }, + { name: 'nonce', type: 'bytes32' }, + ], +}; + +const owner = ethers.Wallet.createRandom(); +const stranger = ethers.Wallet.createRandom(); + +async function signed(over: Partial = {}, signer: ethers.HDNodeWallet = owner) { + const authorization: Eip3009Authorization = { + from: owner.address, + to: ESCROW, + value: '1000000', + validAfter: '0', + validBefore: String(NOW + 3600), + nonce: ethers.hexlify(ethers.randomBytes(32)), + ...over, + }; + const signature = await signer.signTypedData(DOMAIN, TYPES, authorization); + return { authorization, signature }; +} + +function harness(over: Partial = {}) { + const usedNonces = new Set(); + const relayed: Eip3009Authorization[] = []; + const credits: Array<[string, bigint, string]> = []; + const deps: GaslessDeps = { + mode: 'on', + escrow: ESCROW, + usdc: USDC, + realStaking: true, + chain: { + authorizationState: async (from, nonce) => usedNonces.has(`${from.toLowerCase()}:${nonce.toLowerCase()}`), + balanceOf: async () => 5_000_000n, + usdcDomain: async () => ({ name: 'USDC', version: '2' }), + }, + accountOf: async (w) => (w.toLowerCase() === owner.address.toLowerCase() ? 'acct-owner' : null), + relay: async (a) => { + const k = `${a.from.toLowerCase()}:${a.nonce.toLowerCase()}`; + if (usedNonces.has(k)) throw new Error('FiatTokenV2: authorization is used or canceled'); + usedNonces.add(k); + relayed.push(a); + return { txHash: '0x' + 'ab'.repeat(32) }; + }, + credit: async (w, amount, tx) => { + credits.push([w, amount, tx]); + return { ok: true, builder_id: 'acct-owner', total_active_stake: amount.toString(), authority_after: '0', is_simulated: false, verified: true, tx_hash: tx }; + }, + now: () => NOW, + admit: () => true, + ...over, + }; + return { deps, usedNonces, relayed, credits }; +} + +describe('gasless deposit (EIP-3009)', () => { + // Real time inside verifyEip3009Local; pin it to the same clock the deps use. + beforeAll(() => jest.useFakeTimers({ now: NOW * 1000, doNotFake: ['nextTick', 'setImmediate', 'setTimeout', 'clearTimeout'] })); + afterAll(() => jest.useRealTimers()); + + test('happy path: the escrow submits the owner-signed authorization, then the stake is credited once', async () => { + const h = harness(); + const out = await gaslessDeposit(await signed(), h.deps); + expect(out.status).toBe(201); + expect(out.body).toMatchObject({ ok: true, sent: true, gas_paid_by: 'escrow', amount_micro_usdc: '1000000' }); + expect(h.relayed).toHaveLength(1); + expect(h.credits).toEqual([[owner.address, 1_000_000n, '0x' + 'ab'.repeat(32)]]); + }); + + test('REPLAY: the same authorization sent twice moves USDC once and credits once', async () => { + const h = harness(); + const req = await signed(); + expect((await gaslessDeposit(req, h.deps)).status).toBe(201); + const again = await gaslessDeposit(req, h.deps); + expect(again.status).toBe(409); + expect(again.body).toMatchObject({ ok: false, sent: false, code: 'authorization_used' }); + expect(h.relayed).toHaveLength(1); + expect(h.credits).toHaveLength(1); + }); + + test('REPLAY, concurrent: two simultaneous submissions of one authorization send once', async () => { + const h = harness(); + const req = await signed(); + const [a, b] = await Promise.all([gaslessDeposit(req, h.deps), gaslessDeposit(req, h.deps)]); + expect([a.status, b.status].sort()).toEqual([201, 409]); + expect(h.relayed).toHaveLength(1); + expect(h.credits).toHaveLength(1); + }); + + test('REPLAY: a nonce already used on chain (e.g. by the owner directly) is refused before any send', async () => { + const h = harness(); + const req = await signed(); + h.usedNonces.add(`${owner.address.toLowerCase()}:${req.authorization.nonce.toLowerCase()}`); + const out = await gaslessDeposit(req, h.deps); + expect(out.body).toMatchObject({ code: 'authorization_used', sent: false }); + expect(h.relayed).toHaveLength(0); + }); + + test('EXPIRY: an expired authorization is refused and nothing is sent', async () => { + const h = harness(); + const out = await gaslessDeposit(await signed({ validBefore: String(NOW - 1) }), h.deps); + expect(out.status).toBe(400); + expect(out.body.code).toBe('expired'); + expect(h.relayed).toHaveLength(0); + }); + + test('EXPIRY: an authorization that expires before it could be mined is refused (escrow would pay gas for a revert)', async () => { + const h = harness(); + const out = await gaslessDeposit(await signed({ validBefore: String(NOW + MIN_WINDOW_S - 1) }), h.deps); + expect(out.body.code).toBe('expires_too_soon'); + const ok = await gaslessDeposit(await signed({ validBefore: String(NOW + MIN_WINDOW_S) }), h.deps); + expect(ok.status).toBe(201); + }); + + test('not yet valid (validAfter in the future) is refused', async () => { + const h = harness(); + const out = await gaslessDeposit(await signed({ validAfter: String(NOW + 60) }), h.deps); + expect(out.body.code).toBe('bad_signature'); + expect(h.relayed).toHaveLength(0); + }); + + test('a signature by someone other than `from` is refused', async () => { + const h = harness(); + const out = await gaslessDeposit(await signed({}, stranger), h.deps); + expect(out.status).toBe(400); + expect(out.body.code).toBe('bad_signature'); + expect(h.relayed).toHaveLength(0); + }); + + test('a signature over a different amount than the one sent is refused', async () => { + const h = harness(); + const req = await signed({ value: '1000000' }); + const out = await gaslessDeposit({ ...req, authorization: { ...req.authorization, value: '9000000' } }, h.deps); + expect(out.body.code).toBe('bad_signature'); + expect(h.relayed).toHaveLength(0); + }); + + test('an authorization that does not pay the escrow is refused', async () => { + const h = harness(); + const out = await gaslessDeposit(await signed({ to: stranger.address }), h.deps); + expect(out.body.code).toBe('wrong_recipient'); + expect(h.relayed).toHaveLength(0); + }); + + test('a wallet with no account is refused before the USDC moves (nobody to credit)', async () => { + const h = harness({ accountOf: async () => null }); + const out = await gaslessDeposit(await signed(), h.deps); + expect(out.status).toBe(404); + expect(h.relayed).toHaveLength(0); + }); + + test('a balance below the amount is refused before any send', async () => { + const h = harness(); + h.deps.chain.balanceOf = async () => 999_999n; + const out = await gaslessDeposit(await signed(), h.deps); + expect(out.body.code).toBe('insufficient_balance'); + expect(h.relayed).toHaveLength(0); + }); + + test('an unreadable chain is "not checked", never a send', async () => { + const h = harness(); + h.deps.chain.authorizationState = async () => { throw new Error('rpc down'); }; + const out = await gaslessDeposit(await signed(), h.deps); + expect(out.status).toBe(503); + expect(out.body.code).toBe('not_checked'); + expect(h.relayed).toHaveLength(0); + }); + + test('shadow mode runs every check and sends nothing', async () => { + const h = harness({ mode: 'shadow' }); + const out = await gaslessDeposit(await signed(), h.deps); + expect(out.status).toBe(200); + expect(out.body).toMatchObject({ ok: true, mode: 'shadow', sent: false, would_submit: true }); + expect(h.relayed).toHaveLength(0); + expect(h.credits).toHaveLength(0); + // and a bad one still fails in shadow + expect((await gaslessDeposit(await signed({}, stranger), h.deps)).body.code).toBe('bad_signature'); + }); + + test('off (the default) refuses without reading the chain', async () => { + const h = harness({ mode: 'off' }); + h.deps.chain.authorizationState = async () => { throw new Error('must not be read'); }; + const out = await gaslessDeposit(await signed(), h.deps); + expect(out.status).toBe(503); + expect(out.body.code).toBe('gasless_deposit_off'); + }); + + test('a broadcast with an unknown outcome reports the tx and does not credit', async () => { + const h = harness({ relay: async () => { throw new RefundBroadcastUnconfirmed('0x' + 'cd'.repeat(32), 'timeout'); } }); + const out = await gaslessDeposit(await signed(), h.deps); + expect(out.status).toBe(202); + expect(out.body).toMatchObject({ code: 'sent_unconfirmed', tx_hash: '0x' + 'cd'.repeat(32), sent: 'unknown' }); + expect(h.credits).toHaveLength(0); + }); + + test('sent but the credit refused: 202 with the tx hash, so it can be claimed, never reported as credited', async () => { + const h = harness({ credit: async () => ({ ok: false, builder_id: 'acct-owner', total_active_stake: '0', authority_after: '0', is_simulated: true, error: 'deposit verification failed: 0 confirmations' }) }); + const out = await gaslessDeposit(await signed(), h.deps); + expect(out.status).toBe(202); + expect(out.body).toMatchObject({ ok: false, sent: true, code: 'sent_not_credited' }); + }); + + test('sent, then the credit THROWS: 202 with the tx hash, never a 500 that drops it (Grok r1 lead on #1558)', async () => { + const h = harness({ credit: async () => { throw new Error('connection reset'); } }); + const out = await gaslessDeposit(await signed(), h.deps); + expect(out.status).toBe(202); + expect(out.body).toMatchObject({ ok: false, sent: true, code: 'credit_not_checked', tx_hash: '0x' + 'ab'.repeat(32) }); + }); + + test('DUST: below the 1 USDC floor is refused before any send; the floor itself is accepted (Strix on #1558)', async () => { + const h = harness(); + const dust = await gaslessDeposit(await signed({ value: String(MIN_GASLESS_DEPOSIT - 1n) }), h.deps); + expect(dust.body.code).toBe('bad_amount'); + expect((await gaslessDeposit(await signed({ value: '1' }), h.deps)).body.code).toBe('bad_amount'); + expect(h.relayed).toHaveLength(0); + expect((await gaslessDeposit(await signed({ value: String(MIN_GASLESS_DEPOSIT) }), h.deps)).status).toBe(201); + }); + + test('QUEUE: when the admission budget is spent, 429 and nothing is queued for the escrow (Strix on #1558)', async () => { + const h = harness({ admit: () => false }); + const out = await gaslessDeposit(await signed(), h.deps); + expect(out.status).toBe(429); + expect(out.body).toMatchObject({ code: 'escrow_busy', sent: false }); + expect(h.relayed).toHaveLength(0); + }); + + test('QUEUE: shadow mode and refused deposits use no admission', async () => { + const admit = jest.fn(() => true); + await gaslessDeposit(await signed(), harness({ mode: 'shadow', admit }).deps); + await gaslessDeposit(await signed({}, stranger), harness({ admit }).deps); + expect(admit).not.toHaveBeenCalled(); + }); + + test('QUEUE: a deposit the in-lock re-check refuses takes no admission slot (Grok r3 on #1558)', async () => { + const admit = jest.fn(() => true); + const h = harness({ admit }); + let reads = 0; + h.deps.chain.authorizationState = async () => ++reads > 1; // unused at the pre-check, used by the re-check + const out = await gaslessDeposit(await signed(), h.deps); + expect(out.body.code).toBe('authorization_used'); + expect(admit).not.toHaveBeenCalled(); + expect(h.relayed).toHaveLength(0); + }); + + test('NO LEAK: a chain, relay or credit error never reaches the answer (ethers puts the RPC URL, and any key in it, in its messages)', async () => { + const leak = 'https://rpc.example.invalid/v2/NOT-A-REAL-KEY-123'; + const spy = jest.spyOn(console, 'error').mockImplementation(() => {}); + try { + const bodies: unknown[] = []; + const read = harness(); + read.deps.chain.authorizationState = async () => { throw new Error(`server response 401 ${leak}`); }; + bodies.push((await gaslessDeposit(await signed(), read.deps)).body); + const domain = harness(); + domain.deps.chain.usdcDomain = async () => { throw new Error(`missing response ${leak}`); }; + bodies.push((await gaslessDeposit(await signed(), domain.deps)).body); + bodies.push((await gaslessDeposit(await signed(), harness({ relay: async () => { throw new Error(`could not coalesce ${leak}`); } }).deps)).body); + bodies.push((await gaslessDeposit(await signed(), harness({ credit: async () => { throw new Error(`timeout ${leak}`); } }).deps)).body); + bodies.push((await gaslessDeposit(await signed(), harness({ credit: async () => ({ ok: false, builder_id: 'x', total_active_stake: '0', authority_after: '0', is_simulated: true, error: `deposit verification failed: rpc error fetching receipt: ${leak}` }) }).deps)).body); + for (const b of bodies) expect(JSON.stringify(b)).not.toMatch(/NOT-A-REAL-KEY-123|rpc\.example/); + expect(bodies.map((b: any) => b.code)).toEqual(['not_checked', 'not_checked', 'not_sent', 'credit_not_checked', 'sent_not_credited']); + } finally { + spy.mockRestore(); + } + }); + + test('QUEUE, wired: a second deposit from the same wallet within the minute is 429 and is not sent', async () => { + const h = harness({ admit: createGaslessAdmission(4, 1) }); + expect((await gaslessDeposit(await signed(), h.deps)).status).toBe(201); + const second = await gaslessDeposit(await signed(), h.deps); + expect(second).toMatchObject({ status: 429, body: { code: 'escrow_busy', sent: false } }); + expect(h.relayed).toHaveLength(1); + }); + + test('malformed input is refused', async () => { + const h = harness(); + for (const body of [null, {}, { authorization: {}, signature: '0x' }, { ...(await signed()), signature: 'nope' }]) { + expect((await gaslessDeposit(body, h.deps)).body.code).toBe('bad_authorization'); + } + expect((await gaslessDeposit(await signed({ value: '0' }), h.deps)).body.code).toBe('bad_amount'); + }); +}); + +describe('createGaslessAdmission', () => { + test('admits 4 a minute, process-wide; a minute later it admits again', () => { + const admit = createGaslessAdmission(4); + const t0 = 1_000_000; + expect([0, 1, 2, 3, 4].map((i) => admit(t0 + i * 1000, `0xpayer${i}`))).toEqual([true, true, true, true, false]); + expect(admit(t0 + 59_999, '0xpayer9')).toBe(false); + expect(admit(t0 + 60_000, '0xpayer9')).toBe(true); + }); + + test('one payer gets one slot a minute, so one wallet cannot spend the whole budget (Strix on #1558)', () => { + const admit = createGaslessAdmission(4, 1); + const t0 = 2_000_000; + expect(admit(t0, '0xAbC')).toBe(true); + expect(admit(t0 + 1, '0xabc')).toBe(false); // same wallet, any letter case + expect(admit(t0 + 2, '0xdef')).toBe(true); // another payer still gets in + expect(admit(t0 + 60_000, '0xabc')).toBe(true); + }); +}); + +describe('GASLESS_DEPOSIT_MODE', () => { + test.each([ + [undefined, 'off'], ['', 'off'], ['off', 'off'], ['shadow', 'shadow'], ['on', 'on'], [' ON ', 'on'], ['true', 'off'], ['enforce', 'off'], + ])('%j -> %s', (raw, want) => { + expect(gaslessDepositMode(raw as string | undefined)).toBe(want); + }); +});