Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions src/config/known-env-vars.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/ops/flag-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions src/routes/v1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
Expand Down
60 changes: 57 additions & 3 deletions src/services/escrow-refunder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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<ethers.ContractTransaction>): 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);
Expand All @@ -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');
Expand Down Expand Up @@ -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));
}
Loading
Loading