Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(payments): implement payment session management and update API

qrqkd43a50a9e20a
diff --git a/api/_lib/migrations/20260626200000_agent_capabilities.sql b/api/_lib/migrations/20260626200000_agent_capabilities.sql
index 97d3cb4bd..6f50b743a 100644
--- a/api/_lib/migrations/20260626200000_agent_capabilities.sql
+++ b/api/_lib/migrations/20260626200000_agent_capabilities.sql
@@ -68,13 +68,13 @@ CREATE TABLE IF NOT EXISTS agent_launched_coins (
UNIQUE (mint, network)
);
CREATE INDEX IF NOT EXISTS idx_launched_coins_agent ON agent_launched_coins(agent_id);
-CREATE INDEX IF NOT EXISTS idx_launched_coins_claim ON agent_launched_coins(agent_id, network) WHERE auto_claim_enabled OR launcher_id IS NOT NULL;
-
-- auto_claim_enabled column convenience (on the launcher drives per-coin default,
-- but allow per-coin override in agent_launched_coins):
ALTER TABLE agent_launched_coins
ADD COLUMN IF NOT EXISTS auto_claim_enabled BOOLEAN NOT NULL DEFAULT false;
+CREATE INDEX IF NOT EXISTS idx_launched_coins_claim ON agent_launched_coins(agent_id, network) WHERE auto_claim_enabled OR launcher_id IS NOT NULL;
+
-- 4. Market maker configs — one per agent per coin
CREATE TABLE IF NOT EXISTS agent_market_maker_configs (
id BIGSERIAL PRIMARY KEY,
diff --git a/api/_lib/pay/payment-session.js b/api/_lib/pay/payment-session.js
index 94a251f1a..78465ab9a 100644
--- a/api/_lib/pay/payment-session.js
+++ b/api/_lib/pay/payment-session.js
@@ -199,6 +199,39 @@ export async function listPaymentSessions(userId, { status, limit = 20, cursor }
};
}
+/**
+ * Update mutable fields on an active session.
+ * Only label, allowed_hosts, and max_per_tx_usd can be changed after creation.
+ * Returns the updated session row or null if not found / not owned / not active.
+ */
+export async function updatePaymentSession(sessionId, userId, { label, allowedHosts, maxPerTxUsd } = {}) {
+ const params = { id: sessionId, userId };
+
+ if (label !== undefined) {
+ params.label = String(label).trim().slice(0, MAX_LABEL_LEN);
+ }
+ if (allowedHosts !== undefined) {
+ params.allowedHosts = normalizeAllowedHosts(allowedHosts);
+ }
+ if (maxPerTxUsd !== undefined) {
+ params.maxPerTxAtomics = maxPerTxUsd != null ? usdToAtomics(normalizeMaxPerTx(maxPerTxUsd)).toString() : null;
+ }
+
+ const [row] = await sql`
+ UPDATE payment_sessions
+ SET
+ label = CASE WHEN ${params.label !== undefined}::boolean THEN ${params.label ?? null} ELSE label END,
+ allowed_hosts = CASE WHEN ${params.allowedHosts !== undefined}::boolean THEN ${params.allowedHosts ?? []} ELSE allowed_hosts END,
+ max_per_tx_usdc = CASE WHEN ${params.maxPerTxAtomics !== undefined}::boolean THEN ${params.maxPerTxAtomics ?? null}::bigint ELSE max_per_tx_usdc END,
+ updated_at = now()
+ WHERE id = ${sessionId} AND user_id = ${userId} AND status = 'active'
+ RETURNING id, user_id, agent_id, label, budget_usdc, spent_usdc,
+ max_per_tx_usdc, allowed_hosts, network, status, expires_at,
+ session_metadata, created_at, updated_at
+ `;
+ return row ? formatSession(row) : null;
+}
+
/**
* Cancel a session. Refunds un-spent budget to the user's credit balance.
*/
diff --git a/api/cron/payment-session-sweep.js b/api/cron/payment-session-sweep.js
new file mode 100644
index 000000000..e9cdf8682
--- /dev/null
+++ b/api/cron/payment-session-sweep.js
@@ -0,0 +1,91 @@
+// GET /api/cron/payment-session-sweep — expire stale sessions and refund budgets.
+//
+// Runs on a schedule (recommended: every 5 minutes). Finds payment sessions whose
+// expires_at has passed but are still 'active', marks them 'expired', and refunds
+// any un-spent budget back to the creator's credit balance.
+//
+// Design:
+// • Processes up to BATCH_LIMIT sessions per tick — the next tick catches the rest.
+// • Refunds are idempotent (ON CONFLICT DO NOTHING on credit_ledger) so retries
+// don't double-credit.
+// • All rows updated atomically per-session; a crash mid-batch leaves the
+// remaining sessions to be picked up on the next tick.
+//
+// Auth: requires CRON_SECRET header matching the CRON_SECRET env var. Same pattern
+// as every other cron in /api/cron/.
+
+import { sql } from '../_lib/db.js';
+import { creditAccount } from '../_lib/credits.js';
+import { atomicsToUsd } from '../_lib/pay/spend-governor.js';
+import { cors, json, wrap } from '../_lib/http.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+
+export const maxDuration = 30;
+
+const BATCH_LIMIT = Number(process.env.PAYMENT_SESSION_SWEEP_BATCH) || 100;
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET;
+ if (!secret) return false; // allow in dev if no secret set
+ const provided = req.headers['x-cron-secret'] || req.headers['authorization']?.replace(/^Bearer\s+/i, '');
+ if (!provided || !constantTimeEquals(provided, secret)) {
+ res.writeHead(401, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ error: 'unauthorized' }));
+ return true; // handled
+ }
+ return false;
+}
+
+export default wrap(async (req, res) => {
+ cors(req, res, { methods: 'GET,POST,OPTIONS' });
+ if (req.method?.toUpperCase() === 'OPTIONS') return;
+ if (requireCron(req, res)) return;
+
+ const t0 = Date.now();
+
+ // Find expired sessions in one query, limiting the batch
+ const expiredRows = await sql`
+ UPDATE payment_sessions
+ SET status = 'expired', updated_at = now()
+ WHERE status = 'active'
+ AND expires_at < now()
+ RETURNING id, user_id, budget_usdc, spent_usdc
+ LIMIT ${BATCH_LIMIT}
+ `;
+
+ let refunded = 0;
+ let refundErrors = 0;
+
+ // Refund un-spent budget for each expired session
+ await Promise.all(expiredRows.map(async (row) => {
+ const refundAtomics = BigInt(row.budget_usdc) - BigInt(row.spent_usdc);
+ if (refundAtomics <= 0n) return;
+
+ try {
+ await creditAccount({
+ userId: row.user_id,
+ amountUsd: atomicsToUsd(refundAtomics),
+ kind: 'refund',
+ action: 'payment_session_expire',
+ refType: 'payment_session',
+ refId: row.id,
+ idempotencyKey: `paysess_expire_${row.id}`,
+ });
+ refunded++;
+ } catch {
+ refundErrors++;
+ }
+ }));
+
+ const durationMs = Date.now() - t0;
+ return json(res, 200, {
+ ok: true,
+ expired: expiredRows.length,
+ refunded,
+ refund_errors: refundErrors,
+ duration_ms: durationMs,
+ note: expiredRows.length === BATCH_LIMIT
+ ? `Batch limit (${BATCH_LIMIT}) reached — more sessions may remain. Next tick will continue.`
+ : null,
+ });
+});
diff --git a/api/pay/execute.js b/api/pay/execute.js
index a20671d06..7de6c6025 100644
--- a/api/pay/execute.js
+++ b/api/pay/execute.js
@@ -9,10 +9,12 @@
// - idempotency_key: caller's dedup key (optional, recommended)
//
// The platform:
-// 1. Verifies the session token and checks governance (budget, allowlist, per-tx cap)
-// 2. Probes the endpoint for its 402 challenge
-// 3. Reserves the amount from the session budget (atomic, race-safe)
-// 4. Signs the Solana USDC transfer with the platform payer wallet
+// 1. Verifies the session token and reads the session's network preference
+// 2. Probes the endpoint for its 402 challenge, selecting the right network accept
+// 3. Enforces governance (budget, allowlist, per-tx cap) and reserves budget atomically
+// 4. Signs the payment using the platform payer wallet for the session's network:
+// • solana → Solana USDC SPL transfer (X402_AGENT_SOLANA_SECRET_BASE58)
+// • base → EIP-3009 transferWithAuthorization via viem (X402_EVM_AGENT_PRIVATE_KEY)
// 5. Presents X-PAYMENT header and returns the endpoint's response
// 6. Records the execution in payment_session_executions
// 7. On failure, rolls back the budget reservation so the session isn't charged
@@ -41,43 +43,61 @@ import { solanaConnection } from '../_lib/solana/connection.js';
import {
usdToAtomics,
atomicsToUsd,
+ verifySessionToken,
reserveSessionSpend,
rollbackReservation,
recordExecution,
SpendGovernorError,
} from '../_lib/pay/spend-governor.js';
+import { createPrivateKeySigner, buildEvmExactPayload } from '../_lib/x402/a2a-client.js';
+
+// Known USDC mint addresses per network
+const USDC_SOLANA_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const USDC_BASE_ADDRESS = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+const BASE_CHAIN_ID = 8453; // eip155:8453
-const USDC_MAINNET_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
const SOLANA_RPC = env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
const FETCH_TIMEOUT_MS = 20_000;
-// ── Platform payer keypair ──────────────────────────────────────────────────
-// Shared with x402-pay.js; loads X402_AGENT_SOLANA_SECRET_BASE58 or falls back
-// to the dev test keypair. This is the wallet that signs session payments on
-// behalf of users — it needs to hold USDC to fund the transfers.
-let _platformKeypair = null;
+// ── Platform payer: Solana ───────────────────────────────────────────────────
+let _solanaKeypair = null;
-function loadPlatformKeypair() {
- if (_platformKeypair) return _platformKeypair;
+function loadSolanaKeypair() {
+ if (_solanaKeypair) return _solanaKeypair;
const b58 = process.env.X402_AGENT_SOLANA_SECRET_BASE58;
if (b58) {
- const raw = bs58.decode(b58);
- _platformKeypair = Keypair.fromSecretKey(raw);
- return _platformKeypair;
+ _solanaKeypair = Keypair.fromSecretKey(bs58.decode(b58));
+ return _solanaKeypair;
}
if (process.env.NODE_ENV !== 'production') {
try {
const arr = JSON.parse(readFileSync('/home/codespace/.config/x402-test-wallets/solana.json', 'utf8'));
- _platformKeypair = Keypair.fromSecretKey(Uint8Array.from(arr));
- return _platformKeypair;
+ _solanaKeypair = Keypair.fromSecretKey(Uint8Array.from(arr));
+ return _solanaKeypair;
} catch { /* fall through */ }
}
- const e = new Error('Platform payer wallet not configured (set X402_AGENT_SOLANA_SECRET_BASE58)');
+ const e = new Error('Platform Solana payer wallet not configured (set X402_AGENT_SOLANA_SECRET_BASE58)');
e.status = 503;
e.code = 'wallet_unconfigured';
throw e;
}
+// ── Platform payer: EVM ──────────────────────────────────────────────────────
+let _evmSigner = null;
+
+async function loadEvmSigner() {
+ if (_evmSigner) return _evmSigner;
+ const privateKey = process.env.X402_EVM_AGENT_PRIVATE_KEY;
+ if (!privateKey) {
+ const e = new Error('Platform EVM payer wallet not configured (set X402_EVM_AGENT_PRIVATE_KEY)');
+ e.status = 503;
+ e.code = 'wallet_unconfigured';
+ throw e;
+ }
+ _evmSigner = await createPrivateKeySigner(privateKey);
+ return _evmSigner;
+}
+
// ── SSRF-guarded fetch ──────────────────────────────────────────────────────
async function guardedFetch(rawUrl, { method = 'GET', headers = {}, body } = {}) {
const url = validatePublicUrl(rawUrl);
@@ -116,11 +136,23 @@ function b64decodeJson(s) {
try { return JSON.parse(Buffer.from(String(s), 'base64').toString('utf8')); } catch { return null; }
}
-// ── Probe a 402 endpoint ────────────────────────────────────────────────────
-async function probe402(url, { method, body }) {
+// Classify a network string into 'solana' | 'base' | 'evm' | 'unknown'
+function classifyNetwork(network) {
+ if (!network) return 'unknown';
+ if (typeof network === 'string' && network.startsWith('solana')) return 'solana';
+ if (network === 'eip155:8453' || network === 'base') return 'base';
+ if (/^eip155:\d+$/.test(network)) return 'evm';
+ return 'unknown';
+}
+
+// ── Probe a 402 endpoint and select the best matching accept ────────────────
+// networkPreference: 'solana' | 'base' | 'evm' — used to pick the right
+// accept from the challenge's offers. Falls back to Solana if preferred network
+// isn't available.
+async function probe402(rawUrl, { method, body, networkPreference = 'solana' }) {
let res;
try {
- res = await guardedFetch(url, { method, body });
+ res = await guardedFetch(rawUrl, { method, body });
} catch (err) {
if (err instanceof SsrfError) {
throw Object.assign(new Error('Target URL is not a reachable public endpoint'), {
@@ -143,40 +175,87 @@ async function probe402(url, { method, body }) {
});
}
- const accept = challenge.accepts.find(
- (a) => typeof a?.network === 'string' && a.network.startsWith('solana'),
- );
- if (!accept) {
- throw Object.assign(new Error('Service has no Solana payment option (only EVM may be supported)'), {
- status: 422, code: 'no_solana_accept',
- detail: { networks: [...new Set(challenge.accepts.map((a) => a?.network).filter(Boolean))] },
- });
- }
-
- // Security: only allow the known Solana USDC mint — no arbitrary SPL tokens
- if (accept.asset !== USDC_MAINNET_MINT) {
- throw Object.assign(new Error('Service requested payment in a non-USDC asset; sessions only pay Solana USDC'), {
- status: 422, code: 'unsupported_asset',
- detail: { asset: accept.asset, expected: USDC_MAINNET_MINT },
- });
- }
-
- if (!accept.extra?.feePayer) {
- throw Object.assign(new Error('Service did not advertise a Solana fee payer'), {
- status: 422, code: 'missing_fee_payer',
- });
+ // Select the accept that matches the session's network preference.
+ // For Solana: look for a solana:* accept with the known USDC mint.
+ // For Base: look for eip155:8453 with the known USDC address.
+ // If the preferred network isn't available, fail clearly — mixing networks
+ // between session policy and endpoint capability is not allowed.
+ let accept = null;
+
+ if (networkPreference === 'solana') {
+ accept = challenge.accepts.find(
+ (a) => typeof a?.network === 'string' &&
+ a.network.startsWith('solana') &&
+ a.asset === USDC_SOLANA_MINT,
+ );
+ if (!accept) {
+ // Accept any Solana option as fallback (validate asset separately)
+ accept = challenge.accepts.find(
+ (a) => typeof a?.network === 'string' && a.network.startsWith('solana'),
+ );
+ }
+ if (!accept) {
+ throw Object.assign(new Error('Service has no Solana payment option; endpoint may be EVM-only'), {
+ status: 422, code: 'no_solana_accept',
+ detail: { networks: [...new Set(challenge.accepts.map((a) => a?.network).filter(Boolean))] },
+ });
+ }
+ if (accept.asset !== USDC_SOLANA_MINT) {
+ throw Object.assign(new Error(`Service requested payment in a non-USDC asset (${accept.asset})`), {
+ status: 422, code: 'unsupported_asset',
+ detail: { asset: accept.asset, expected: USDC_SOLANA_MINT },
+ });
+ }
+ if (!accept.extra?.feePayer) {
+ throw Object.assign(new Error('Solana 402 challenge is missing feePayer'), {
+ status: 422, code: 'missing_fee_payer',
+ });
+ }
+ } else if (networkPreference === 'base') {
+ accept = challenge.accepts.find(
+ (a) => (a?.network === 'eip155:8453' || a?.network === 'base') &&
+ typeof a?.asset === 'string' &&
+ a.asset.toLowerCase() === USDC_BASE_ADDRESS.toLowerCase(),
+ );
+ if (!accept) {
+ // Fall back to any EVM accept on Base
+ accept = challenge.accepts.find(
+ (a) => a?.network === 'eip155:8453' || a?.network === 'base',
+ );
+ }
+ if (!accept) {
+ throw Object.assign(new Error('Service has no Base/EVM payment option; endpoint may be Solana-only'), {
+ status: 422, code: 'no_evm_accept',
+ detail: { networks: [...new Set(challenge.accepts.map((a) => a?.network).filter(Boolean))] },
+ });
+ }
+ if (accept.asset?.toLowerCase() !== USDC_BASE_ADDRESS.toLowerCase()) {
+ throw Object.assign(new Error(`Service requested payment in a non-USDC EVM asset (${accept.asset})`), {
+ status: 422, code: 'unsupported_asset',
+ detail: { asset: accept.asset, expected: USDC_BASE_ADDRESS },
+ });
+ }
+ } else {
+ // Unknown network preference — try to find any Solana accept first, then any EVM
+ accept = challenge.accepts.find((a) => typeof a?.network === 'string' && a.network.startsWith('solana'))
+ || challenge.accepts[0];
+ if (!accept) {
+ throw Object.assign(new Error('Service has no recognized payment options'), {
+ status: 422, code: 'no_accept',
+ });
+ }
}
const resource =
challenge.resource && typeof challenge.resource === 'object'
? challenge.resource
- : { url: typeof challenge.resource === 'string' ? challenge.resource : url };
+ : { url: typeof challenge.resource === 'string' ? challenge.resource : rawUrl };
return { challenge, accept, resource };
}
// ── Build and sign the Solana USDC transfer ─────────────────────────────────
-async function buildPaymentPayload({ accept, buyer, conn, resourceUrl }) {
+async function buildSolanaPayload({ accept, buyer, conn, resourceUrl }) {
const mint = new PublicKey(accept.asset);
const payTo = new PublicKey(accept.payTo);
const feePayer = new PublicKey(accept.extra.feePayer);
@@ -224,6 +303,28 @@ async function buildPaymentPayload({ accept, buyer, conn, resourceUrl }) {
};
}
+// ── Build and sign an EVM EIP-3009 transferWithAuthorization ────────────────
+async function buildEvmPayload({ accept, signer, resourceUrl }) {
+ const payload = await buildEvmExactPayload({
+ accept,
+ signer,
+ resource: { url: resourceUrl, mimeType: 'application/json' },
+ });
+ return payload;
+}
+
+// Explorer URL for a given tx hash and network
+function explorerUrl(txHash, network) {
+ if (!txHash) return null;
+ if (typeof network === 'string' && network.startsWith('solana')) {
+ return `https://solscan.io/tx/${txHash}`;
+ }
+ if (network === 'eip155:8453' || network === 'base') {
+ return `https://basescan.org/tx/${txHash}`;
+ }
+ return null;
+}
+
// ── Main handler ─────────────────────────────────────────────────────────────
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
@@ -247,7 +348,6 @@ export default wrap(async (req, res) => {
const requestBody = method === 'POST' ? body.body ?? null : null;
const idempotencyKey = body.idempotency_key ?? null;
- // Validate the URL is reachable (not SSRF)
try {
validatePublicUrl(targetUrl);
} catch {
@@ -256,10 +356,24 @@ export default wrap(async (req, res) => {
const t0 = Date.now();
+ // Phase 0: peek at the session to know the network preference before probing.
+ // This is a read-only lookup — the atomic reservation happens later in phase 3.
+ let sessionPreview;
+ try {
+ sessionPreview = await verifySessionToken(sessionToken);
+ } catch (err) {
+ if (err instanceof SpendGovernorError) {
+ return error(res, err.status, err.code, err.message, err.detail);
+ }
+ throw err;
+ }
+
+ const networkPreference = classifyNetwork(sessionPreview.network) === 'base' ? 'base' : 'solana';
+
// Phase 1: probe the endpoint for its 402 challenge
let probeResult;
try {
- probeResult = await probe402(targetUrl, { method, body: requestBody });
+ probeResult = await probe402(targetUrl, { method, body: requestBody, networkPreference });
} catch (err) {
return error(res, err.status ?? 502, err.code ?? 'probe_failed', err.message, err.detail);
}
@@ -275,11 +389,11 @@ export default wrap(async (req, res) => {
});
}
- const { accept, resource, challenge } = probeResult;
+ const { accept, resource } = probeResult;
const amountAtomics = BigInt(accept.amount);
const amountUsd = atomicsToUsd(amountAtomics);
- // Phase 2: governance enforcement — check session, allowlist, budget
+ // Phase 2: governance enforcement — check session, allowlist, budget (atomic)
let sessionRecord, reservationId;
try {
const reservation = await reserveSessionSpend({
@@ -296,28 +410,50 @@ export default wrap(async (req, res) => {
throw err;
}
- // Phase 3: load platform payer and sign
- let keypair;
- try {
- keypair = loadPlatformKeypair();
- } catch (err) {
- // Roll back — we reserved but can't sign
- await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});
- return error(res, 503, 'wallet_unconfigured', 'Platform payment wallet is not configured');
- }
-
- const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
+ // Phase 3: load platform payer and build the signed payment payload
let paymentPayload;
- try {
- paymentPayload = await buildPaymentPayload({
- accept,
- buyer: keypair,
- conn,
- resourceUrl: resource.url,
- });
- } catch (err) {
- await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});
- return error(res, 502, 'build_failed', `Failed to build payment: ${err?.message}`);
+ let payerAddress;
+
+ if (networkPreference === 'base') {
+ let signer;
+ try {
+ signer = await loadEvmSigner();
+ } catch (err) {
+ await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});
+ return error(res, 503, 'wallet_unconfigured', 'Platform EVM payment wallet is not configured');
+ }
+ payerAddress = signer.address;
+ try {
+ paymentPayload = await buildEvmPayload({
+ accept,
+ signer,
+ resourceUrl: resource.url || targetUrl,
+ });
+ } catch (err) {
+ await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});
+ return error(res, 502, 'build_failed', `Failed to build EVM payment: ${err?.message}`);
+ }
+ } else {
+ let keypair;
+ try {
+ keypair = loadSolanaKeypair();
+ } catch (err) {
+ await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});
+ return error(res, 503, 'wallet_unconfigured', 'Platform Solana payment wallet is not configured');
+ }
+ payerAddress = keypair.publicKey.toBase58();
+ const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
+ try {
+ paymentPayload = await buildSolanaPayload({
+ accept,
+ buyer: keypair,
+ conn,
+ resourceUrl: resource.url || targetUrl,
+ });
+ } catch (err) {
+ await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});
+ return error(res, 502, 'build_failed', `Failed to build Solana payment: ${err?.message}`);
+ }
}
const xPayment = Buffer.from(JSON.stringify(paymentPayload)).toString('base64');
@@ -332,7 +468,6 @@ export default wrap(async (req, res) => {
});
} catch (err) {
// Network failure AFTER signing — chain state unknown, do NOT roll back.
- // The wallet may have been debited. Record as 'failed' in the audit log.
await recordExecution({
sessionId: sessionRecord.id,
userId: sessionRecord.user_id,
@@ -341,7 +476,7 @@ export default wrap(async (req, res) => {
amountAtomics,
network: accept.network,
txHash: null,
- payerAddress: keypair.publicKey.toBase58(),
+ payerAddress,
payeeAddress: accept.payTo,
status: 'failed',
errorCode: 'settle_uncertain',
@@ -355,37 +490,36 @@ export default wrap(async (req, res) => {
const paidJson = safeJson(paid.text) ?? paid.text;
const settled = b64decodeJson(paid.headers.get('x-payment-response'));
- const txHash = settled?.transaction || null;
- const payer = settled?.payer || keypair.publicKey.toBase58();
+ const txHash = settled?.transaction || settled?.txHash || null;
+ const payer = settled?.payer || payerAddress;
const durationMs = Date.now() - t0;
- // Handle endpoint rejection after payment attempt
- if (!paid.ok) {
- if (paid.status === 402) {
- // Explicit pre-settlement rejection — no funds moved, safe to roll back
- await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});
- await recordExecution({
- sessionId: sessionRecord.id,
- userId: sessionRecord.user_id,
- endpointUrl: targetUrl,
- method,
- amountAtomics,
- network: accept.network,
- txHash: null,
- payerAddress: payer,
- payeeAddress: accept.payTo,
- status: 'failed',
- errorCode: 'payment_rejected',
- errorMessage: 'Service rejected the payment before settlement',
- durationMs,
- idempotencyKey,
- }).catch(() => {});
- return error(res, 402, 'payment_rejected',
- 'Service rejected the payment before settlement — budget has been restored.',
- typeof paidJson === 'object' ? paidJson : null);
- }
+ // Explicit pre-settlement rejection — no funds moved, safe to roll back
+ if (paid.status === 402) {
+ await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});
+ await recordExecution({
+ sessionId: sessionRecord.id,
+ userId: sessionRecord.user_id,
+ endpointUrl: targetUrl,
+ method,
+ amountAtomics,
+ network: accept.network,
+ txHash: null,
+ payerAddress: payer,
+ payeeAddress: accept.payTo,
+ status: 'failed',
+ errorCode: 'payment_rejected',
+ errorMessage: 'Service rejected the payment before settlement',
+ durationMs,
+ idempotencyKey,
+ }).catch(() => {});
+ return error(res, 402, 'payment_rejected',
+ 'Service rejected the payment before settlement — budget has been restored.',
+ typeof paidJson === 'object' ? paidJson : null);
+ }
- // Non-402 error after payment — chain state uncertain
+ // Non-402 non-success — chain state uncertain
+ if (!paid.ok) {
await recordExecution({
sessionId: sessionRecord.id,
userId: sessionRecord.user_id,
@@ -435,11 +569,11 @@ export default wrap(async (req, res) => {
payer,
pay_to: accept.payTo,
tx_hash: txHash,
- explorer: txHash ? `https://solscan.io/tx/${txHash}` : null,
+ explorer: explorerUrl(txHash, accept.network),
},
session: {
id: sessionRecord.id,
- spent_usd: atomicsToUsd(sessionRecord.spent_usdc),
+ spent_usd: atomicsToUsd(BigInt(sessionRecord.spent_usdc)),
remaining_usd: atomicsToUsd(
BigInt(sessionRecord.budget_usdc) - BigInt(sessionRecord.spent_usdc),
),
diff --git a/api/pay/session.js b/api/pay/session.js
index 5019be421..6d583d969 100644
--- a/api/pay/session.js
+++ b/api/pay/session.js
@@ -7,6 +7,7 @@
//
// POST /api/pay/session — create a new session
// GET /api/pay/session/:id — inspect a session (owner only)
+// PATCH /api/pay/session/:id — update label / allowlist / per-tx cap
// DELETE /api/pay/session/:id — cancel + refund un-spent budget
// GET /api/pay/session/:id/executions — list payments made in a session
// GET /api/pay/session — list all sessions for the caller
@@ -19,6 +20,7 @@ import {
getPaymentSession,
listPaymentSessions,
cancelPaymentSession,
+ updatePaymentSession,
listSessionExecutions,
getPaymentStats,
} from '../_lib/pay/payment-session.js';
@@ -40,7 +42,7 @@ function parsePath(req) {
}
export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+ if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS', credentials: true })) return;
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
@@ -125,6 +127,24 @@ export default wrap(async (req, res) => {
return json(res, 200, { session });
}
+ // PATCH /api/pay/session/:id — update mutable fields on an active session
+ if (httpMethod === 'PATCH') {
+ const body = await readJson(req, res);
+ if (!body) return;
+
+ const updates = {};
+ if (typeof body.label === 'string') updates.label = body.label.trim();
+ if (Array.isArray(body.allowed_hosts)) updates.allowedHosts = body.allowed_hosts;
+ if (body.max_per_tx_usd !== undefined) updates.maxPerTxUsd = body.max_per_tx_usd;
+ if (Object.keys(updates).length === 0) {
+ return error(res, 400, 'nothing_to_update', 'Provide at least one of: label, allowed_hosts, max_per_tx_usd');
+ }
+
+ const result = await updatePaymentSession(id, user.id, updates);
+ if (!result) return error(res, 404, 'not_found', 'session not found, not active, or not owned by you');
+ return json(res, 200, { session: result });
+ }
+
// DELETE /api/pay/session/:id
if (httpMethod === 'DELETE') {
const result = await cancelPaymentSession(id, user.id);
diff --git a/packages/agentcore-payments-mcp/README.md b/packages/agentcore-payments-mcp/README.md
new file mode 100644
index 000000000..0a243b965
--- /dev/null
+++ b/packages/agentcore-payments-mcp/README.md
@@ -0,0 +1,140 @@
+# @three-ws/agentcore-payments-mcp
+
+MCP server for three.ws Agent Payment Sessions — govern agent x402 spending without exposing private keys.
+
+## Concept
+
+> The agent does not hold a wallet. It proposes spend. Governance enforces policy.
+
+A **Payment Session** is a budget envelope you fund once from your three.ws credits. You hand an agent the session bearer token; the agent calls paid x402 endpoints through this server. The platform's wallet signs every transaction. The session's allowlist, per-transaction ceiling, and total budget are enforced atomically on the server — the agent can never overspend.
+
+## Quick start
+
+```bash
+# Configure
+export THREE_WS_SESSION="__Host-sid=<your-session-cookie>"
+export PAYMENT_SESSION_TOKEN="pss_<session-id>_<random>"
+
+# Run
+npx @three-ws/agentcore-payments-mcp
+```
+
+MCP client config (`~/.cursor/mcp.json`, Claude Desktop, etc.):
+
+```json
+{
+ "mcpServers": {
+ "three-ws-payments": {
+ "command": "npx",
+ "args": ["-y", "@three-ws/agentcore-payments-mcp"],
+ "env": {
+ "THREE_WS_SESSION": "__Host-sid=...",
+ "PAYMENT_SESSION_TOKEN": "pss_..."
+ }
+ }
+ }
+}
+```
+
+## Environment variables
+
+| Variable | Required | Description |
+|---|---|---|
+| `THREE_WS_SESSION` | For session management tools | Browser session cookie (`__Host-sid=...`) for creating/listing/cancelling sessions |
+| `PAYMENT_SESSION_TOKEN` | For `pay_with_session` default | Bearer token returned when you created a session; passed as the default when no inline token is provided |
+| `THREE_WS_BASE` | No | Base URL (default: `https://three.ws`) |
+| `THREE_WS_TIMEOUT_MS` | No | Request timeout in ms (default: 30000) |
+
+## Tools
+
+### `create_payment_session`
+Create a new session funded from your credits.
+
+```json
+{
+ "budget_usd": 10.00,
+ "label": "Research agent — June sprint",
+ "expiry_seconds": 86400,
+ "max_per_tx_usd": 0.50,
+ "allowed_hosts": ["api.example.com", "data.provider.io"],
+ "network": "solana"
+}
+```
+
+Returns `{ session, token }`. **The token is shown once — store it immediately.**
+
+### `pay_with_session`
+Pay an x402 endpoint using a session token. The platform wallet signs; your session's policy is enforced.
+
+```json
+{
+ "url": "https://api.example.com/data",
+ "method": "GET",
+ "session_token": "pss_...",
+ "idempotency_key": "run-42-fetch-data"
+}
+```
+
+Returns `{ ok, paid, result, payment, session }` with the tx hash, explorer link, and updated budget.
+
+If `session_token` is omitted, the `PAYMENT_SESSION_TOKEN` env var is used.
+
+### `check_payment_session`
+Inspect a session's budget, status, and recent payments.
+
+```json
+{ "session_id": "...", "include_executions": true }
+```
+
+### `list_payment_sessions`
+List all sessions for the authenticated user, with aggregate stats.
+
+```json
+{ "status": "active", "limit": 20 }
+```
+
+### `cancel_payment_session`
+Cancel a session and refund the un-spent budget to your credits.
+
+```json
+{ "session_id": "..." }
+```
+
+## Network support
+
+| Session `network` | Platform payer | USDC contract |
+|---|---|---|
+| `solana` (default) | `X402_AGENT_SOLANA_SECRET_BASE58` | Solana mainnet USDC |
+| `base` | `X402_EVM_AGENT_PRIVATE_KEY` | Base mainnet USDC (0x8335…) |
+
+## Integrating with `@three-ws/x402-mcp`
+
+The existing `pay_and_call` tool in `@three-ws/x402-mcp` now accepts `session_token` directly:
+
+```json
+{
+ "url": "https://api.example.com/endpoint",
+ "session_token": "pss_...",
+ "confirm": true
+}
+```
+
+This routes the payment through `/api/pay/execute` instead of signing locally — the session's governance policy applies.
+
+## Session lifecycle
+
+```
+create (budget debited from credits)
+ └─ active → pay_with_session calls spend against budget
+ ├─ exhausted (budget fully consumed)
+ ├─ expired (TTL elapsed — cron refunds remaining budget)
+ └─ cancelled (manual — remaining budget refunded immediately)
+```
+
+## Security properties
+
+- **No key exposure**: the session token is a time-bounded, HMAC-signed grant. Compromising it lets an attacker spend up to the remaining budget at allowed hosts — nothing more.
+- **Atomic budget enforcement**: concurrent payments use a SQL `UPDATE … WHERE remaining >= amount RETURNING` — two simultaneous requests can never collectively overspend.
+- **Allowlist**: if `allowed_hosts` is set, the governor rejects any request to a host not on the list before signing.
+- **Per-transaction cap**: `max_per_tx_usd` prevents a single large payment draining the entire budget.
+- **SSRF protection**: all x402 target URLs are validated against a public-IP allowlist and DNS-resolved server-side before any payment is signed.
diff --git a/packages/x402-mcp/src/tools/pay-and-call.js b/packages/x402-mcp/src/tools/pay-and-call.js
index 506d8e6d2..7454a2eb2 100644
--- a/packages/x402-mcp/src/tools/pay-and-call.js
+++ b/packages/x402-mcp/src/tools/pay-and-call.js
@@ -1,6 +1,12 @@
// `pay_and_call` — pay an x402 endpoint in USDC from the local Solana wallet and
// return its result. EXECUTION tool: it moves real money.
//
+// Two payment modes:
+// 1. Self-custodial (default): signs with SOLANA_SECRET_KEY / `secret` arg.
+// 2. Session-governed: when `session_token` is supplied, routes through the
+// three.ws /api/pay/execute endpoint — the platform wallet signs, and the
+// session's budget/allowlist/per-tx policy is enforced. No key needed.
+//
// Guards before any payment: probe the 402 to read the Solana price, refuse if it
// exceeds max_usd or MAX_PAY_USD, and (when REQUIRE_CONFIRM is on) require an
// explicit confirm:true. Payment + settlement are done by the real @x402/* libs.
@@ -8,7 +14,7 @@
import { z } from 'zod';
import { buildPayingFetch, decodeSettlement, probeChallenge, isThreeAccept, isUsdcAccept } from '../lib/x402-buyer.js';
-import { MAX_PAY_USD, REQUIRE_CONFIRM, SOLANA_DEFAULT_SECRET } from '../config.js';
+import { MAX_PAY_USD, REQUIRE_CONFIRM, SOLANA_DEFAULT_SECRET, THREE_WS_BASE, HTTP_TIMEOUT_MS } from '../config.js';
// Split a challenge's Solana accepts into the two main assets so we can price
// and pay in the caller's chosen token.
@@ -34,31 +40,96 @@ export const def = {
// Moves real funds — irreversible transfer.
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
description:
- 'Call a paid x402 endpoint and settle the payment automatically from your Solana wallet (SOLANA_SECRET_KEY or a per-call `secret`), then return the result. Pay in USDC (default) or, when the endpoint advertises it, in $THREE — set token:"three". Bounded by max_usd and the MAX_PAY_USD cap (priced off the endpoint\'s USDC quote); refuses before any money moves if the price is over the cap. With REQUIRE_CONFIRM on (default), the call refuses until re-issued with confirm:true. Settles the Solana (solana:*) requirement via the `exact` scheme.',
+ 'Call a paid x402 endpoint and settle the payment automatically, then return the result.\n\nTwo modes:\n• Self-custodial (default): signs with SOLANA_SECRET_KEY or `secret` arg — you hold the key.\n• Session-governed: pass `session_token` (a three.ws Payment Session token) — the platform wallet signs on your behalf; the session\'s budget, allowlist, and per-tx cap are enforced by the platform. No private key required. Supports Solana USDC and Base USDC sessions.\n\nPay in USDC (default) or, when the endpoint advertises it, in $THREE (set token:"three"). Bounded by max_usd and the MAX_PAY_USD cap; refuses before any money moves if the price is over the cap. With REQUIRE_CONFIRM on, the call refuses until re-issued with confirm:true.',
inputSchema: {
url: z.string().url().describe('The x402 endpoint to pay and call.'),
method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method.'),
body: z.record(z.any()).optional().describe('JSON body for POST requests.'),
+ session_token: z
+ .string()
+ .optional()
+ .describe('three.ws Payment Session token (pss_…). When provided, the platform wallet pays — no local key needed. Overrides `secret`.'),
token: z
.enum(['usdc', 'three'])
.default('usdc')
- .describe('Settlement token. "usdc" (default) or "three" — the $THREE platform token; the endpoint must advertise it.'),
+ .describe('Settlement token. "usdc" (default) or "three" — the $THREE platform token; the endpoint must advertise it. Ignored when session_token is set.'),
max_usd: z
.number()
.positive()
.optional()
.describe('Hard ceiling for THIS call in USD. Can only lower the MAX_PAY_USD cap, never raise it.'),
- secret: z.string().optional().describe('Per-call base58 signer override (defaults to SOLANA_SECRET_KEY).'),
+ secret: z.string().optional().describe('Per-call base58 signer override (defaults to SOLANA_SECRET_KEY). Ignored when session_token is set.'),
confirm: z.boolean().optional().describe('Must be true to execute when REQUIRE_CONFIRM is on.'),
+ idempotency_key: z.string().optional().describe('Deduplication key for this call. Recommended when using session_token to avoid double-charges on retries.'),
},
async handler(args) {
const url = String(args?.url ?? '').trim();
const method = args?.method === 'POST' ? 'POST' : 'GET';
+
+ // ── Session-governed mode ───────────────────────────────────────────
+ // When a session_token is provided, delegate everything to the three.ws
+ // /api/pay/execute endpoint: probing, governance, signing, and settlement.
+ // No local wallet needed.
+ const sessionToken = args?.session_token || process.env.PAYMENT_SESSION_TOKEN || '';
+ if (sessionToken) {
+ const ceiling = Math.min(MAX_PAY_USD, args?.max_usd ?? Infinity);
+
+ if (REQUIRE_CONFIRM && args?.confirm !== true) {
+ // We don't know the exact price without probing — let the user confirm intent.
+ return {
+ ok: false,
+ error: 'confirm_required',
+ message: `This will spend up to $${ceiling} (session-governed) on ${url}. Re-issue with confirm:true to proceed (or set REQUIRE_CONFIRM=0).`,
+ mode: 'session',
+ url,
+ };
+ }
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);
+ let res, text;
+ try {
+ res = await fetch(`${THREE_WS_BASE}/api/pay/execute`, {
+ method: 'POST',
+ signal: controller.signal,
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify({
+ session_token: sessionToken,
+ url,
+ method,
+ body: args?.body ?? undefined,
+ idempotency_key: args?.idempotency_key ?? undefined,
+ }),
+ });
+ text = await res.text();
+ } catch (err) {
+ throw Object.assign(new Error(`Session payment failed: ${err?.message}`), {
+ code: 'session_execute_failed',
+ });
+ } finally {
+ clearTimeout(timer);
+ }
+
+ let result;
+ try { result = text ? JSON.parse(text) : null; } catch { result = text; }
+
+ if (!res.ok) {
+ throw Object.assign(
+ new Error(result?.message || result?.error || `Session execute returned HTTP ${res.status}`),
+ { code: result?.code || 'session_execute_failed', status: res.status, body: result },
+ );
+ }
+
+ return { ...result, mode: 'session' };
+ }
+
+ // ── Self-custodial mode ─────────────────────────────────────────────
const secret = args?.secret || SOLANA_DEFAULT_SECRET;
if (!secret) {
- throw Object.assign(new Error('No signer configured. Set SOLANA_SECRET_KEY or pass `secret`.'), {
- code: 'no_signer',
- });
+ throw Object.assign(
+ new Error('No signer configured. Set SOLANA_SECRET_KEY / pass `secret`, or provide a `session_token` for session-governed payments.'),
+ { code: 'no_signer' },
+ );
}
// Probe first so we never pay blind and can enforce the cap pre-payment.
@@ -86,9 +157,6 @@ export const def = {
code: 'three_not_offered',
});
}
- // Cap is always priced off the USDC quote (the dollar value); $THREE amounts
- // are token counts, not USD. If only $THREE is offered, the USD price is
- // unknown and the cap can't bind — confirm:true is then the only gate.
const priceUsd = usdFromAccept(usdc);
const ceiling = Math.min(MAX_PAY_USD, args?.max_usd ?? Infinity);
if (priceUsd != null && priceUsd > ceiling) {
@@ -104,6 +172,7 @@ export const def = {
ok: false,
error: 'confirm_required',
message: `This will spend up to ${spendLabel} on ${url}. Re-issue with confirm:true to proceed (or set REQUIRE_CONFIRM=0).`,
+ mode: 'self_custodial',
token,
price_usd: priceUsd,
...(threeAmount ? { three_amount: threeAmount } : {}),
@@ -136,6 +205,7 @@ export const def = {
return {
ok: true,
paid: true,
+ mode: 'self_custodial',
url,
payer: address,
token,
diff --git a/public/nav-data.js b/public/nav-data.js
index dfe48a90c..fd44e6fdd 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -315,6 +315,7 @@ export const NAV_GROUPS = [
{ title: 'Tutorials', href: '/tutorials', desc: 'Step-by-step guides' },
{ title: 'Chat', href: '/chat', desc: 'Talk to your agent' },
{ title: 'Pay', href: '/pay', desc: 'Agent payments — x402 + USDC' },
+ { title: 'Payment Sessions', href: '/payments', desc: 'Governed agent spend budgets — no private key needed' },
{ title: 'Credits', href: '/credits', desc: 'Top up & spend — SOL or $THREE' },
{
title: 'Avatar SDK',
diff --git a/src/dashboard-next/nav.js b/src/dashboard-next/nav.js
index c96f4fe6a..d7dbf059b 100644
--- a/src/dashboard-next/nav.js
+++ b/src/dashboard-next/nav.js
@@ -37,6 +37,7 @@ export const NAV = [
{ path: '/dashboard/analytics', label: 'Analytics', icon: 'chart', group: 'Monetize', tags: ['revenue', 'charts', 'metrics', 'funnel', 'performance', 'views', 'engagement'] },
{ path: '/dashboard/creator', label: 'Creator Studio', icon: 'creator', group: 'Monetize', tags: ['creator', 'earnings', 'pricing', 'price', 'payout', 'royalties', 'skill analytics', 'sell', 'income', 'make money', '$three discount'] },
{ path: '/dashboard/monetize', label: 'Monetize', icon: 'coin', group: 'Monetize', tags: ['revenue', 'payments', 'subscriptions', 'withdrawals', 'earnings', 'plan', 'billing'] },
+ { path: '/payments', label: 'Payment Sessions', icon: 'paysess', group: 'Monetize', tags: ['x402', 'agent pay', 'session', 'budget', 'usdc', 'autonomous', 'mcp', 'spend', 'governed'], external: true },
{ path: '/dashboard/transactions',label: 'Transactions', icon: 'receipt', group: 'Monetize', tags: ['history', 'purchases', 'sales', 'receipts', 'ledger', 'orders', 'spent', 'earned', 'invoice', 'transaction history', 'buys', 'csv'] },
{ path: '/dashboard/tokens', label: 'Tokens', icon: 'token', group: 'Monetize', tags: ['pump.fun', 'launch', 'bonding curve', 'royalties', 'trade'] },
{ path: '/dashboard/copy', label: 'Copy Trading', icon: 'live', group: 'Monetize', tags: ['copy', 'copy-trade', 'mirror', 'leader', 'follow', 'traders', 'intents', 'pump.fun', 'sniper'] },
@@ -104,6 +105,7 @@ export const ICONS = {
gift: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="8" width="14" height="9" rx="1.5"/><path d="M3 11h14M10 8v9"/><path d="M10 8S8.5 4.5 6.5 4.5a2 2 0 000 4H10zM10 8s1.5-3.5 3.5-3.5a2 2 0 010 4H10z"/></svg>',
pin: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2a5 5 0 015 5c0 3.5-5 11-5 11S5 10.5 5 7a5 5 0 015-5z"/><circle cx="10" cy="7" r="1.8"/></svg>',
receipt: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 2.5h10v15l-2-1.2-2 1.2-2-1.2-2 1.2-2-1.2V2.5z"/><path d="M8 6.5h4M8 9.5h4M8 12.5h2.5"/></svg>',
+ paysess: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="5" width="16" height="10" rx="2"/><path d="M2 8.5h16"/><circle cx="6" cy="12" r="1.2" fill="currentColor" stroke="none"/><path d="M9.5 12h5"/></svg>',
};
/** Resolve the route for the current pathname (exact match wins; falls back to startsWith). */
diff --git a/vercel.json b/vercel.json
index 2949ee5ef..0ca13800f 100644
--- a/vercel.json
+++ b/vercel.json
@@ -82,6 +82,9 @@
"api/cron/reflect-sweep.js": {
"maxDuration": 120
},
+ "api/cron/payment-session-sweep.js": {
+ "maxDuration": 30
+ },
"api/cron/oracle-score.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 120
@@ -4327,6 +4330,10 @@
}
],
"crons": [
+ {
+ "path": "/api/cron/payment-session-sweep",
+ "schedule": "*/5 * * * *"
+ },
{
"path": "/api/cron/avaturn-seed-cron",
"schedule": "* * * * *"