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(legal): require a signed ToS, Risk Disclosure, and Agent Wallet Agreement before any real-funds action

nirholas099e3a1837f6
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 5d60616be..5ad1789f4 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -254,7 +254,7 @@ bottom.
| Alpha Co-pilot (the agent narrates its own read) | page [pages/alpha-copilot.html](pages/alpha-copilot.html) `→ /alpha-copilot`, client [src/alpha-copilot.js](src/alpha-copilot.js), styles [src/alpha-copilot.css](src/alpha-copilot.css), profile cross-link [src/shared/alpha-copilot-link.js](src/shared/alpha-copilot-link.js), server [api/agents/alpha.js](api/agents/alpha.js) `→ GET /api/agents/:id/alpha/candidates` + `POST /api/agents/:id/alpha/read`, grounding + scrub [api/\_lib/alpha-read.js](api/_lib/alpha-read.js) | Live | The intelligence and voice layer on the same trade rails the Trading Copilot uses: pick a public agent from a real gallery, pick a real live pump.fun mint off the candidate feed, and the agent reads it in character while its `<agent-3d>` avatar speaks the verdict aloud (agent TTS provider, then the free server lane, then browser speech). Every figure it says is validated against the `signals` bundle the server actually fetched (bonding-curve state, a real non-binding reference buy quote for true price impact, graduation progress, smart-money wallets, and for the owner the wallet balance and spend limits); a mismatch replaces the line and raises `hallucination_guard.line_replaced`, which the page surfaces rather than hides. The narrator never signs: acting on a read is an owner-only drawer that re-quotes through `previewAgentTrade` and executes through `executeAgentTrade`, so the spend policy, firewall, and custody audit all still apply. Docs: [docs/alpha-copilot.md](docs/alpha-copilot.md) |
| Social recovery & inheritance (guardian console) | page [pages/guardian.html](pages/guardian.html) `-> /guardian` + client [src/guardian.js](src/guardian.js), inbox [api/agents/recovery-inbox.js](api/agents/recovery-inbox.js) `-> GET /api/agents/recovery-inbox`, per-agent actions [api/agents/recovery.js](api/agents/recovery.js) `-> /api/agents/:id/recovery/...`, rules [api/_lib/agent-recovery.js](api/_lib/agent-recovery.js), owner-side tab [src/agent-wallet-hub/tabs/recovery.js](src/agent-wallet-hub/tabs/recovery.js), schema [api/_lib/migrations/20260623100000_social_recovery.sql](api/_lib/migrations/20260623100000_social_recovery.sql) | Live | The other side of a locked-out or departed owner. The owner names guardians, an approval threshold and a beneficiary from their agent's wallet hub; the guardians and beneficiaries act from `/guardian`, which lists every agent they are trusted to protect with the open recovery or inheritance process, the reason the requester gave, who has already voted, the safety-window and expiry countdowns, and their own approve / decline / confirm / complete actions. A key is never decrypted or exported: completing a process re-points ownership only. The requester cannot approve their own takeover, an open request freezes autonomous spend, threshold approvals start a 48h time-lock, and the real owner's return cancels the whole thing. Inheritance is a dead-man's switch armed from real owner activity plus a grace window. Docs: [docs/guardian.md](docs/guardian.md), [docs/custody.md](docs/custody.md). Tests: [tests/agent-recovery.test.js](tests/agent-recovery.test.js), [tests/api-agents-recovery-handler.test.js](tests/api-agents-recovery-handler.test.js) |
| Master wallet (per-user custodial hub) | page [pages/wallet.html](pages/wallet.html) `→ /wallet` + controller [src/master-wallet.js](src/master-wallet.js), client [src/wallet-api.js](src/wallet-api.js), styles [public/master-wallet.css](public/master-wallet.css); API [api/user/wallet/index.js](api/user/wallet/index.js) (create + balances), [send.js](api/user/wallet/send.js), [fund-agent.js](api/user/wallet/fund-agent.js), [history.js](api/user/wallet/history.js); schema [master_wallets](api/_lib/migrations/20260730040000_master_wallets.sql) | In-repo | One custodial Solana + EVM keypair per USER account (distinct from per-agent wallets): hold SOL/USDC across Solana and Base, top up any agent you own, send to any Solana address, and read history straight from chain. Session-cookie auth only, so no API key or agent can ever spend it; writes are CSRF-guarded and capped at 5 outbound transfers per user per day. The page prices every send through the server's `simulate` path first and requires an explicit confirm showing recipient, amount, asset and network before anything is signed. NOT [src/wallet.js](src/wallet.js), which connects an external Phantom/Seed-Vault wallet. Docs: [docs/user-wallet.md](docs/user-wallet.md). Tests: [tests/master-wallet-page.test.js](tests/master-wallet-page.test.js) |
-| Real-funds risk acknowledgment | gate [public/risk-ack.js](public/risk-ack.js) `→ /legal/risk`, app wrapper [src/shared/risk-ack.js](src/shared/risk-ack.js), record endpoint [api/legal/risk-ack.js](api/legal/risk-ack.js), disclosure [public/legal/risk.html](public/legal/risk.html) | In-repo | Versioned, once-per-browser acceptance dialog every money-committing surface awaits before executing (trade, snipe, withdraw, swap, launch, x402, onramp — devnet exempt). Acceptances persist in `audit_log` (`risk-ack-accept`). See [docs/risk-acknowledgment.md](docs/risk-acknowledgment.md) |
+| Real-funds agreements (signature gate) | dialog [public/risk-ack.js](public/risk-ack.js), app wrapper [src/shared/risk-ack.js](src/shared/risk-ack.js), server enforcement [api/_lib/real-funds-agreement.js](api/_lib/real-funds-agreement.js), sign/status endpoint [api/legal/risk-ack.js](api/legal/risk-ack.js), review page [public/legal/agreements.html](public/legal/agreements.html) `→ /legal/agreements`, documents [public/legal/tos.html](public/legal/tos.html), [public/legal/risk.html](public/legal/risk.html), [public/legal/agent-wallet.html](public/legal/agent-wallet.html) `→ /legal/agent-wallet`, coverage guard [tests/real-funds-agreement-coverage.test.js](tests/real-funds-agreement-coverage.test.js) | In-repo | Before any real-funds action (deposit address reveal, tip, trade, snipe, withdraw, send, swap, launch, x402, onramp, autopilot arm) a person signs the Terms of Service, Risk Disclosure, and Agent Wallet Agreement: one checkbox per document, eligibility and no-liability attestations, and a typed-name e-signature. Signatures land append-only in `legal_signatures` with document versions and text fingerprints. Every custodial money endpoint calls `requireRealFundsAgreement()`, which answers `403 risk_ack_required` for unsigned accounts (session and API key alike); devnet exempt. See [docs/risk-acknowledgment.md](docs/risk-acknowledgment.md) |
| Global markets + coin detail pages | [pages/coins.html](pages/coins.html) + [src/coins-index.js](src/coins-index.js) `→ /coins`, [pages/coin.html](pages/coin.html) + [src/coin-page.js](src/coin-page.js) `→ /coin/:id`, backend [api/coin/](api/coin) (detail, tickers, ohlc, pool, markets, news, global over [api/_lib/coingecko.js](api/_lib/coingecko.js)) | In-repo | CoinGecko-style markets index (global stats bar, sortable top-coins table, search, sparklines) + a rich detail page per coin: interactive chart with a source switcher (native CoinGecko line chart, TradingView advanced candlesticks, or the DexScreener / GeckoTerminal on-chain terminal — each shown only when it can chart the coin; GeckoTerminal's pool resolved via [api/coin/pool.js](api/coin/pool.js)), 1h→1y price-performance matrix, market-stats grid, circulating/max supply bar with Mcap/FDV ratio, ATH/ATL with drawdown & recovery multiple, community sentiment vote split, community + developer (GitHub) activity grids, a paginated exchange-listings table (`api/coin/tickers`, ±2% depth + trust) linking into exchange detail, related news, and full link pills (site/social/whitepaper/forum/chat/explorers). Design adopted from cryptocurrency.cv; accepts CoinGecko slugs or Solana mints. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| Global Intel Globe (`/globe`) | Page [pages/globe.html](pages/globe.html) `-> /globe`, renderer [src/globe-intel.js](src/globe-intel.js), pure logic [src/globe-intel-core.js](src/globe-intel-core.js), styles [src/globe-intel.css](src/globe-intel.css); API [api/globe/intel.js](api/globe/intel.js) over [api/_lib/globe-sources.js](api/_lib/globe-sources.js) and [api/_lib/globe-centroids.js](api/_lib/globe-centroids.js); ingest [api/cron/globe-ingest.js](api/cron/globe-ingest.js) -> `globe_events`; reference set [data/globe-reference.json](data/globe-reference.json), geometry baked by [scripts/build-globe-geometry.mjs](scripts/build-globe-geometry.mjs) into [public/data/globe-land.json](public/data/globe-land.json) + [data/country-centroids.json](data/country-centroids.json) | Live | **A 3D globe of what is happening on Earth right now.** Eleven layers on one sphere: armed conflict, force posture and sanctions classified out of the GDELT 2.0 event stream by CAMEO code, attention hotspots computed from them, natural events (USGS, NASA EONET, GDACS), severe weather (GDACS), national internet outages (Georgia Tech IODA), economic stress (World Bank), and the reference geography that gives the live layers meaning: overseas military bases, nuclear sites, and maritime chokepoints that score themselves against the live feed rather than sitting still. Every upstream is keyless, so the page works on a fresh clone. GDELT publishes one file every 15 minutes and no queryable history (its GEO 2.0 API 404s for every query), so the 24h/7d/30d control is only honest because the cron keeps the window in Postgres; each layer reports the span it actually covered and the panel prints "Covers 15h so far" rather than implying a week. A dead upstream renders as a named layer with its reason, never as an empty globe. Camera, zoom, projection, range and layer selection all live in the URL, so any view is a shareable link. Globe and flat map are the same geometry lerped between two projections, written into `position` rather than a vertex shader so every marker stays pickable in both. Docs: [docs/globe.md](docs/globe.md). Tests: [tests/globe-intel-core.test.js](tests/globe-intel-core.test.js), [tests/globe-sources.test.js](tests/globe-sources.test.js) |
| Market tools (heatmap, sentiment, gas, compare) | [pages/heatmap.html](pages/heatmap.html) + [src/heatmap.js](src/heatmap.js) `→ /heatmap`, [pages/fear-greed.html](pages/fear-greed.html) + [src/fear-greed.js](src/fear-greed.js) `→ /fear-greed`, [pages/gas.html](pages/gas.html) + [src/gas.js](src/gas.js) `→ /gas`, [pages/compare.html](pages/compare.html) + [src/compare.js](src/compare.js) `→ /compare`; backend [api/coin/fear-greed.js](api/coin/fear-greed.js), [api/coin/gas.js](api/coin/gas.js) | In-repo | Four tools extending Markets, same design system: treemap heatmap (market-cap-sized tiles), Fear & Greed gauge + history, live Ethereum gas tracker (keyless `eth_feeHistory`), and up-to-4-coin compare (overlay perf + stats). All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
diff --git a/api/_lib/legal.js b/api/_lib/legal.js
index 361e56d8e..0b740d747 100644
--- a/api/_lib/legal.js
+++ b/api/_lib/legal.js
@@ -15,7 +15,7 @@
import { sql } from './db.js';
import { logAuditNow } from './audit.js';
-export const TOS_VERSION = 2;
+export const TOS_VERSION = 3;
/**
* Parse the optional ToS-acceptance fields from an auth request body.
diff --git a/api/_lib/migrations/20260917180000_legal_signatures.sql b/api/_lib/migrations/20260917180000_legal_signatures.sql
new file mode 100644
index 000000000..2cf572458
--- /dev/null
+++ b/api/_lib/migrations/20260917180000_legal_signatures.sql
@@ -0,0 +1,32 @@
+-- Real-funds agreement signatures: the evidentiary record that a person signed
+-- the Terms of Service, the Risk Disclosure, and the Agent Wallet Agreement
+-- before any real-funds action. Written by POST /api/legal/risk-ack and read by
+-- requireRealFundsAgreement() (api/_lib/real-funds-agreement.js), which refuses
+-- money-moving API calls from an account with no current signature on file.
+--
+-- Append-only by design: a newer signature is a new row, nothing is updated or
+-- deleted. user_id deliberately has no foreign key, so a signature survives the
+-- deletion of the account that made it (the Agent Wallet Agreement promises the
+-- record is kept as long as the law requires). Anonymous signatures (a visitor
+-- funding someone else's agent before signing in) carry a null user_id.
+--
+-- documents holds, per document, the version signed and the sha256 of that
+-- document's text as served when it was signed:
+-- {"tos":{"version":3,"sha256":"…"},"risk":{…},"agentWallet":{…}}
+create table if not exists legal_signatures (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid,
+ bundle_version int not null,
+ documents jsonb not null,
+ signature_name text not null,
+ attestations jsonb not null,
+ context text,
+ path text,
+ ip text,
+ user_agent text,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists legal_signatures_user_idx
+ on legal_signatures (user_id, bundle_version desc, created_at desc)
+ where user_id is not null;
diff --git a/api/_lib/real-funds-agreement.js b/api/_lib/real-funds-agreement.js
new file mode 100644
index 000000000..7bf7e7d7d
--- /dev/null
+++ b/api/_lib/real-funds-agreement.js
@@ -0,0 +1,316 @@
+// Real-funds agreement: server-side record and enforcement.
+//
+// Before any real-funds action, a person signs three documents together: the
+// Terms of Service, the Risk Disclosure, and the Agent Wallet Agreement. The
+// signing dialog lives in public/risk-ack.js and posts to /api/legal/risk-ack;
+// this module validates that signature, writes the durable record into
+// legal_signatures (migration 20260917180000_legal_signatures.sql), and gives
+// every money-moving endpoint one call, requireRealFundsAgreement(), that
+// refuses an account without a current signature. Usage is in
+// docs/risk-acknowledgment.md.
+//
+// The client gate is a convenience; this is the enforcement. It covers session
+// and API-key callers alike, so a script cannot skip the agreement the UI shows.
+//
+// Versions come from AGREEMENT_DOCUMENTS / RISK_ACK_VERSION in the client
+// module, so the documents a signature records are always the ones the dialog
+// showed. Each signature also stores the sha256 of every document's <main>
+// text as this server serves it, which pins exactly what was signed even if
+// the page is later edited without a version bump.
+
+import { createHash } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import { sql } from './db.js';
+import { withDbRetry } from './db-retry.js';
+import { logAuditNow } from './audit.js';
+import { clientIp } from './rate-limit.js';
+import { error } from './http.js';
+import { env } from './env.js';
+import {
+ AGREEMENT_ATTESTATIONS,
+ AGREEMENT_DOCUMENTS,
+ RISK_ACK_REQUIRED_ERROR,
+ RISK_ACK_VERSION,
+ normalizeSignatureName,
+} from '../../public/risk-ack.js';
+
+const SLUG = /^[a-z0-9][a-z0-9-]{0,39}$/;
+const PATH = /^\/[\x20-\x7e]{0,199}$/;
+const UA_MAX = 512;
+const SIGN_PATH = '/legal/agreements';
+
+const DOCUMENT_FILES = {
+ tos: new URL('../../public/legal/tos.html', import.meta.url),
+ risk: new URL('../../public/legal/risk.html', import.meta.url),
+ agentWallet: new URL('../../public/legal/agent-wallet.html', import.meta.url),
+};
+
+/**
+ * sha256 of a legal page's <main> element, whitespace-collapsed so a
+ * re-indent does not change the fingerprint but any wording change does. Pure.
+ * @param {string} html
+ */
+export function fingerprintDocumentHtml(html) {
+ const match = /<main\b[^>]*>([\s\S]*?)<\/main>/i.exec(html);
+ const text = (match ? match[1] : html).replace(/\s+/g, ' ').trim();
+ return createHash('sha256').update(text).digest('hex');
+}
+
+let _fingerprints = null;
+
+/** Fingerprints of the served documents, computed once per process. Never rejects. */
+export function documentFingerprints() {
+ if (_fingerprints) return _fingerprints;
+ _fingerprints = Promise.all(
+ AGREEMENT_DOCUMENTS.map(async (d) => {
+ try {
+ return [d.key, fingerprintDocumentHtml(await readFile(DOCUMENT_FILES[d.key], 'utf8'))];
+ } catch (err) {
+ console.error('[real-funds-agreement] could not fingerprint', d.key, err?.message || err);
+ return [d.key, null];
+ }
+ }),
+ ).then((pairs) => Object.fromEntries(pairs));
+ return _fingerprints;
+}
+
+/**
+ * Validate a signature POST body. Pure: every rule the record must satisfy
+ * lives here, so the endpoint cannot store a signature the dialog could not
+ * have produced.
+ *
+ * @param {unknown} body
+ * @returns {{ ok: true, value: { version: number, documents: Record<string, number>, attestations: Record<string, true>, signatureName: string, context: string|null, path: string|null } }
+ * | { ok: false, code: string, message: string }}
+ */
+export function validateSignatureBody(body) {
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
+ return { ok: false, code: 'invalid_body', message: 'body must be a JSON object' };
+ }
+ const version = Number(body.version);
+ if (!Number.isInteger(version) || version !== RISK_ACK_VERSION) {
+ return {
+ ok: false,
+ code: 'invalid_version',
+ message: `version must be ${RISK_ACK_VERSION}, the current agreement version. Reload the page and sign again.`,
+ };
+ }
+ const docs = body.documents && typeof body.documents === 'object' ? body.documents : {};
+ for (const d of AGREEMENT_DOCUMENTS) {
+ if (Number(docs[d.key]) !== d.version) {
+ return {
+ ok: false,
+ code: 'document_not_accepted',
+ message: `${d.title} version ${d.version} must be accepted`,
+ };
+ }
+ }
+ const attest = body.attestations && typeof body.attestations === 'object' ? body.attestations : {};
+ for (const a of AGREEMENT_ATTESTATIONS) {
+ if (attest[a.key] !== true) {
+ return { ok: false, code: 'attestation_missing', message: `the "${a.key}" confirmation must be checked` };
+ }
+ }
+ const signatureName = normalizeSignatureName(body.signatureName);
+ if (!signatureName) {
+ return { ok: false, code: 'invalid_signature', message: 'type your full name to sign' };
+ }
+ return {
+ ok: true,
+ value: {
+ version,
+ documents: Object.fromEntries(AGREEMENT_DOCUMENTS.map((d) => [d.key, d.version])),
+ attestations: Object.fromEntries(AGREEMENT_ATTESTATIONS.map((a) => [a.key, true])),
+ signatureName,
+ context: typeof body.context === 'string' && SLUG.test(body.context) ? body.context : null,
+ path: typeof body.path === 'string' && PATH.test(body.path) ? body.path : null,
+ },
+ };
+}
+
+/**
+ * Write a validated signature. The legal_signatures row is the deliverable;
+ * the audit_log row is the secondary trail. Never throws.
+ *
+ * @param {{ userId: string|null, value: ReturnType<typeof validateSignatureBody>['value'], req?: import('http').IncomingMessage }} args
+ * @returns {Promise<boolean>} true when the legal_signatures row landed
+ */
+export async function recordRealFundsSignature({ userId, value, req = null }) {
+ const fingerprints = await documentFingerprints();
+ const documents = Object.fromEntries(
+ AGREEMENT_DOCUMENTS.map((d) => [d.key, { version: d.version, sha256: fingerprints[d.key] }]),
+ );
+ const ip = req ? clientIp(req) : null;
+ const ua = req?.headers?.['user-agent'] ? String(req.headers['user-agent']).slice(0, UA_MAX) : null;
+ let recorded = false;
+ try {
+ await withDbRetry(
+ () => sql`
+ insert into legal_signatures
+ (user_id, bundle_version, documents, signature_name, attestations, context, path, ip, user_agent)
+ values
+ (${userId}, ${value.version}, ${JSON.stringify(documents)}::jsonb, ${value.signatureName},
+ ${JSON.stringify(value.attestations)}::jsonb, ${value.context}, ${value.path}, ${ip}, ${ua})
+ `,
+ { timeoutMs: 8_000 },
+ );
+ recorded = true;
+ } catch (err) {
+ console.error('[real-funds-agreement] signature insert failed', err?.message || err);
+ }
+ if (recorded) {
+ if (userId) _rememberSigned(userId);
+ await logAuditNow({
+ userId,
+ action: 'risk-ack-accept',
+ resourceId: null,
+ meta: { version: value.version, documents: value.documents, context: value.context, path: value.path },
+ req,
+ });
+ }
+ return recorded;
+}
+
+// Positive results only: signatures are append-only and the required version
+// is a deploy-time constant, so "signed" can never become false inside one
+// process. Negative results are never cached, so a fresh signature takes
+// effect on the very next request.
+const SIGNED_CACHE_TTL_MS = 10 * 60_000;
+const SIGNED_CACHE_MAX = 5_000;
+const _signedCache = new Map();
+
+function _cachedSigned(userId) {
+ const at = _signedCache.get(userId);
+ if (at === undefined) return false;
+ if (Date.now() - at > SIGNED_CACHE_TTL_MS) {
+ _signedCache.delete(userId);
+ return false;
+ }
+ return true;
+}
+
+function _rememberSigned(userId) {
+ if (_signedCache.size >= SIGNED_CACHE_MAX) _signedCache.delete(_signedCache.keys().next().value);
+ _signedCache.set(userId, Date.now());
+}
+
+/** Test hook: forget cached signature lookups. */
+export function resetRealFundsAgreementCache() {
+ _signedCache.clear();
+}
+
+/**
+ * The account's latest signature at or above the current version.
+ * Throws on a database failure; callers decide how to fail.
+ * @param {string} userId
+ * @returns {Promise<{ signedAt: string, signatureName: string, context: string|null } | null>}
+ */
+export async function currentSignatureFor(userId) {
+ const rows = await withDbRetry(
+ () => sql`
+ select created_at, signature_name, context
+ from legal_signatures
+ where user_id = ${userId} and bundle_version >= ${RISK_ACK_VERSION}
+ order by created_at desc
+ limit 1
+ `,
+ { timeoutMs: 5_000 },
+ );
+ const row = rows?.[0];
+ if (!row) return null;
+ _rememberSigned(userId);
+ return {
+ signedAt: new Date(row.created_at).toISOString(),
+ signatureName: row.signature_name,
+ context: row.context ?? null,
+ };
+}
+
+/**
+ * Every signature this account has made, newest first, for the review page.
+ * @param {string} userId
+ * @param {{ limit?: number }} [opts]
+ */
+export async function signatureHistoryFor(userId, { limit = 20 } = {}) {
+ const rows = await withDbRetry(
+ () => sql`
+ select id, bundle_version, documents, signature_name, context, path, created_at
+ from legal_signatures
+ where user_id = ${userId}
+ order by created_at desc
+ limit ${Math.min(Math.max(1, limit), 100)}
+ `,
+ { timeoutMs: 5_000 },
+ );
+ return (rows || []).map((r) => ({
+ id: r.id,
+ version: r.bundle_version,
+ current: r.bundle_version >= RISK_ACK_VERSION,
+ documents: r.documents,
+ signatureName: r.signature_name,
+ context: r.context ?? null,
+ path: r.path ?? null,
+ signedAt: new Date(r.created_at).toISOString(),
+ }));
+}
+
+/** The machine-readable part of a refusal, so any client can route the user to sign. */
+export function agreementRequirement() {
+ const origin = env.APP_ORIGIN;
+ return {
+ version: RISK_ACK_VERSION,
+ sign_url: `${origin}${SIGN_PATH}`,
+ documents: AGREEMENT_DOCUMENTS.map((d) => ({
+ key: d.key,
+ title: d.title,
+ version: d.version,
+ url: `${origin}${d.path}`,
+ })),
+ };
+}
+
+/**
+ * Refuse a real-funds request from an account that has not signed the current
+ * agreements. Sends the response and resolves false when refused; resolves
+ * true when the caller may proceed.
+ *
+ * Devnet is exempt: it moves no real value, and the client gate exempts it
+ * too. A database failure fails CLOSED with 503: real funds never move on an
+ * unverified agreement.
+ *
+ * @param {import('http').IncomingMessage} req
+ * @param {import('http').ServerResponse} res
+ * @param {{ userId: string|null|undefined, network?: string|null, context?: string }} opts
+ * @returns {Promise<boolean>}
+ */
+export async function requireRealFundsAgreement(req, res, { userId, network = null, context = 'real-funds' } = {}) {
+ if (String(network || '').toLowerCase() === 'devnet') return true;
+ if (!userId) {
+ error(res, 401, 'unauthorized', 'sign in to use real-funds features');
+ return false;
+ }
+ if (_cachedSigned(userId)) return true;
+ let signature;
+ try {
+ signature = await currentSignatureFor(userId);
+ } catch (err) {
+ console.error('[real-funds-agreement] signature lookup failed', context, err?.message || err);
+ error(
+ res,
+ 503,
+ 'agreement_check_unavailable',
+ 'We could not verify your signed real-funds agreements, so nothing was sent. Try again in a moment.',
+ );
+ return false;
+ }
+ if (signature) return true;
+ error(
+ res,
+ 403,
+ RISK_ACK_REQUIRED_ERROR,
+ 'Sign the real-funds agreements (Terms of Service, Risk Disclosure, and Agent Wallet Agreement) before using ' +
+ `real funds. Nothing was sent. Sign at ${env.APP_ORIGIN}${SIGN_PATH}`,
+ { context, ...agreementRequirement() },
+ );
+ return false;
+}
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 2c995ff28..be4ee58c1 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -59,6 +59,26 @@ alter table users add column if not exists onboarding_tour_completed_at timestam
alter table users add column if not exists tos_accepted_version int;
alter table users add column if not exists tos_accepted_at timestamptz;
+-- Real-funds agreement signatures (api/_lib/migrations/20260917180000_legal_signatures.sql).
+-- Append-only; user_id has no FK so the record outlives account deletion.
+-- See api/_lib/real-funds-agreement.js.
+create table if not exists legal_signatures (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid,
+ bundle_version int not null,
+ documents jsonb not null,
+ signature_name text not null,
+ attestations jsonb not null,
+ context text,
+ path text,
+ ip text,
+ user_agent text,
+ created_at timestamptz not null default now()
+);
+create index if not exists legal_signatures_user_idx
+ on legal_signatures (user_id, bundle_version desc, created_at desc)
+ where user_id is not null;
+
-- ── user_follows — the social graph ──────────────────────────────────────────
-- A directed follow edge: follower_id follows following_id. Composite PK makes
-- a follow idempotent (one edge per pair) and the toggle a single upsert/delete.
diff --git a/api/_mcp/tools/oracle.js b/api/_mcp/tools/oracle.js
index 6b7294b94..7e300e252 100644
--- a/api/_mcp/tools/oracle.js
+++ b/api/_mcp/tools/oracle.js
@@ -25,6 +25,7 @@ import { sql } from '../../_lib/db.js';
import { limits } from '../../_lib/rate-limit.js';
import { readFeed, scoreCoin, getWatch, upsertWatch, recentActions, actionsSummary } from '../../_lib/oracle/store.js';
import { isUuid } from '../../_lib/validate.js';
+import { currentSignatureFor, agreementRequirement } from '../../_lib/real-funds-agreement.js';
const NETWORKS = new Set(['mainnet', 'devnet']);
const CATEGORIES = new Set([
@@ -67,6 +68,30 @@ function mcpErr(msg) {
return { content: [{ type: 'text', text: msg }], isError: true };
}
+// Arming a live watch commits the agent's custodial SOL to autonomous buys, so it
+// needs the signed real-funds agreement. Returns null when the caller may proceed,
+// otherwise a designed tool error. A database failure fails closed.
+async function liveArmAgreementError(userId) {
+ let signature;
+ try {
+ signature = await currentSignatureFor(userId);
+ } catch (err) {
+ console.error('[mcp/oracle] agreement lookup failed', err?.message || err);
+ return mcpErr('Could not verify your signed real-funds agreements, so the watch was not armed live. Try again in a moment.');
+ }
+ if (signature) return null;
+ const requirement = agreementRequirement();
+ return {
+ content: [{
+ type: 'text',
+ text: 'Sign the real-funds agreements (Terms of Service, Risk Disclosure, and Agent Wallet Agreement) before arming a live watch. ' +
+ `Nothing was changed. Sign at ${requirement.sign_url}`,
+ }],
+ structuredContent: { armed: false, reason: 'risk_ack_required', ...requirement },
+ isError: true,
+ };
+}
+
// Throws on a DB fault rather than swallowing it. Swallowing turned an outage
// into "that agent does not belong to your account": a confident, false answer
// that sends the owner off to audit permissions that were never the problem.
@@ -261,6 +286,14 @@ export const toolDefs = [
size_scaling: args?.size_scaling !== false,
};
+ if (cfg.armed && cfg.mode === 'live' && network !== 'devnet') {
+ const current = await getWatch(agentId, network);
+ if (!(current?.armed === true && current?.mode === 'live')) {
+ const refusal = await liveArmAgreementError(auth.userId);
+ if (refusal) return refusal;
+ }
+ }
+
await upsertWatch(agentId, auth.userId, network, cfg);
const [watch, summary] = await Promise.all([
diff --git a/api/_mcpagent/tools.js b/api/_mcpagent/tools.js
index e9860416e..5f957ed15 100644
--- a/api/_mcpagent/tools.js
+++ b/api/_mcpagent/tools.js
@@ -32,6 +32,7 @@ import {
usdcToAtomics,
MonetizeError,
} from '../_lib/agent-paid-services.js';
+import { currentSignatureFor, agreementRequirement } from '../_lib/real-funds-agreement.js';
function rpcError(code, message, data) {
const e = new Error(message);
@@ -65,6 +66,42 @@ function signInRequired(text) {
};
}
+// Real funds only move for an account that signed the current real-funds
+// agreements. Returns null when the caller may proceed, otherwise a designed
+// tool result. A database failure fails closed: nothing moves unverified.
+async function agreementRequired(userId, resource) {
+ let signature;
+ try {
+ signature = await currentSignatureFor(userId);
+ } catch (err) {
+ console.error('[mcpagent] agreement lookup failed', err?.message || err);
+ return {
+ content: [
+ {
+ type: 'text',
+ text: 'Could not verify your signed real-funds agreements, so nothing was sent. Try again in a moment.',
+ },
+ ],
+ structuredContent: { paid: false, reason: 'agreement_check_unavailable', resource },
+ isError: true,
+ };
+ }
+ if (signature) return null;
+ const requirement = agreementRequirement();
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ 'Sign the real-funds agreements (Terms of Service, Risk Disclosure, and Agent Wallet Agreement) before paying from your wallet. ' +
+ `Nothing was sent. Sign at ${requirement.sign_url}`,
+ },
+ ],
+ structuredContent: { paid: false, reason: 'risk_ack_required', resource, ...requirement },
+ isError: true,
+ };
+}
+
// Scope is enforced inside the handler (not via the dispatcher's tool.scope) so
// the null-userId x402 path gets the friendly signInRequired() message first,
// and an authenticated-but-under-scoped token gets a clear, designed error
@@ -309,6 +346,9 @@ export const toolDefs = [
// before payExternalX402 so no money can move without the grant.
if (!hasScope(auth.scope, 'wallet:write')) return scopeRequired('wallet:write');
+ const unsigned = await agreementRequired(auth.userId, args.resource_url);
+ if (unsigned) return unsigned;
+
try {
const res = await payExternalX402({
userId: auth.userId,
diff --git a/api/agent-subscriptions.js b/api/agent-subscriptions.js
index c1ce75112..be20051d1 100644
--- a/api/agent-subscriptions.js
+++ b/api/agent-subscriptions.js
@@ -23,6 +23,7 @@ import { sql } from './_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from './_lib/http.js';
import { requireCsrf } from './_lib/csrf.js';
+import { requireRealFundsAgreement } from './_lib/real-funds-agreement.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { z } from 'zod';
import { parse } from './_lib/validate.js';
@@ -187,6 +188,7 @@ export default wrap(async (req, res) => {
WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL
`;
if (!agent) return error(res, 403, 'forbidden', 'agent not found or not owned by you');
+ if (!(await requireRealFundsAgreement(req, res, { userId, context: 'recurring-payment-create' }))) return;
// Verify the delegation is active and belongs to this agent.
const [delegation] = await sql`
@@ -380,6 +382,7 @@ export default wrap(async (req, res) => {
}
if (body.action === 'resume') {
+ if (!(await requireRealFundsAgreement(req, res, { userId, context: 'recurring-payment-resume' }))) return;
// Resuming a schedule whose delegation is gone would just fail on the
// next tick and re-pause it. Say so instead of pretending it worked.
if (current.delegation_status !== 'active') {
diff --git a/api/agents/a2a-hire.js b/api/agents/a2a-hire.js
index 392f62fe5..8bf6ffb18 100644
--- a/api/agents/a2a-hire.js
+++ b/api/agents/a2a-hire.js
@@ -26,6 +26,7 @@
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { limits } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
import { randomUUID } from 'node:crypto';
@@ -184,6 +185,11 @@ export default wrap(async (req, res) => {
});
}
+ // Every hire pays mainnet USDC from the hirer's custodial wallet, so the caller
+ // must have signed the real-funds agreements before any hire is recorded or
+ // any spend is reserved.
+ if (!(await requireRealFundsAgreement(req, res, { userId, context: 'a2a-hire' }))) return;
+
if (!resolveSpendEnabled()) {
return error(res, 501, 'spend_disabled', 'autonomous agent spending is not enabled on this server (set THREEWS_AGENT_PAY_ENABLED=1)');
}
diff --git a/api/agents/agent-mirror.js b/api/agents/agent-mirror.js
index 0419958b3..b106bc07b 100644
--- a/api/agents/agent-mirror.js
+++ b/api/agents/agent-mirror.js
@@ -20,6 +20,7 @@ import { sql } from '../_lib/db.js';
import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { isUuid } from '../_lib/validate.js';
import { logAudit } from '../_lib/audit.js';
import { normalizeFollowInput, SKIP_LABELS } from '../_lib/mirror-engine.js';
@@ -139,7 +140,6 @@ async function handleUpsert(req, res, id) {
if (!method(req, res, ['POST'])) return;
const owned = await loadOwned(req, res, id);
if (!owned) return;
- if (!(await requireCsrf(req, res, owned.auth.userId))) return;
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
@@ -153,6 +153,13 @@ async function handleUpsert(req, res, id) {
if (leaderId === id) return error(res, 400, 'cannot_follow_self', 'an agent cannot mirror itself');
const network = netOf(body.network);
+ const enabled = body.enabled === false ? false : true;
+
+ // An enabled follow trades the follower's custodial wallet autonomously, so it
+ // needs signed real-funds agreements. Saving a paused follow does not. Checked
+ // before CSRF so a refusal does not burn the owner's single-use token.
+ if (enabled && !(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network, context: 'mirror' }))) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
// The leader must exist and be public (you can only copy a transparent agent).
const [leader] = await sql`SELECT id, name, is_public FROM agent_identities WHERE id = ${leaderId} AND deleted_at IS NULL`;
@@ -166,7 +173,6 @@ async function handleUpsert(req, res, id) {
const norm = normalizeFollowInput(body);
if (!norm.ok) return error(res, 400, 'validation_error', norm.error);
const v = norm.value;
- const enabled = body.enabled === false ? false : true;
// Cursor starts at the leader's latest trade so a new follow mirrors only
// trades made AFTER the follow began — never backfills history.
@@ -245,6 +251,12 @@ async function handleSync(req, res, id) {
if (!method(req, res, ['POST'])) return;
const owned = await loadOwned(req, res, id);
if (!owned) return;
+
+ const follows = await sql`SELECT * FROM agent_mirror_follows WHERE follower_agent_id = ${id} AND enabled = true`;
+ // Syncing executes mirrored trades from the custodial wallet. Devnet-only
+ // follows are exempt; checked before CSRF so a refusal keeps the token.
+ const syncNetwork = follows.some((f) => f.network !== 'devnet') ? 'mainnet' : 'devnet';
+ if (follows.length && !(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network: syncNetwork, context: 'mirror' }))) return;
if (!(await requireCsrf(req, res, owned.auth.userId))) return;
const rl = await limits.authIp(clientIp(req));
@@ -254,7 +266,6 @@ async function handleSync(req, res, id) {
return error(res, 409, 'mirror_killed', 'mirroring is paused by the kill switch — turn it off to sync');
}
- const follows = await sql`SELECT * FROM agent_mirror_follows WHERE follower_agent_id = ${id} AND enabled = true`;
const out = [];
for (const f of follows) {
// Attach leader name for the custody label without an extra round trip later.
diff --git a/api/agents/agent-strategy-objects.js b/api/agents/agent-strategy-objects.js
index a6a451c6e..612bbf91a 100644
--- a/api/agents/agent-strategy-objects.js
+++ b/api/agents/agent-strategy-objects.js
@@ -17,6 +17,7 @@ import { sql } from '../_lib/db.js';
import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { isUuid } from '../_lib/validate.js';
import { logAudit } from '../_lib/audit.js';
import { normalizeStrategyConfig } from '../_lib/strategy-schema.js';
@@ -142,13 +143,16 @@ async function handleEquip(req, res, id) {
if (!owned) return;
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- if (!(await requireCsrf(req, res, owned.auth.userId))) return;
if (!owned.row.meta?.solana_address) return error(res, 409, 'wallet_preparing', 'this agent’s wallet is still provisioning');
const body = await readJson(req).catch(() => null);
const strategyId = body?.strategy_id;
if (!isUuid(strategyId)) return error(res, 400, 'validation_error', 'a valid strategy_id is required');
const network = netOf(body?.network);
+ // Equipping arms the strategy to trade the custodial wallet autonomously.
+ // Checked before CSRF so a refusal does not burn the owner's single-use token.
+ if (!(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network, context: 'strategy' }))) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
// The strategy must be the caller's own OR a published one (forking is the path to
// owning the rules; equipping a published strategy runs it under YOUR spend policy).
@@ -193,10 +197,16 @@ async function handleUnequip(req, res, id) {
async function handleToggle(req, res, id) {
const owned = await loadOwned(req, res, id);
if (!owned) return;
- if (!(await requireCsrf(req, res, owned.auth.userId))) return;
const body = await readJson(req).catch(() => ({}));
if (!isUuid(body?.equip_id)) return error(res, 400, 'validation_error', 'equip_id required');
const active = body.active !== false;
+ // Resuming re-arms autonomous trading; pausing never needs the agreement.
+ if (active) {
+ const [target] = await sql`SELECT network FROM agent_strategy_equips WHERE id = ${body.equip_id} AND agent_id = ${id}`;
+ if (!target) return error(res, 404, 'not_found', 'equip not found');
+ if (!(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network: netOf(target.network), context: 'strategy' }))) return;
+ }
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
const [row] = await sql`UPDATE agent_strategy_equips SET active = ${active}, updated_at = now() WHERE id = ${body.equip_id} AND agent_id = ${id} RETURNING strategy_id`;
if (!row) return error(res, 404, 'not_found', 'equip not found');
await sql`UPDATE agent_strategies SET equips_count = (SELECT count(*) FROM agent_strategy_equips WHERE strategy_id = ${row.strategy_id} AND active = true) WHERE id = ${row.strategy_id}`.catch(() => {});
@@ -227,7 +237,6 @@ async function handleSweep(req, res, id) {
if (!owned) return;
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- if (!(await requireCsrf(req, res, owned.auth.userId))) return;
const killed = await killEngaged(owned.auth.userId);
const equips = await sql`
@@ -237,6 +246,14 @@ async function handleSweep(req, res, id) {
WHERE e.agent_id = ${id} AND e.active = true
ORDER BY e.last_eval_at ASC NULLS FIRST
`;
+ // A sweep can open new positions unless the kill switch is engaged, in which
+ // case it only runs exits. Devnet-only equips are exempt. Checked before CSRF
+ // so a refusal does not burn the owner's single-use token.
+ if (equips.length && !killed) {
+ const sweepNetwork = equips.some((e) => netOf(e.network) !== 'devnet') ? 'mainnet' : 'devnet';
+ if (!(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network: sweepNetwork, context: 'strategy' }))) return;
+ }
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
if (!equips.length) return json(res, 200, { data: { evaluated: 0, results: [] } });
const byNet = new Set(equips.map((e) => netOf(e.network)));
diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.js
index 913737e45..936ebe102 100644
--- a/api/agents/agent-trade.js
+++ b/api/agents/agent-trade.js
@@ -20,6 +20,7 @@
// skips the broadcast (paper mode) — an ops/test toggle, never the default.
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { sql } from '../_lib/db.js';
import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -401,6 +402,7 @@ async function handleExecute(req, res, id) {
// CSRF on the real, fund-moving path only — `simulate` is a dry run that never
// signs or records. Bearer/API-key callers (the primary consumers of this flat
// trade endpoint) are exempt inside requireCsrf.
+ if (!input.simulate && !(await requireRealFundsAgreement(req, res, { userId: auth.userId, network: input.network, context: 'trade' }))) return;
if (!input.simulate && !(await requireCsrf(req, res, auth.userId))) return;
let result;
diff --git a/api/agents/autopilot.js b/api/agents/autopilot.js
index 28fff2546..9c86d342c 100644
--- a/api/agents/autopilot.js
+++ b/api/agents/autopilot.js
@@ -15,6 +15,7 @@
import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { limits } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
import { sql } from '../_lib/db.js';
@@ -152,6 +153,11 @@ async function handlePut(req, res, id) {
if ('armed' in body) patch.armed = body.armed === true;
if ('kill_switch' in body) patch.kill_switch = body.kill_switch === true;
+ // Arming hands the agent autonomous spending, so it needs a signed real-funds
+ // agreement. Disarming and the kill switch never do: stopping an agent must
+ // always be possible.
+ if (patch.armed === true && !(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network: netOf(req), context: 'autopilot' }))) return;
+
// Arming is explicit consent — stamp approval + compile time server-side.
const nowIso = new Date().toISOString();
if (patch.armed === true) {
@@ -191,6 +197,7 @@ async function handleRun(req, res, id) {
// sibling wallet-intents runner, which has always defaulted to simulation.
// Spending is opt-in and explicit: dry_run must be literally false.
const dryRun = body?.dry_run !== false;
+ if (!dryRun && !(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network, context: 'autopilot' }))) return;
try {
const result = await runAutopilotCycle({
diff --git a/api/agents/pumpfun/[action].js b/api/agents/pumpfun/[action].js
index 2bef5b991..e04263901 100644
--- a/api/agents/pumpfun/[action].js
+++ b/api/agents/pumpfun/[action].js
@@ -26,6 +26,7 @@ import {
} from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { isUuid } from '../../_lib/validate.js';
+import { requireRealFundsAgreement } from '../../_lib/real-funds-agreement.js';
import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
import { submitProtected } from '../../_lib/execution-engine.js';
import { buildAgentTradeFee } from '../../_lib/pump-platform-fee.js';
@@ -129,6 +130,8 @@ async function handleBuy(req, res, id) {
return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
}
+ if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, network: body.network, context: 'pumpfun-buy' }))) return;
+
const loaded = await loadAgentForSigning(id, auth.userId);
if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
const { keypair, meta } = loaded;
@@ -437,6 +440,8 @@ async function handleLaunch(req, res, id) {
return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
}
+ if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, network: body.network, context: 'pumpfun-launch' }))) return;
+
const loaded = await loadAgentForSigning(id, auth.userId);
if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
const { keypair, meta } = loaded;
@@ -642,6 +647,10 @@ async function handlePay(req, res, id) {
return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
}
+ // Every action except the read-only balances lookup signs a transaction with
+ // the custodial key, so it needs the signed real-funds agreements.
+ if (body.action !== 'balances' && !(await requireRealFundsAgreement(req, res, { userId: auth.userId, network: body.network, context: 'pumpfun-pay' }))) return;
+
const loaded = await loadAgentForSigning(id, auth.userId, {
reason: `pumpfun.pay.${body.action}`,
meta: { tokenMint: body.tokenMint, network: body.network },
@@ -1071,6 +1080,8 @@ async function handleSell(req, res, id) {
return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
}
+ if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, network: body.network, context: 'pumpfun-sell' }))) return;
+
const loaded = await loadAgentForSigning(id, auth.userId);
if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
const { keypair } = loaded;
@@ -1293,6 +1304,8 @@ async function handleSwap(req, res, id) {
if (body.side === 'sell' && !body.tokenAmount)
return error(res, 400, 'validation_error', 'side=sell requires tokenAmount');
+ if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, network: body.network, context: 'pumpfun-swap' }))) return;
+
const loaded = await loadAgentForSigning(id, auth.userId, {
reason: `pumpfun.swap.${body.side}`,
meta: { mint: body.mint, network: body.network },
diff --git a/api/agents/sns.js b/api/agents/sns.js
index 7e849d3e2..b20ffdb56 100644
--- a/api/agents/sns.js
+++ b/api/agents/sns.js
@@ -26,6 +26,7 @@
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { sql } from '../_lib/db.js';
import { submitProtected } from '../_lib/execution-engine.js';
import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
@@ -131,11 +132,14 @@ async function handleCheck(req, res) {
// ── Option A: agent wallet pays + auto-attach ─────────────────────────────
async function handleRegisterAgent(req, res, id, auth) {
if (!method(req, res, ['POST'])) return;
- if (!(await requireCsrf(req, res, auth.userId))) return;
const body = await readJson(req).catch(() => ({}));
const domain = normalizeDomain(body?.domain);
if (!domain) return error(res, 400, 'validation_error', 'domain required (a–z, 0–9, hyphen)');
const space = Number.isInteger(body?.space) && body.space >= 1000 && body.space <= 10000 ? body.space : 1000;
+ // The agent's custodial wallet pays mainnet USDC for the domain. Checked
+ // before CSRF so a refusal does not burn the owner's single-use token.
+ if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, network: 'mainnet', context: 'sns-register' }))) return;
+ if (!(await requireCsrf(req, res, auth.userId))) return;
const loaded = await loadAgentForSigning(id, auth.userId, { reason: 'sns_register' });
if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
diff --git a/api/agents/solana-trade.js b/api/agents/solana-trade.js
index 677b8abac..cfda13a57 100644
--- a/api/agents/solana-trade.js
+++ b/api/agents/solana-trade.js
@@ -19,6 +19,7 @@
// plumbing that trades whatever mint the owner supplies at runtime.
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { sql } from '../_lib/db.js';
import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -282,6 +283,7 @@ export async function handleTrade(req, res, id) {
// CSRF on the state-changing path only — a live preview/quote moves no funds and
// would otherwise burn a single-use token on every keystroke. Bearer callers exempt.
+ if (!preview && !(await requireRealFundsAgreement(req, res, { userId: auth.userId, network, context: 'trade' }))) return;
if (!preview && !(await requireCsrf(req, res, auth.userId))) return;
let slippageBps = Number(body.slippage_bps ?? body.slippageBps);
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index af9d6a9a8..c031ad806 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -2,6 +2,7 @@
// Dispatched from api/agents/[id].js with the `action` sub-path.
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { sql } from '../_lib/db.js';
import { confirmOrThrow, pollConfirmation } from '../_lib/solana/confirm.js';
import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
@@ -587,6 +588,10 @@ async function handleWithdraw(req, res, id) {
// `simulate` request moves no funds and never touches the key (it returns a live
// preview, like the trade endpoint's preview), so it is CSRF-exempt — otherwise a
// read-back/quote would burn the owner's single-use token before they confirm.
+ // Real funds leave a custodial wallet only for an account that has signed
+ // the real-funds agreements. Checked before CSRF so a refusal does not burn
+ // the owner's single-use token.
+ if (!simulate && !(await requireRealFundsAgreement(req, res, { userId: auth.userId, network, context: 'withdraw' }))) return;
if (!simulate && !(await requireCsrf(req, res, auth.userId))) return;
const idempotencyKey =
@@ -1431,8 +1436,9 @@ async function handleVanity(req, res, id) {
}
// POST — sensitive: it grinds a new keypair and sweeps every holding to it,
- // so it moves funds. Require CSRF, then gate behind the withdrawal per-user
- // cap + per-IP burst.
+ // so it moves funds. Require a signed real-funds agreement and CSRF, then
+ // gate behind the withdrawal per-user cap + per-IP burst.
+ if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, context: 'vanity' }))) return;
if (!(await requireCsrf(req, res, auth.userId))) return;
const rlUser = await limits.withdrawalPerUser(auth.userId);
if (!rlUser.success) return rateLimited(res, rlUser);
diff --git a/api/agents/wallet-intents.js b/api/agents/wallet-intents.js
index 5eff46f9e..a9a60655c 100644
--- a/api/agents/wallet-intents.js
+++ b/api/agents/wallet-intents.js
@@ -21,6 +21,7 @@ import { cors, json, method, error, readJson, rateLimited, serverError } from '.
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { limits } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { sql } from '../_lib/db.js';
import { loadUserProviderKeys } from '../_lib/provider-keys.js';
import { getSpendLimits, getTradeLimits } from '../_lib/agent-trade-guards.js';
@@ -254,7 +255,6 @@ async function simulate(intent, owned, network) {
async function handleCreate(req, res, id) {
const owned = await loadOwned(req, res, id);
if (owned.error) return;
- if (!(await requireCsrf(req, res, owned.auth.userId))) return;
const body = await readJsonObject(req, res);
if (!body) return;
@@ -262,6 +262,12 @@ async function handleCreate(req, res, id) {
const norm = normalizeIntent(body.intent);
if (!norm.ok) return error(res, 422, norm.error || 'invalid_intent', norm.message || 'the intent could not be validated');
+ // Arming a rule that can move funds needs the signed real-funds agreements;
+ // freeze and notify rules never spend. Checked before CSRF so a refusal does
+ // not burn the owner's single-use token.
+ const spends = !['freeze', 'notify'].includes(norm.intent.action?.type);
+ if (spends && !(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network: netOf(req), context: 'wallet-intent' }))) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
// Preserve a resolved destination + tip-back flag the compiler already grounded.
if (body.intent.action) {
const src = body.intent.action;
@@ -288,7 +294,6 @@ async function handleCreate(req, res, id) {
async function handleUpdate(req, res, id, intentId) {
const owned = await loadOwned(req, res, id);
if (owned.error) return;
- if (!(await requireCsrf(req, res, owned.auth.userId))) return;
const body = await readJsonObject(req, res);
if (!body) return;
@@ -299,6 +304,12 @@ async function handleUpdate(req, res, id, intentId) {
if ('title' in body) patch.title = body.title;
if ('intent' in body) patch.intent = body.intent;
+ // Enabling a rule or rewriting what it does re-arms autonomous spending.
+ // Disabling, renaming, and publishing never need the agreement.
+ const rearms = patch.enabled === true || 'intent' in patch;
+ if (rearms && !(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network: netOf(req), context: 'wallet-intent' }))) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+
try {
const result = await updateIntent(id, owned.auth.userId, intentId, patch);
if (!result) return error(res, 404, 'not_found', 'intent not found');
@@ -327,7 +338,6 @@ async function handleRun(req, res, id) {
if (!method(req, res, ['POST'])) return;
const owned = await loadOwned(req, res, id);
if (owned.error) return;
- if (!(await requireCsrf(req, res, owned.auth.userId))) return;
const rl = await limits.walletRead(owned.auth.userId);
if (!rl.success) return rateLimited(res, rl);
@@ -339,6 +349,8 @@ async function handleRun(req, res, id) {
const intentId = String(body.intent_id || '');
if (!UUID_RE.test(intentId)) return error(res, 400, 'validation_error', 'intent_id is required');
const dryRun = body.dry_run !== false; // default to a safe simulation
+ if (!dryRun && !(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network: netOf(req), context: 'wallet-intent' }))) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
try {
const result = await runIntentNow({ agentId: id, userId: owned.auth.userId, intentId, network: netOf(req), dryRun });
diff --git a/api/autopilot/config.js b/api/autopilot/config.js
index 480a87662..282917df8 100644
--- a/api/autopilot/config.js
+++ b/api/autopilot/config.js
@@ -12,6 +12,7 @@ import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { getAutopilotConfig, setAutopilotConfig, computeTrust } from '../_lib/autopilot.js';
import { isUuid } from '../_lib/validate.js';
@@ -63,7 +64,6 @@ export default wrap(async (req, res) => {
return json(res, 200, { config, trust });
}
- if (!(await requireCsrf(req, res, auth.userId))) return;
const body = await readJson(req);
const agentId = body.agentId || body.agent_id;
const agent = await ownedAgent(req, res, agentId, auth);
@@ -76,6 +76,18 @@ export default wrap(async (req, res) => {
if ('daily_spend_sol' in body) patch.daily_spend_sol = body.daily_spend_sol;
if ('require_confirm' in body) patch.require_confirm = body.require_confirm === true;
+ // A patch that leaves autopilot enabled with the wallet_transfer scope, while
+ // arming it or setting its SOL cap, lets the agent spend real SOL, so it needs a
+ // signed real-funds agreement. Turning autopilot off or revoking the scope never
+ // does. Checked before CSRF so a refusal does not burn the single-use token.
+ const current = getAutopilotConfig(agent.meta);
+ const armedAfter =
+ ('enabled' in patch ? patch.enabled : current.enabled) &&
+ (patch.scopes && 'wallet_transfer' in patch.scopes ? patch.scopes.wallet_transfer === true : current.scopes.wallet_transfer);
+ const touchesSpend = 'enabled' in patch || 'daily_spend_sol' in patch || (patch.scopes && 'wallet_transfer' in patch.scopes);
+ if (armedAfter && touchesSpend && !(await requireRealFundsAgreement(req, res, { userId: auth.userId, context: 'autopilot-config' }))) return;
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+
const config = await setAutopilotConfig(agentId, patch);
return json(res, 200, { config });
});
diff --git a/api/autopilot/proposals.js b/api/autopilot/proposals.js
index 38cdcea0a..a649f46a3 100644
--- a/api/autopilot/proposals.js
+++ b/api/autopilot/proposals.js
@@ -19,6 +19,7 @@ import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import {
generateProposals, executeProposal, dismissProposal, undoProposal, dryRunProposal,
@@ -103,8 +104,6 @@ async function handleList(req, res, auth) {
}
async function handleAct(req, res, auth) {
- if (!(await requireCsrf(req, res, auth.userId))) return;
-
const body = await readJson(req);
const agentId = body.agentId || body.agent_id;
const action = body.action;
@@ -115,6 +114,25 @@ async function handleAct(req, res, auth) {
const agent = await ownedAgent(req, res, agentId, auth);
if (!agent) return;
+ // Every action other than 'generate' operates on a specific proposal.
+ let proposalId = null;
+ let proposal = null;
+ if (action !== 'generate') {
+ proposalId = body.proposalId || body.proposal_id;
+ if (!proposalId) return error(res, 400, 'validation_error', 'proposalId required');
+ if (!isUuid(proposalId)) return error(res, 400, 'validation_error', 'proposalId must be a uuid');
+ const [row] = await sql`SELECT * FROM agent_autopilot_proposals WHERE id = ${proposalId} AND agent_id = ${agentId}`;
+ if (!row) return error(res, 404, 'not_found', 'proposal not found');
+ proposal = decorateProposal(row);
+ }
+
+ // Executing a wallet_transfer sends real SOL from the agent's custodial wallet,
+ // so it needs a signed real-funds agreement. Checked before CSRF so a refusal
+ // does not burn the owner's single-use token.
+ if (action === 'execute' && proposal.kind === 'wallet_transfer' &&
+ !(await requireRealFundsAgreement(req, res, { userId: auth.userId, context: 'autopilot-transfer' }))) return;
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+
if (action === 'generate') {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl, 'too many generation requests');
@@ -146,14 +164,6 @@ async function handleAct(req, res, auth) {
return json(res, 200, { created, autoRan, source: result.source, scanned: result.scanned, trust });
}
- // All remaining actions operate on a specific proposal.
- const proposalId = body.proposalId || body.proposal_id;
- if (!proposalId) return error(res, 400, 'validation_error', 'proposalId required');
- if (!isUuid(proposalId)) return error(res, 400, 'validation_error', 'proposalId must be a uuid');
- const [row] = await sql`SELECT * FROM agent_autopilot_proposals WHERE id = ${proposalId} AND agent_id = ${agentId}`;
- if (!row) return error(res, 404, 'not_found', 'proposal not found');
- const proposal = decorateProposal(row);
-
try {
if (action === 'dryrun') {
const preview = await dryRunProposal({ proposal, agent, config: getAutopilotConfig(agent.meta) });
diff --git a/api/dca-strategies.js b/api/dca-strategies.js
index 05c1a4987..d6cfc9f89 100644
--- a/api/dca-strategies.js
+++ b/api/dca-strategies.js
@@ -13,6 +13,7 @@ import { sql } from './_lib/db.js';
import { getSessionUser } from './_lib/auth.js';
import { cors, json, error, wrap, readJson, method, rateLimited } from './_lib/http.js';
import { requireCsrf } from './_lib/csrf.js';
+import { requireRealFundsAgreement } from './_lib/real-funds-agreement.js';
import { parse } from './_lib/validate.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import {
@@ -155,6 +156,8 @@ export default wrap(async (req, res) => {
return json(res, 200, { ok: true, data: paused });
}
+ if (!(await requireRealFundsAgreement(req, res, { userId: session.id, context: 'dca-resume' }))) return;
+
// Resuming onto a dead delegation would only fail on the next tick and
// re-pause the row, so refuse with the reason instead.
if (row.delegation_status !== 'active') {
@@ -364,6 +367,7 @@ export default wrap(async (req, res) => {
LIMIT 1
`;
if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (!(await requireRealFundsAgreement(req, res, { userId: session.id, context: 'dca-create' }))) return;
// Confirm delegation exists and is active, and belongs to this agent
const [delegation] = await sql`
diff --git a/api/irl/drops.js b/api/irl/drops.js
index 5d6eafda4..57509ef21 100644
--- a/api/irl/drops.js
+++ b/api/irl/drops.js
@@ -28,6 +28,7 @@ import { cors, json, wrap, error, rateLimited, readJson } from '../_lib/http.js'
import { ataExists } from '../_lib/solana/read-guards.js';
import { limits, clientIp, limitFailClosedRead } from '../_lib/rate-limit.js';
import { getSessionUser } from '../_lib/auth.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { readDeviceToken } from '../_lib/irl-auth.js';
import { verifyFixToken, fixEnforced } from '../_lib/irl-presence.js';
import { solanaConnection, loadAgentForSigning } from '../_lib/agent-pumpfun.js';
@@ -225,6 +226,7 @@ async function handleCreate(req, res, { body, userId, deviceToken, session }) {
// ── agent bounty (server-funded from the agent's custodial wallet) ─────────────
async function handleAgentBounty(req, res, { body, userId, agentId }) {
+ if (!(await requireRealFundsAgreement(req, res, { userId, context: 'irl-agent-bounty' }))) return;
const loaded = await loadAgentForSigning(agentId, userId, { reason: 'irl_bounty_fund' });
if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
const { agent, keypair, meta } = loaded;
diff --git a/api/labor/award.js b/api/labor/award.js
index cffe32084..7bf599c94 100644
--- a/api/labor/award.js
+++ b/api/labor/award.js
@@ -4,6 +4,7 @@
// is autonomous, the autopilot then performs + settles the job through to payout.
import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { authWrite, loadOwnedAgent, ownershipError, requireUuid } from '../_lib/labor-auth.js';
import { getBounty, getBid, listBidsForBounty, getJobByBounty } from '../_lib/agent-labor.js';
import { applyAward } from '../_lib/labor-match.js';
@@ -38,6 +39,9 @@ export default wrap(async (req, res) => {
if (!rawBid || rawBid.bounty_id !== bountyId) return error(res, 404, 'bid_not_found', 'bid not found for this bounty');
if (rawBid.status !== 'pending') return error(res, 409, 'bid_unavailable', `that bid is ${rawBid.status}`);
+ // Awarding commits the poster's escrowed reward to this worker's payout.
+ if (!(await requireRealFundsAgreement(req, res, { userId, context: 'labor-award' }))) return;
+
const shaped = (await listBidsForBounty(bountyId)).find((b) => b.id === bidId);
const winner = { ...shaped, worker_user_id: rawBid.worker_user_id, price_atomics: String(rawBid.price_atomics) };
const rationale = `Awarded by owner to ${winner.worker_name}: ${winner.price_three} $THREE, score ${winner.score ?? 'n/a'}.`;
diff --git a/api/labor/post.js b/api/labor/post.js
index 7f74ed422..a8d39503e 100644
--- a/api/labor/post.js
+++ b/api/labor/post.js
@@ -10,6 +10,7 @@
import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { authWrite, loadOwnedAgent, ownershipError, requireSolanaWallet, requireUuid } from '../_lib/labor-auth.js';
import { TOKEN_MINT } from '../_lib/token/config.js';
import { getTokenPriceUsd } from '../_lib/token/price.js';
@@ -71,6 +72,8 @@ export default wrap(async (req, res) => {
return ownershipError(res, e);
}
+ if (!(await requireRealFundsAgreement(req, res, { userId, context: 'labor-post' }))) return;
+
// Value the reward in real USD for the spend policy. Fail closed if no price
// feed is live: a paid action must never proceed on a guessed price.
let usd;
diff --git a/api/labor/settle.js b/api/labor/settle.js
index fe2c700e4..94db98c51 100644
--- a/api/labor/settle.js
+++ b/api/labor/settle.js
@@ -5,15 +5,18 @@
import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { authWrite, requireUuid } from '../_lib/labor-auth.js';
import { getJob, getJobByBounty, getBounty } from '../_lib/agent-labor.js';
import { runSettlement } from '../_lib/labor-settle.js';
-async function ownsEither(userId, posterAgentId, workerAgentId) {
+// Which side of the job the caller owns: { poster, worker }.
+async function ownedSides(userId, posterAgentId, workerAgentId) {
const rows = await sql`
SELECT id FROM agent_identities
WHERE id IN (${posterAgentId}, ${workerAgentId}) AND user_id = ${userId} AND deleted_at IS NULL`;
- return rows.length > 0;
+ const ids = new Set(rows.map((r) => r.id));
+ return { poster: ids.has(posterAgentId), worker: ids.has(workerAgentId) };
}
export default wrap(async (req, res) => {
@@ -35,7 +38,8 @@ export default wrap(async (req, res) => {
const job = jobId ? await getJob(jobId) : await getJobByBounty(bountyId);
if (!job) return error(res, 404, 'not_found', 'job not found');
- if (!(await ownsEither(userId, job.poster_agent_id, job.worker_agent_id))) {
+ const sides = await ownedSides(userId, job.poster_agent_id, job.worker_agent_id);
+ if (!sides.poster && !sides.worker) {
return error(res, 403, 'forbidden', 'only the poster or worker owner can settle this job');
}
@@ -46,6 +50,10 @@ export default wrap(async (req, res) => {
return error(res, 409, 'not_deliverable', `job is ${job.status}; nothing to settle until it is delivered`);
}
+ // The poster releasing its own escrow is a real-funds action; a worker settling
+ // to get paid is not.
+ if (sides.poster && !sides.worker && !(await requireRealFundsAgreement(req, res, { userId, context: 'labor-settle' }))) return;
+
const bounty = await getBounty(job.bounty_id);
const result = await runSettlement({ job, bounty });
return json(res, 200, { ok: true, job_id: job.id, settlement: result });
diff --git a/api/launch/mm.js b/api/launch/mm.js
index 0c7f975df..933e45599 100644
--- a/api/launch/mm.js
+++ b/api/launch/mm.js
@@ -19,6 +19,7 @@ import { cors, json, method, error, readJson, rateLimited, wrap } from '../_lib/
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { sql } from '../_lib/db.js';
import {
PRESETS, GUARDS, GRADUATION_ACTIONS, PolicyError,
@@ -34,6 +35,17 @@ const SSE_MAX_MS = 10 * 60_000;
// Lifecycle controls, as opposed to a create/update POST (no `action` param).
const LIFECYCLE_ACTIONS = ['pause', 'resume', 'kill', 'withdraw'];
+// True when applying `patch` moves the maker INTO live trading (enabled, not
+// killed, mode live) from any state that was not already live. Only that
+// transition needs the signed real-funds agreement; pause, kill and simulate
+// edits never do.
+function armsLiveMaker(existing, patch) {
+ const live = (p) => p.enabled === true && p.kill_switch !== true && p.mode === 'live';
+ const defined = Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== undefined));
+ const before = existing || { enabled: false, kill_switch: false, mode: 'simulate' };
+ return live({ ...before, ...defined }) && !(existing && live(existing));
+}
+
// An explicit network in the body wins over the query string: a POST carries its
// own mint + network pair, and honouring the query there let a stale `?network=`
// silently retarget the write at the other network's policy.
@@ -193,7 +205,9 @@ async function handlePost(req, res, url) {
return json(res, 200, { data: { policy: toPublicPolicy(row) } });
}
if (action === 'resume') {
- const row = await upsertPolicy({ mint, network, agentId, userId: auth.userId, patch: { enabled: true, kill_switch: false } });
+ const resumePatch = { enabled: true, kill_switch: false };
+ if (armsLiveMaker(existing, resumePatch) && !(await requireRealFundsAgreement(req, res, { userId: auth.userId, network, context: 'market-maker-arm' }))) return;
+ const row = await upsertPolicy({ mint, network, agentId, userId: auth.userId, patch: resumePatch });
return json(res, 200, { data: { policy: toPublicPolicy(row) } });
}
if (action === 'kill') {
@@ -215,6 +229,7 @@ async function handlePost(req, res, url) {
// Create or update from the supplied fields/preset.
const patch = normalizePolicyPatch(body, { isCreate: !existing });
+ if (armsLiveMaker(existing, patch) && !(await requireRealFundsAgreement(req, res, { userId: auth.userId, network, context: 'market-maker-arm' }))) return;
const row = await upsertPolicy({ mint, network, agentId, userId: auth.userId, patch });
return json(res, existing ? 200 : 201, { data: { policy: toPublicPolicy(row) } });
} catch (e) {
diff --git a/api/legal/risk-ack.js b/api/legal/risk-ack.js
index edb4fb181..033a05f7d 100644
--- a/api/legal/risk-ack.js
+++ b/api/legal/risk-ack.js
@@ -1,56 +1,84 @@
-// /api/legal/risk-ack — record a user's acceptance of the Risk Disclosure.
+// /api/legal/risk-ack: sign, and check, the real-funds agreements.
//
-// POST /api/legal/risk-ack { version, context?, path? }
-// → 200 { ok: true, recorded }
-// → 400 invalid_version, 413 payload_too_large,
-// 415 unsupported_media_type when the body is not a readable acceptance
+// GET /api/legal/risk-ack
+// → 200 { authenticated, signed, version, signedAt, documents, history? }
+// history (the account's past signatures) only with ?history=1 and a session.
//
-// The client-side gate (public/risk-ack.js) fires this after the user accepts
-// the real-funds risk acknowledgment. The acceptance itself lives in the
-// browser (localStorage, versioned); this endpoint writes the durable
-// server-side record into audit_log — who (when signed in), which disclosure
-// version, from which feature ('trade', 'snipe', 'x402-pay', …), when, from
-// where. The audit-log-cleanup cron exempts 'risk-ack-accept' (and
-// 'tos-accept') rows from its 365-day retention, so acceptance records
-// persist indefinitely.
+// POST /api/legal/risk-ack
+// { version, documents: {tos, risk, agentWallet}, attestations: {eligible, noLiability},
+// signatureName, context?, path? }
+// → 200 { ok: true, recorded: true, version }
+// → 400 invalid_body | invalid_version | document_not_accepted |
+// attestation_missing | invalid_signature
+// → 413 payload_too_large, 415 unsupported_media_type
+// → 503 signature_not_recorded when the durable write did not land
//
-// Anonymous acceptances are recorded too (userId null): the gate also runs in
-// third-party x402 embeds and pre-auth flows where no session exists.
+// The signing dialog (public/risk-ack.js) posts here before any real-funds
+// action. The row in legal_signatures is what requireRealFundsAgreement()
+// (api/_lib/real-funds-agreement.js) checks on every money-moving endpoint,
+// so a write that did not land is a failure the caller must see: the dialog
+// stays open and asks the person to sign again, rather than letting them walk
+// into a refusal on the very next request.
//
-// `recorded` reports whether the durable write actually landed, and the write
-// is awaited rather than fired and forgotten: an acceptance the caller was
-// told about but that never reached the database is exactly the failure this
-// endpoint exists to prevent. A dropped write still answers 200, because the
-// user did accept and their money action must not stall on our bookkeeping.
+// Anonymous signatures are recorded too (user_id null): a visitor funding
+// someone else's agent, or paying through the x402 embed on a merchant site,
+// signs before any session exists. The audit-log-cleanup cron exempts the
+// matching 'risk-ack-accept' audit rows from retention, and legal_signatures
+// is never pruned.
import { getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { logAuditNow } from '../_lib/audit.js';
-// The version constant is owned by the client gate, which is dependency-free
-// and importable from both worlds (see its header). Importing it here rather
-// than restating the number keeps the accepted version bound to the disclosure
-// that was actually shown; a client cannot record acceptance of a revision
-// that does not exist yet.
+import {
+ agreementRequirement,
+ currentSignatureFor,
+ recordRealFundsSignature,
+ signatureHistoryFor,
+ validateSignatureBody,
+} from '../_lib/real-funds-agreement.js';
import { RISK_ACK_VERSION } from '../../public/risk-ack.js';
-const SLUG = /^[a-z0-9][a-z0-9-]{0,39}$/;
-const PATH = /^\/[\x20-\x7e]{0,199}$/;
-
export default wrap(async function handler(req, res) {
- // '*' origin: the acknowledgment modal also runs inside the drop-in x402
- // embed on merchant sites; acceptance recording must not be blocked there.
- // Those requests are credential-less, so '*' is safe.
- if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;
- if (!method(req, res, ['POST'])) return;
+ // '*' origin: the signing dialog also runs inside the drop-in x402 embed on
+ // merchant sites. Those requests are credential-less and sign anonymously,
+ // so '*' is safe; a session-bearing signature only comes from our origin.
+ if (cors(req, res, { origins: '*', methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
const rl = await limits.publicIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- // Swallowing the read error collapsed every body failure into the version
- // complaint below, so an oversized or non-JSON POST was told its `version`
- // was wrong when the field was fine and the body was the problem. Report the
- // real cause (413 oversized, 415 wrong content-type, 400 unparseable).
+ if (req.method === 'GET') return handleStatus(req, res);
+ return handleSign(req, res);
+});
+
+async function handleStatus(req, res) {
+ const user = await getSessionUser(req).catch(() => null);
+ const base = { version: RISK_ACK_VERSION, documents: agreementRequirement().documents };
+ if (!user) {
+ return json(res, 200, { authenticated: false, signed: false, signedAt: null, ...base }, { 'cache-control': 'no-store' });
+ }
+ let signature;
+ try {
+ signature = await currentSignatureFor(user.id);
+ } catch {
+ return error(res, 503, 'status_unavailable', 'could not read your signed agreements, try again');
+ }
+ const out = {
+ authenticated: true,
+ signed: !!signature,
+ signedAt: signature?.signedAt ?? null,
+ signatureName: signature?.signatureName ?? null,
+ ...base,
+ };
+ const url = new URL(req.url, 'http://local');
+ if (url.searchParams.get('history') === '1') {
+ out.history = await signatureHistoryFor(user.id).catch(() => []);
+ }
+ return json(res, 200, out, { 'cache-control': 'no-store' });
+}
+
+async function handleSign(req, res) {
let body;
try {
body = await readJson(req, 10_000);
@@ -60,27 +88,19 @@ export default wrap(async function handler(req, res) {
status === 413 ? 'payload_too_large' : status === 415 ? 'unsupported_media_type' : 'bad_request';
return error(res, status, code, err?.message || 'could not read request body');
}
- const version = Number(body?.version);
- if (!Number.isInteger(version) || version < 1 || version > RISK_ACK_VERSION) {
+
+ const parsed = validateSignatureBody(body);
+ if (!parsed.ok) return error(res, 400, parsed.code, parsed.message);
+
+ const user = await getSessionUser(req).catch(() => null);
+ const recorded = await recordRealFundsSignature({ userId: user?.id ?? null, value: parsed.value, req });
+ if (!recorded) {
return error(
res,
- 400,
- 'invalid_version',
- `version must be an integer between 1 and ${RISK_ACK_VERSION}`,
+ 503,
+ 'signature_not_recorded',
+ 'your signature could not be saved; nothing was charged, please sign again',
);
}
- const context = typeof body?.context === 'string' && SLUG.test(body.context) ? body.context : null;
- const path = typeof body?.path === 'string' && PATH.test(body.path) ? body.path : null;
-
- const user = await getSessionUser(req).catch(() => null);
-
- const recorded = await logAuditNow({
- userId: user?.id ?? null,
- action: 'risk-ack-accept',
- resourceId: null,
- meta: { version, context, path },
- req,
- });
-
- return json(res, 200, { ok: true, recorded });
-});
+ return json(res, 200, { ok: true, recorded: true, version: RISK_ACK_VERSION }, { 'cache-control': 'no-store' });
+}
diff --git a/api/marketplace/buy-asset.js b/api/marketplace/buy-asset.js
index a9fd84a20..3cf47fc64 100644
--- a/api/marketplace/buy-asset.js
+++ b/api/marketplace/buy-asset.js
@@ -32,6 +32,7 @@ import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { rpcFallbackFromEnv } from '../_lib/solana/rpc-fallback.js';
import { isUuid } from '../_lib/validate.js';
import { solanaConnection } from '../_lib/solana/connection.js';
@@ -193,6 +194,7 @@ async function handleCreate(req, res) {
if (!agent) return error(res, 404, 'not_found', 'buyer agent not found');
if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
buyerAgent = agent;
+ if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, context: 'agent-asset-purchase' }))) return;
}
const [price] = await sql`
diff --git a/api/marketplace/purchase-as-agent.js b/api/marketplace/purchase-as-agent.js
index 78dc6e025..d7eddb952 100644
--- a/api/marketplace/purchase-as-agent.js
+++ b/api/marketplace/purchase-as-agent.js
@@ -33,6 +33,7 @@ import { sql } from '../_lib/db.js';
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, readJson, wrap, rateLimited, respondError } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
import { confirmSkillPurchase, resolvePayoutAddress, logEvent } from '../_lib/purchase-confirm.js';
@@ -99,6 +100,7 @@ export default wrap(async (req, res) => {
`;
if (!buyer) return error(res, 404, 'not_found', 'buyer agent not found');
if (buyer.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+ if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, context: 'agent-skill-purchase' }))) return;
// Self-dealing detection (buyer and seller owned by same user)
const [seller] = await sql`
diff --git a/api/oracle/watch.js b/api/oracle/watch.js
index f4675c3a0..2bd5730a4 100644
--- a/api/oracle/watch.js
+++ b/api/oracle/watch.js
@@ -21,6 +21,7 @@ import { sql } from '../_lib/db.js';
import { isUuid } from '../_lib/validate.js';
import { z } from 'zod';
import { getWatch, upsertWatch, recentActions, actionsSummary } from '../_lib/oracle/store.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
const NETWORKS = new Set(['mainnet', 'devnet']);
const TIERS = new Set(['prime', 'strong', 'lean', 'watch']);
@@ -127,6 +128,11 @@ export default wrap(async (req, res) => {
if (rawDaily != null && !(rawDaily >= perTrade)) {
return error(res, 400, 'validation_error', 'max_daily_sol must be at least per_trade_sol to arm a live agent');
}
+ // Only the move INTO live-armed needs the signed agreement; re-saving an
+ // already live-armed watch, simulate mode, and disarming stay open.
+ const current = await getWatch(cfg.agent_id, network);
+ const wasLiveArmed = current?.armed === true && current?.mode === 'live';
+ if (!wasLiveArmed && !(await requireRealFundsAgreement(req, res, { userId, network, context: 'oracle-watch-arm' }))) return;
}
// Sanitize telegram_chat_id: allow numeric IDs (positive or negative) and
diff --git a/api/portfolio/[action].js b/api/portfolio/[action].js
index 95c5ee24f..2143211bb 100644
--- a/api/portfolio/[action].js
+++ b/api/portfolio/[action].js
@@ -17,6 +17,7 @@ import { evmFallbackProvider } from '../_lib/evm/rpc.js';
import { limits } from '../_lib/rate-limit.js';
import { getSessionUser, isSameSiteOrigin } from '../_lib/auth.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { logAudit } from '../_lib/audit.js';
import { sql } from '../_lib/db.js';
import { getBalances, walletUsdTotal, invalidateBalances } from '../_lib/balances.js';
@@ -404,6 +405,7 @@ async function handleSend(req, res) {
if (!isSameSiteOrigin(req)) {
return error(res, 403, 'forbidden', 'cross-site request denied');
}
+ if (!(await requireRealFundsAgreement(req, res, { userId: user.id, context: 'portfolio-send' }))) return;
if (!(await requireCsrf(req, res, user.id))) return;
const rl = await limits.strict(`portfolio:send:${user.id}`);
diff --git a/api/pump/[action].js b/api/pump/[action].js
index 898937638..fedb09246 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -112,6 +112,7 @@ import { solanaConnection, loadAgentForSigning } from '../_lib/agent-pumpfun.js'
import { connectPumpFunFeed } from '../_lib/pumpfun-ws-feed.js';
import { makeRuntime } from '../_lib/skill-runtime.js';
import { loadWallet } from '../_lib/solana-wallet.js';
+import { requireRealFundsAgreement, currentSignatureFor } from '../_lib/real-funds-agreement.js';
import {
checkBuyAllowed,
reserveSpend,
@@ -1684,6 +1685,13 @@ async function handleLaunchConfirm(req, res) {
try {
const { normalizePolicyPatch, upsertPolicy } = await import('../_lib/market-maker.js');
const patch = normalizePolicyPatch(p.mm, { isCreate: true });
+ // The launch itself is already on-chain, so an unsigned real-funds
+ // agreement must not fail this confirm. Attach the maker disarmed instead;
+ // arming it later goes through /api/launch/mm, which enforces the agreement.
+ if (p.network !== 'devnet' && patch.enabled === true && patch.kill_switch !== true && patch.mode === 'live') {
+ const signed = await currentSignatureFor(user.id).catch(() => null);
+ if (!signed) patch.enabled = false;
+ }
await upsertPolicy({ mint: p.mint, network: p.network, agentId: p.agent_id, userId: user.id, patch });
} catch (e) {
console.warn('[pump/launch-confirm] market-maker attach skipped:', e?.code || e?.message);
@@ -1834,6 +1842,7 @@ async function handleLaunchAgent(req, res) {
});
if (!agent) return error(res, 404, 'not_found', 'agent not found');
const resolvedAgentId = agent.id;
+ if (!(await requireRealFundsAgreement(req, res, { userId: user.id, network: body.network, context: 'pump-launch-agent' }))) return;
const loaded = await loadAgentForSigning(resolvedAgentId, user.id, {
reason: 'studio_pump_launch',
@@ -3507,6 +3516,7 @@ async function handleStrategyRun(req, res) {
if (!auth) return error(res, 401, 'unauthorized', 'sign in required for live mode');
if (!body.agentId)
return error(res, 400, 'validation_error', 'agentId required for live mode');
+ if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, network, context: 'pump-strategy-run' }))) return;
try {
const r = await loadAgentWalletForStrategy(body.agentId, auth.userId);
wallet = r.wallet;
@@ -5028,7 +5038,7 @@ async function signSendWithAgent({ network, agentKeypair, instructions, extraSig
// Resolve the agent + mint the caller controls, and assert the agent's custodial
// wallet is the on-chain creator (agent_authority) of the coin. Returns
// { agent, mintRow, loaded, creator } or sends an error and returns null.
-async function resolveAgentFeeContext(req, res, body) {
+async function resolveAgentFeeContext(req, res, body, { agreementContext = null } = {}) {
const user = await requireSessionUser(req, res);
if (!user) return null;
@@ -5052,6 +5062,9 @@ async function resolveAgentFeeContext(req, res, body) {
error(res, 404, 'not_found', 'coin not found for this agent');
return null;
}
+ if (agreementContext && !(await requireRealFundsAgreement(req, res, { userId: user.id, network: body.network, context: agreementContext }))) {
+ return null;
+ }
const loaded = await loadAgentForSigning(agent.id, user.id, {
reason: 'studio_fee_action',
@@ -5224,7 +5237,8 @@ async function handleFeeSharingAgent(req, res) {
if (!rl.success) return rateLimited(res, rl);
const body = parse(feeSharingAgentSchema, await readJson(req));
- const ctx = await resolveAgentFeeContext(req, res, body);
+ // Redirects the coin's creator-fee revenue and pays config rent from the agent wallet.
+ const ctx = await resolveAgentFeeContext(req, res, body, { agreementContext: 'pump-fee-sharing' });
if (!ctx) return;
const newShareholders = body.shareholders.map((s) => {
diff --git a/api/signals/subscribe.js b/api/signals/subscribe.js
index 9959c3f29..74e35cc48 100644
--- a/api/signals/subscribe.js
+++ b/api/signals/subscribe.js
@@ -18,10 +18,23 @@
import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { sql } from '../_lib/db.js';
import { deliverSubscription } from '../_lib/signal-engine.js';
import { requireUser, loadOwnedAgent, normNetwork, parseRowId } from './_common.js';
+// A live subscription pays x402 USDC and mirrors trades from the subscriber
+// agent's custodial wallet. Turning one on (or delivering it now) needs the
+// signed real-funds agreement; simulate mode, pause, stop and kill never do.
+function isLiveRunning(row) {
+ return !!row && row.mode === 'live' && row.status === 'active' && row.killed !== true;
+}
+
+async function loadSub(subId, userId) {
+ const [row] = await sql`select * from signal_subscriptions where id = ${subId} and owner_user_id = ${userId} limit 1`;
+ return row || null;
+}
+
function num(v, fallback) { const n = Number(v); return Number.isFinite(n) ? n : fallback; }
function shapeSub(s) {
@@ -110,6 +123,10 @@ export default wrap(async (req, res) => {
// Instant kill: the halt path, takes precedence.
if (body.killed != null) {
const killed = body.killed === true || body.killed === 'true';
+ if (!killed) {
+ const cur = await loadSub(subId, userId);
+ if (cur?.mode === 'live' && !isLiveRunning(cur) && !(await requireRealFundsAgreement(req, res, { userId, network: normNetwork(cur.network), context: 'signal-subscribe' }))) return;
+ }
const [row] = await sql`
update signal_subscriptions set killed = ${killed}, status = ${killed ? 'paused' : 'active'}, updated_at = now()
where id = ${subId} and owner_user_id = ${userId} returning *
@@ -120,11 +137,16 @@ export default wrap(async (req, res) => {
if (body.action === 'sync') {
const [row] = await sql`select * from signal_subscriptions where id = ${subId} and owner_user_id = ${userId} limit 1`;
if (!row) return error(res, 404, 'not_found', 'subscription not found');
+ if (row.mode === 'live' && !(await requireRealFundsAgreement(req, res, { userId, network: normNetwork(row.network), context: 'signal-subscribe' }))) return;
const result = await deliverSubscription(row, { maxEvents: 10 });
return json(res, 200, { ok: true, ...result });
}
if (body.status) {
const status = ['active', 'paused', 'stopped'].includes(body.status) ? body.status : 'paused';
+ if (status === 'active') {
+ const cur = await loadSub(subId, userId);
+ if (cur?.mode === 'live' && !isLiveRunning(cur) && !(await requireRealFundsAgreement(req, res, { userId, network: normNetwork(cur.network), context: 'signal-subscribe' }))) return;
+ }
// Resuming clears any kill; pausing/stopping leaves the kill flag untouched.
const [row] = status === 'active'
? await sql`
@@ -160,6 +182,10 @@ export default wrap(async (req, res) => {
const slippageBps = Math.round(Math.max(0, Math.min(5000, num(body.slippage_bps, 300))));
const firewallLevel = body.firewall_level === 'warn' ? 'warn' : 'block';
const copyExits = body.copy_exits !== false;
+ if (mode === 'live') {
+ const [cur] = await sql`select mode, status, killed from signal_subscriptions where subscriber_agent_id = ${body.agent_id} and feed_id = ${feed.id} limit 1`;
+ if (!isLiveRunning(cur) && !(await requireRealFundsAgreement(req, res, { userId, network, context: 'signal-subscribe' }))) return;
+ }
// New subscriptions start at the current emission head: never charged for or
// made to mirror a backlog of signals emitted before they subscribed.
diff --git a/api/sniper/strategy.js b/api/sniper/strategy.js
index 91374c95d..32e44a351 100644
--- a/api/sniper/strategy.js
+++ b/api/sniper/strategy.js
@@ -17,6 +17,7 @@
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
import { solanaConnection } from '../_lib/solana/connection.js';
@@ -311,12 +312,6 @@ async function listStrategies(req, res, userId) {
// ── POST — upsert/arm strategy ───────────────────────────────────────────────
async function upsertStrategy(req, res, userId) {
- // Arming a sniper commits the agent's real custodial funds to autonomous
- // trading, so this state-changing write gets the same CSRF gate as withdraw
- // and the spend-limit endpoints. Machine (bearer) callers are exempt inside
- // requireCsrf, which is why the client already sends the token.
- if (!(await requireCsrf(req, res, userId))) return;
-
const body = await readJson(req);
// Treasury auto-funding moves SOL from the platform's launcher master into an
// agent wallet, so consent for it is granted by an operator against the row
@@ -457,6 +452,19 @@ async function upsertStrategy(req, res, userId) {
return error(res, 400, 'bad_request', 'min_claim_lamports cannot exceed max_claim_lamports');
}
+ // Only the transition INTO an armed state needs the signed agreement: disarming,
+ // the kill switch, and edits to an already-armed or disarmed strategy stay open.
+ const wasArmed = cur.enabled === true && cur.kill_switch !== true;
+ const willArm = next.enabled === true && next.kill_switch !== true;
+ if (willArm && !wasArmed && !(await requireRealFundsAgreement(req, res, { userId, network: p.network, context: 'sniper-arm' }))) return;
+
+ // Arming a sniper commits the agent's real custodial funds to autonomous
+ // trading, so this state-changing write gets the same CSRF gate as withdraw
+ // and the spend-limit endpoints. Machine (bearer) callers are exempt inside
+ // requireCsrf, which is why the client already sends the token. It runs after
+ // validation and the agreement gate so a refused save does not burn the token.
+ if (!(await requireCsrf(req, res, userId))) return;
+
const [row] = await sql`
insert into agent_sniper_strategies
(agent_id, user_id, network, enabled, kill_switch,
diff --git a/api/swarms/index.js b/api/swarms/index.js
index 1036cc469..6116cf949 100644
--- a/api/swarms/index.js
+++ b/api/swarms/index.js
@@ -20,12 +20,24 @@ import { cors, method, json, error, wrap, readJson, rateLimited } from '../_lib/
import { parseLimit, parseOffset } from '../_lib/http-params.js';
import { resolveAccount } from '../_lib/account-auth.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { limits } from '../_lib/rate-limit.js';
import {
createSwarm, joinSwarm, contributeToSwarm, exitSwarm, killSwarm,
- setSwarmPaused, listSwarms, listSwarmsForUser, parseContributionLamports, SwarmError,
+ setSwarmPaused, listSwarms, listSwarmsForUser, parseContributionLamports, SwarmError, getSwarm,
} from '../_lib/swarms.js';
+// Actions that move treasury funds or turn autonomous treasury trading on. kill,
+// pause and join move nothing, so they stay open without a signed agreement.
+const REAL_FUNDS_ACTIONS = new Set(['create', 'contribute', 'exit', 'resume']);
+
+async function swarmNetworkFor(body, action) {
+ if (action === 'create') return body.network === 'devnet' ? 'devnet' : 'mainnet';
+ if (!isUuid(body.swarm_id)) return undefined;
+ const swarm = await getSwarm(body.swarm_id);
+ return swarm?.network;
+}
+
const isUuid = (s) => typeof s === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);
function handleSwarmError(res, e) {
@@ -61,15 +73,20 @@ export default wrap(async (req, res) => {
// POST: all mutations require auth, CSRF (session callers), and a budget.
const auth = await resolveAccount(req, res);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
- if (!(await requireCsrf(req, res, auth.userId))) return;
- const rl = await limits.swarmMutate(auth.userId);
- if (!rl.success) return rateLimited(res, rl, 'too many swarm actions: slow down');
// Let readJson's own 415 / 400 surface (wrap() renders either from err.status).
// Swallowing it here answered a wrong content-type with `unknown action`, which
// sends the caller hunting through their action names for a body they never
- // managed to send.
+ // managed to send. The body is read before CSRF so the agreement gate can refuse
+ // a money action without burning the single-use token.
const body = await readJson(req);
const action = String(body?.action || '');
+ if (REAL_FUNDS_ACTIONS.has(action)) {
+ const network = await swarmNetworkFor(body, action);
+ if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, network, context: `swarm-${action}` }))) return;
+ }
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+ const rl = await limits.swarmMutate(auth.userId);
+ if (!rl.success) return rateLimited(res, rl, 'too many swarm actions: slow down');
try {
switch (action) {
diff --git a/api/user/wallet/fund-agent.js b/api/user/wallet/fund-agent.js
index 277625302..302617f3b 100644
--- a/api/user/wallet/fund-agent.js
+++ b/api/user/wallet/fund-agent.js
@@ -10,6 +10,7 @@
// account yet). Mirrors the simulate contract in send.js.
import { getSessionUser } from '../../_lib/auth.js';
+import { requireRealFundsAgreement } from '../../_lib/real-funds-agreement.js';
import { sql } from '../../_lib/db.js';
import { cors, json, error, wrap, method, readJson } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
@@ -49,6 +50,7 @@ export default wrap(async (req, res) => {
// Parsed before the limiter so a preview does not spend the 5-per-DAY
// withdrawal budget. See the matching note in send.js.
const simulate = body.simulate === true;
+ if (!simulate && !(await requireRealFundsAgreement(req, res, { userId: session.id, context: 'fund-agent' }))) return;
const rl = simulate
? await limits.walletSimulate(session.id)
: await limits.withdrawalPerUser(session.id);
diff --git a/api/user/wallet/send.js b/api/user/wallet/send.js
index 7629c1711..9ed66b008 100644
--- a/api/user/wallet/send.js
+++ b/api/user/wallet/send.js
@@ -3,6 +3,7 @@
// Body: { destination: string, amount: number | "max", asset: "SOL" | "<usdc-mint>" }
import { getSessionUser } from '../../_lib/auth.js';
+import { requireRealFundsAgreement } from '../../_lib/real-funds-agreement.js';
import { sql } from '../../_lib/db.js';
import { cors, json, error, wrap, method, readJson } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
@@ -41,6 +42,7 @@ export default wrap(async (req, res) => {
const network = 'mainnet';
const asset = typeof body.asset === 'string' && body.asset.trim() ? body.asset.trim() : 'SOL';
const simulate = body.simulate === true;
+ if (!simulate && !(await requireRealFundsAgreement(req, res, { userId: session.id, network, context: 'master-send' }))) return;
// The body is parsed before the limiters on purpose: a simulate moves no
// funds, so it must not draw on the 5-per-DAY withdrawal budget. Charging
diff --git a/api/vaults/[id].js b/api/vaults/[id].js
index 20e006992..f458ef795 100644
--- a/api/vaults/[id].js
+++ b/api/vaults/[id].js
@@ -19,6 +19,7 @@ import {
TERM_BOUNDS, clampTermBps,
} from '../_lib/vault-accounting.js';
import { isUuid } from '../_lib/validate.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
function idFromReq(req) {
const fromQuery = req.query?.id;
@@ -123,6 +124,7 @@ async function handlePatch(req, res, id) {
}
if (action === 'resume') {
if (vault.status === 'closed') return error(res, 409, 'closed', 'vault is closed');
+ if (!(await requireRealFundsAgreement(req, res, { userId: who.userId, network: vault.network, context: 'vault-resume' }))) return;
const next = await setVaultStatus(vault.id, 'open', { haltReason: null });
await recordVaultEvent({ vaultId: vault.id, type: 'resume', userId: who.userId, reason: 'owner resumed trading' });
return json(res, 200, { data: { vault: next } }, { 'cache-control': 'no-store' });
diff --git a/api/vaults/index.js b/api/vaults/index.js
index 295b4e462..e8e98f2e2 100644
--- a/api/vaults/index.js
+++ b/api/vaults/index.js
@@ -16,6 +16,7 @@ import { createVault, listVaults, listBackedVaults, recordVaultEvent } from '../
import { generateVaultWallet } from '../_lib/vault-wallet.js';
import { usdcToAtomics, sharePriceE6, roiBps, toBig, TERM_BOUNDS, clampTermBps } from '../_lib/vault-accounting.js';
import { isUuid } from '../_lib/validate.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
function clampInt(v, bound) {
return clampTermBps(v, bound) ?? bound.def;
@@ -96,6 +97,7 @@ async function handleOpen(req, res) {
// Reputation gate: only a verifiably-skilled agent can open a vault.
try { await assertReputationVerified(agentId, network); } catch (e) { return error(res, e.status || 403, e.code || 'forbidden', e.message, e.detail || {}); }
+ if (!(await requireRealFundsAgreement(req, res, { userId, network, context: 'vault-open' }))) return;
// Required risk terms.
const maxPerTradeUsdc = Number(body.maxPerTradeUsdc ?? body.max_per_trade_usdc);
diff --git a/api/x402-pay.js b/api/x402-pay.js
index e49307e79..2129a0a02 100644
--- a/api/x402-pay.js
+++ b/api/x402-pay.js
@@ -49,6 +49,7 @@ import { thumbnailUrl } from './_lib/r2.js';
import { logger } from './_lib/usage.js';
import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
import { recoverSolanaAgentKeypair } from './_lib/agent-wallet.js';
+import { requireRealFundsAgreement } from './_lib/real-funds-agreement.js';
import { SpendLimitError, reserveSpendUsd, updateCustodyEvent, releaseSpendReservation } from './_lib/agent-trade-guards.js';
import { validatePublicUrl, resolvePublicHost, pinnedAgent, SsrfError } from './_lib/ssrf.js';
import { BUILDER_CODE } from './_lib/x402-builder-code.js';
@@ -1065,6 +1066,7 @@ async function handleExternalPay(req, res, input, ip) {
// CSRF on the settle path (funds move + the agent key signs). The preview branch
// above returns before this point, so a live price probe never burns a token.
// Bearer/API-key callers are exempt inside requireCsrf.
+ if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, context: 'x402-pay' }))) return;
if (!(await requireCsrf(req, res, auth.userId))) return;
const spendGuard = { agentId, userId: auth.userId, meta: loaded.meta, network: 'mainnet' };
@@ -1208,6 +1210,7 @@ export default wrap(async (req, res) => {
if (routing.mode === 'agent') {
const auth = await requireAuth(req);
if (!auth) return json(res, 401, { error: 'authentication_required' });
+ if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, context: 'x402-pay' }))) return;
const loaded = await loadAgentKeypairForUser(routing.agentId, auth.userId);
if (!loaded) return json(res, 403, { error: 'agent_not_found_or_no_solana_wallet' });
// CSRF: this tool call pays from the agent's own wallet. Bearer callers exempt.
diff --git a/api/x402/pay-by-name.js b/api/x402/pay-by-name.js
index 0bf889e7f..4dd2b4004 100644
--- a/api/x402/pay-by-name.js
+++ b/api/x402/pay-by-name.js
@@ -54,6 +54,7 @@ import {
verifyPayment,
} from '../_lib/x402-spec.js';
import { logPaymentEvent } from '../_lib/x402/audit-log.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');
const USDC_DECIMALS = 6;
@@ -382,6 +383,7 @@ async function handleSend(req, res, auth, body) {
return error(res, 400, 'invalid_recipient', 'resolved address is not a valid wallet (off-curve)');
}
+ if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, context: 'pay-by-name' }))) return;
const loaded = await loadAgentForSigning(agentId, auth.userId, {
reason: 'x402_pay_by_name',
meta: { name: body?.name, amount_usdc: Number(amountAtoms) / 10 ** USDC_DECIMALS },
diff --git a/data/changelog.json b/data/changelog.json
index c26c950de..7abf7badb 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-09-17",
+ "title": "Sign the real-funds agreements once before using real money",
+ "summary": "three.ws is experimental technology, and agent wallets are custodial software, not bank accounts. Before you deposit into an agent wallet, trade, send, withdraw, arm autopilot, or pay with real funds, you now sign three agreements in one step: the Terms of Service, the Risk Disclosure, and the new Agent Wallet Agreement. You tick each one, confirm you are eligible and that you understand funds can be lost for any reason with nothing insured, and type your name as your signature. An agent's deposit address now appears only after signing, and every deposit is covered by the Agent Wallet Agreement. When you are signed in, the signature is saved to your account and the servers refuse real-funds actions from unsigned accounts, including through the API, so it cannot be skipped. You can review every signature you have made at /legal/agreements. Devnet stays free of this step.",
+ "tags": ["security", "feature"],
+ "link": "/legal/agreements"
+ },
{
"date": "2026-09-17",
"title": "Coin pages show the numbers, not a score",
diff --git a/data/pages.json b/data/pages.json
index 2a57f1f0f..7eef15d5c 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -6385,11 +6385,27 @@
{
"path": "/legal/risk",
"title": "Risk Disclosure",
- "description": "Risk disclosure for real-funds features: experimental software, total-loss risk, autonomous agents, no liability.",
+ "description": "Risk disclosure for real-funds features: experimental software, total-loss risk, autonomous agents, uninsured custodial agent wallets, no liability.",
"priority": 0.2,
"changefreq": "yearly",
"added": "2026-07-03"
},
+ {
+ "path": "/legal/agent-wallet",
+ "title": "Agent Wallet Agreement",
+ "description": "The agreement governing every agent wallet: experimental custodial software, deposits by anyone at their own risk, no insurance, no guaranteed withdrawal or recovery, and no liability for lost funds.",
+ "priority": 0.3,
+ "changefreq": "yearly",
+ "added": "2026-09-17"
+ },
+ {
+ "path": "/legal/agreements",
+ "title": "Real-Funds Agreements",
+ "description": "Sign, and review your signatures on, the Terms of Service, Risk Disclosure, and Agent Wallet Agreement required before any real-funds action.",
+ "priority": 0.3,
+ "changefreq": "monthly",
+ "added": "2026-09-17"
+ },
{
"path": "/legal/content-policy",
"title": "Content Policy",
diff --git a/docs/risk-acknowledgment.md b/docs/risk-acknowledgment.md
index 7d5137d9f..d9aef949a 100644
--- a/docs/risk-acknowledgment.md
+++ b/docs/risk-acknowledgment.md
@@ -1,98 +1,210 @@
-# The real-funds risk acknowledgment
-
-Every feature on three.ws that can move real money is gated behind a one-time,
-versioned risk acknowledgment. Before a user's first real-funds action — a
-trade, a sniper arm, a withdrawal, a swap, a token launch, an x402 payment, a
-fiat onramp — a dialog asks them to read and accept the
-[Risk Disclosure](https://three.ws/legal/risk): three.ws is experimental
-software, losses can be total, autonomous agents act without asking again, and
-they use real funds entirely at their own risk. Decline and the money action
-simply doesn't run; everything else on the platform keeps working.
-
-## How it behaves
-
-- **Once per browser.** Acceptance is stored in `localStorage` under
- `threews:risk-ack` as `{ version, acceptedAt, context }`. Every gated surface
- shares the same record — accepting in the trade tab also satisfies the swap
- modal, the launcher, and every other gate.
-- **Versioned.** The current disclosure version is `RISK_ACK_VERSION` in
- [`public/risk-ack.js`](../public/risk-ack.js). If the disclosure changes
- materially, bump that constant (and the version line on
- [`public/legal/risk.html`](../public/legal/risk.html)) — every user is then
- re-prompted before their next real-funds action. Stored acceptances with an
- older version no longer count.
-- **Recorded server-side.** On accept, the client fires
- `POST /api/legal/risk-ack` ([`api/legal/risk-ack.js`](../api/legal/risk-ack.js)),
- which writes a `risk-ack-accept` row into `audit_log`: user id when signed
- in (null otherwise), disclosure version, the feature context, path, IP, and
- user agent. The handler awaits that write and answers
- `200 { ok: true, recorded }`, where `recorded` says whether the row actually
- landed; a dropped write still answers 200 because the user did accept. It
- imports `RISK_ACK_VERSION` from the client gate and rejects any `version`
- outside `1..RISK_ACK_VERSION` with `400 invalid_version`, so nobody can
- record acceptance of a revision that does not exist yet; an unreadable body
- gets its real cause (`413 payload_too_large`, `415 unsupported_media_type`,
- or `400 bad_request`) instead of a version complaint. The
- `audit-log-cleanup` cron prunes `audit_log` at 365 days but exempts
- `risk-ack-accept` (and `tos-accept`) rows, so acceptance records persist
- indefinitely. The client's call is fire-and-forget (`keepalive`, errors
- swallowed): a failed network call never blocks the user's accepted state.
-- **Devnet stays friction-free.** Surfaces that know their network only gate
- when it isn't `devnet`. Simulation modes (e.g. Oracle arm's simulate mode)
- are never gated.
-- **Fails closed on "no", degrades gracefully on breakage.** If the user never
- accepts, `ensureRiskAck()` resolves `false` and the caller must abort the
- money action. But the gate machinery itself can never brick a feature:
- `ensureRiskAck()` **never rejects**. If `/risk-ack.js` fails to load (broken
- deploy, blocked request) or the `<dialog>` can't open (unsupported browser),
- the gate degrades to a native `confirm()` carrying the same core
- acknowledgment text — the user is still asked, the feature still works. The
- x402 embed loads the gate lazily for the same reason: a gate failure must
- never take the payment modal down with it. A failed `POST` to the recording
- endpoint never blocks an accepted state. Verified in-browser: blocked module,
- throwing `showModal`, and a 500ing endpoint all leave every feature usable.
-
-## Wiring a new money surface
-
-Any new feature that commits real funds MUST call the gate before executing.
-From bundled app code (`src/`):
+# The real-funds agreements
+
+three.ws is experimental technology, and agent wallets are custodial software,
+not bank accounts. Before anyone uses real money on the platform, they sign
+three agreements in one step:
+
+- the [Terms of Service](https://three.ws/legal/tos) (version 3),
+- the [Risk Disclosure](https://three.ws/legal/risk) (version 2),
+- the [Agent Wallet Agreement](https://three.ws/legal/agent-wallet) (version 1).
+
+Together they say: this is experimental software; anything deposited into,
+held in, or sent from an agent wallet can be lost completely for any reason
+(bugs, hacks, lost keys, autonomous agent decisions, third-party failures, the
+service shutting down); nothing is insured; withdrawal or recovery is never
+guaranteed; deposits by anyone are at the depositor's own risk; and three.ws is
+not responsible for any loss.
+
+People review and sign at [/legal/agreements](https://three.ws/legal/agreements),
+or in the dialog that opens the first time they reach a real-funds action.
+
+## What signing means
+
+The dialog requires, before the Sign button enables:
+
+1. A checkbox for each document, each linking to its full text.
+2. An eligibility attestation (18 or older, not sanctioned, lawful where they live).
+3. A no-liability attestation (experimental technology, total loss possible,
+ nothing insured, three.ws not responsible).
+4. A typed full name, which is the electronic signature.
+
+Pressing **Sign and continue** posts the signature to `POST /api/legal/risk-ack`
+and waits for it to be stored. If the write does not land, the dialog stays
+open with an error and nothing proceeds: the servers enforce the signature, so
+letting someone through on an unrecorded signature would only walk them into a
+refusal.
+
+## Enforcement: the server, not the dialog
+
+Every endpoint where the platform signs with a custodial key on a user's
+request calls one helper before any transaction is built:
```js
-import { ensureRiskAck } from './shared/risk-ack.js'; // adjust the relative path
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
-async function onConfirm() {
- if (!(await ensureRiskAck({ context: 'my-feature' }))) return; // declined
- // … move real funds …
+if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, network, context: 'withdraw' }))) return;
+```
+
+It resolves `true` when the account has a signature at or above the current
+version, and otherwise sends the response and resolves `false`:
+
+| Status | `error` | When |
+|---|---|---|
+| 403 | `risk_ack_required` | The account has not signed the current agreements |
+| 401 | `unauthorized` | No user resolved |
+| 503 | `agreement_check_unavailable` | The signature lookup failed; fails closed, nothing is sent |
+
+A `403` body tells any client, including scripts and API-key callers, exactly
+where to go:
+
+```json
+{
+ "error": "risk_ack_required",
+ "error_description": "Sign the real-funds agreements (Terms of Service, Risk Disclosure, and Agent Wallet Agreement) before using real funds. Nothing was sent. Sign at https://three.ws/legal/agreements",
+ "context": "withdraw",
+ "version": 2,
+ "sign_url": "https://three.ws/legal/agreements",
+ "documents": [
+ { "key": "tos", "title": "Terms of Service", "version": 3, "url": "https://three.ws/legal/tos" },
+ { "key": "risk", "title": "Risk Disclosure", "version": 2, "url": "https://three.ws/legal/risk" },
+ { "key": "agentWallet", "title": "Agent Wallet Agreement", "version": 1, "url": "https://three.ws/legal/agent-wallet" }
+ ]
}
```
-From plain `public/` scripts or third-party embeds:
+Rules the helper and its call sites follow:
+
+- **Session and API key alike.** An API key acts for its owner's account, so an
+ unsigned account's key is refused too. Sign in as the key's owner and sign once.
+- **Devnet is exempt.** Pass the request's `network`; `'devnet'` skips the check.
+- **Previews, quotes, simulations, and dry runs are never gated.** Nothing moves.
+- **Turning spending off is never gated.** Disarming autopilot, a kill switch, or
+ cancelling a strategy always works; only turning spending on is gated.
+- **Checked before CSRF** where the handler allows it, so a refusal does not burn
+ the caller's single-use CSRF token.
+- **Scheduled automation is not interrupted.** Crons that act on strategies a user
+ already armed keep running (stopping them could strand open positions); the gate
+ sits at the moment spending is turned on.
+- **Self-custody signing is gated in the client only.** Flows where the user signs
+ in their own wallet (self-custody launches, swaps, token pay) are gated by the
+ dialog; the platform never holds those keys.
+
+Positive lookups are cached in-process for 10 minutes (signatures are append-only
+and the required version only changes on deploy); negative results are never
+cached, so a fresh signature takes effect on the next request.
+
+### The coverage guard
+
+[`tests/real-funds-agreement-coverage.test.js`](../tests/real-funds-agreement-coverage.test.js)
+scans every route under `api/` (excluding `api/_lib/` and `api/cron/`) that
+decrypts a custodial key or imports a library that does. Each one must either
+call `requireRealFundsAgreement` or appear in the test's exemption list with a
+written reason. A new money endpoint that forgets the gate fails `npm test`.
+
+## The record
+
+Signatures are stored append-only in `legal_signatures`
+([migration](../api/_lib/migrations/20260917180000_legal_signatures.sql)):
+
+| Column | Holds |
+|---|---|
+| `user_id` | The signed-in account, or null for an anonymous signature. No foreign key, so the record outlives account deletion |
+| `bundle_version` | The agreement bundle version (`RISK_ACK_VERSION`) |
+| `documents` | Per document: the version signed and the sha256 of that page's `<main>` text as served at signing time |
+| `signature_name` | The typed name, NFKC-normalized |
+| `attestations` | The attestations confirmed |
+| `context`, `path` | Which feature and page prompted the signature |
+| `ip`, `user_agent`, `created_at` | Where and when |
+
+Each signature also writes a `risk-ack-accept` row to `audit_log`, which the
+audit-log-cleanup cron exempts from retention.
+
+### The endpoint
+
+`GET /api/legal/risk-ack` returns the caller's status:
+
+```json
+{ "authenticated": true, "signed": true, "signedAt": "2026-09-17T18:04:11.000Z", "signatureName": "Ada Lovelace", "version": 2, "documents": [ ... ] }
+```
+
+Add `?history=1` (signed in) to include every past signature. `POST` records a
+signature and answers `200 { ok: true, recorded: true, version }`, `400` with
+`invalid_version`, `document_not_accepted`, `attestation_missing`, or
+`invalid_signature` when the body is not a complete signature, or `503
+signature_not_recorded` when the write did not land.
+
+## Anonymous signatures and deposits
+
+Anyone can fund an agent, including visitors with no account, and anyone can
+send tokens to a public address without visiting three.ws at all. So:
+
+- The Deposit tab in the agent wallet hub, and the deposit sheet on `/wallet`,
+ hide the address on mainnet until the visitor signs. A visitor with no session
+ signs anonymously; the signature covers that browser.
+- Tips from a connected wallet (the tip modal) require a signature.
+- The Agent Wallet Agreement states that every deposit, by anyone and by any
+ means, is governed by it, and a notice under the deposit address says so.
+
+For a signed-in visitor, the client never trusts a signature cached in this
+browser on its own: it confirms the account's server record once per page, so a
+signature left by an anonymous visit or another account does not stand in for
+this account's.
+
+## Client API
+
+The canonical module is [`public/risk-ack.js`](../public/risk-ack.js), served
+at `/risk-ack.js`, dependency-free so plain pages and third-party embeds can
+import it. Bundled app code imports the wrapper
+[`src/shared/risk-ack.js`](../src/shared/risk-ack.js), which never rejects and
+degrades to a native `confirm()` if the module fails to load.
```js
-import { ensureRiskAck } from './risk-ack.js'; // resolves on the three.ws origin
+import { ensureRiskAck, hasRiskAckVerified, fetchWithRiskAck } from './shared/risk-ack.js';
+
+// Gate an action. Resolves false when the person declines: abort.
+if (!(await ensureRiskAck({ context: 'trade' }))) return;
+
+// Decide what to render without prompting (e.g. whether to show a deposit address).
+const signed = await hasRiskAckVerified();
+
+// Let a request re-prompt on the server's refusal and retry once after signing.
+const res = await fetchWithRiskAck('/api/agents/abc/solana/withdraw', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ destination, amount, network: 'mainnet' }),
+}, { context: 'withdraw' });
```
-`context` is a short kebab-case slug of the gated action (`trade`, `snipe`,
-`withdraw`, `swap`, `launch`, `x402-pay`, `onramp`, …). It is stored with the
-acceptance record so the audit trail shows which feature prompted it. The call
-is idempotent — once accepted it resolves `true` instantly, so gating multiple
-layers of the same flow costs nothing.
+`ensureRiskAck({ force: true })` ignores any cached signature and asks again;
+`fetchWithRiskAck` uses it after a `risk_ack_required` response.
-The canonical implementation lives in [`public/risk-ack.js`](../public/risk-ack.js)
-(dependency-free, served at `/risk-ack.js`); [`src/shared/risk-ack.js`](../src/shared/risk-ack.js)
-is a thin wrapper for bundled code. Pure logic (`parseAckRecord`,
-`isAckCurrent`) is covered by [`tests/risk-ack.test.js`](../tests/risk-ack.test.js).
+## Changing a document
-## Currently gated surfaces
+1. Edit the page under `public/legal/` and update its version and effective date.
+2. Bump that document's `version` in `AGREEMENT_DOCUMENTS` and bump
+ `RISK_ACK_VERSION` in [`public/risk-ack.js`](../public/risk-ack.js).
+3. Deploy. Every signature below the new bundle version stops counting on the
+ client and the server, and everyone signs again before their next real-funds
+ action. People who do not accept can ask support to return their agent wallet
+ balance (Agent Wallet Agreement, section 15).
+
+Bumping `TOS_VERSION` in [`api/_lib/legal.js`](../api/_lib/legal.js) separately
+keeps the sign-in clickwrap record in step with the Terms version.
+
+## Gated surfaces (client)
| Surface | Entry point | Context |
|---|---|---|
-| Agent wallet — trade | `src/agent-wallet-hub/tabs/trade.js` | `trade` |
-| Agent wallet — withdraw | `src/agent-wallet-hub/tabs/withdraw.js` | `withdraw` |
-| Agent wallet — give | `src/agent-wallet-hub/tabs/give.js` | `give` |
-| Agent wallet — arm sniper | `src/agent-wallet-hub/tabs/snipe.js` | `snipe` |
-| Agent wallet — arm autopilot | `src/agent-wallet-hub/tabs/autopilot.js` | `autopilot` |
-| Agent wallet — x402 pay | `src/agent-wallet-hub/tabs/pay.js` | `x402-pay` |
+| Agent wallet: deposit address | `src/agent-wallet-hub/tabs/deposit.js` | `deposit` |
+| Agent wallet: trade | `src/agent-wallet-hub/tabs/trade.js` | `trade` |
+| Agent wallet: withdraw | `src/agent-wallet-hub/tabs/withdraw.js` | `withdraw` |
+| Agent wallet: give | `src/agent-wallet-hub/tabs/give.js` | `give` |
+| Agent wallet: arm sniper | `src/agent-wallet-hub/tabs/snipe.js` | `snipe` |
+| Agent wallet: arm autopilot | `src/agent-wallet-hub/tabs/autopilot.js` | `autopilot` |
+| Agent wallet: x402 pay | `src/agent-wallet-hub/tabs/pay.js` | `x402-pay` |
+| Tip an agent from a connected wallet | `src/shared/agent-tip-modal.js` | `tip` |
+| Master wallet: deposit, send, fund agent | `src/master-wallet.js` | `deposit`, `master-send`, `fund-agent` |
| Oracle arm (live mode only) | `src/arm.js` | `oracle-arm` |
| Jupiter swap modal | `src/swap-jupiter.js` | `swap` |
| pump.fun token launch | `src/pump/launch-token-modal.js` | `launch` |
@@ -103,18 +215,15 @@ is a thin wrapper for bundled code. Pure logic (`parseAckRecord`,
| Forge pay-per-generation | `src/forge-pay.js` | `forge-pay` |
| Add funds / Coinbase onramp | `src/shared/add-funds.js` | `onramp` |
| Drop-in x402 modal (incl. merchant embeds) | `public/x402.js` | `x402-pay` |
+| Review and sign page | `public/legal/agreements.html` | `agreements-page` |
-If you add a surface, add its row here and its gate call in the code — both in
-the same change.
-
-Known gap: the master-wallet page ([/wallet](https://three.ws/wallet),
-`src/master-wallet.js`) moves real funds through its send and fund-agent flows
-but does not call `ensureRiskAck()` yet; it relies on its own simulate-then-
-confirm step instead. Wiring it through the gate is an open task, per the rule
-above.
+If you add a surface, add its row here and its gate call in the code, and if it
+signs with a custodial key, call `requireRealFundsAgreement` in its handler: all
+in the same change.
## Related
-- [Risk Disclosure](https://three.ws/legal/risk) — the full legal text users accept
-- [Custody you can verify](./custody.md) — the spend-limit and freeze controls that bound what agents can do after acceptance
-- [Terms of Service](https://three.ws/legal/tos) — §8 Limitation of Liability, which this acknowledgment supplements
+- [Agent Wallet Agreement](https://three.ws/legal/agent-wallet)
+- [Risk Disclosure](https://three.ws/legal/risk)
+- [Terms of Service](https://three.ws/legal/tos), section 8
+- [Custody you can verify](./custody.md): the spend limits and freezes that bound what agents can do after signing
diff --git a/public/features.json b/public/features.json
index 9871ec2bb..7b64a33e9 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-17T04:57:12.808Z",
+ "generated_at": "2026-09-17T06:50:17.707Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/legal/agent-wallet.html b/public/legal/agent-wallet.html
new file mode 100644
index 000000000..9289b8720
--- /dev/null
+++ b/public/legal/agent-wallet.html
@@ -0,0 +1,171 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot, no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Agent Wallet Agreement · three.ws</title>
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/tokens.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <style>
+ * { box-sizing: border-box; }
+ body {
+ font: 16px/1.7 -apple-system, system-ui, 'Segoe UI', sans-serif;
+ background: var(--bg-0);
+ color: var(--ink);
+ margin: 0;
+ }
+ .wrap { max-width: 720px; margin: 0 auto; padding: 48px 24px 80px; }
+ main.wrap:focus { outline: none; }
+ h1 { font-size: 32px; color: var(--ink-bright); margin: 0 0 6px; letter-spacing: -.02em; }
+ .meta { color: var(--ink-faint); font-size: 14px; margin: 0 0 40px; }
+ h2 { font-size: 18px; color: var(--ink-bright); margin: 40px 0 10px; }
+ p, li { color: var(--ink); font-size: 15px; }
+ ul { padding-left: 20px; }
+ li { margin-bottom: 6px; }
+ a { color: var(--ink-bright); }
+ hr { border: none; border-top: 1px solid var(--stroke); margin: 48px 0; }
+ .foot { color: var(--ink-faint); font-size: 13px; }
+ .callout {
+ border: 1px solid color-mix(in srgb, var(--warn) 35%, transparent);
+ background: color-mix(in srgb, var(--warn) 8%, var(--bg-0));
+ border-radius: 10px;
+ padding: 14px 18px; margin: 0 0 32px;
+ }
+ .callout p { color: color-mix(in srgb, var(--warn) 40%, var(--ink)); margin: 0 0 8px; font-size: 15px; }
+ .callout p:last-child { margin-bottom: 0; }
+ .caps { font-weight: 600; }
+ </style>
+
+ <meta name="description" content="The agreement that governs every agent wallet on three.ws: experimental custodial software, deposits by anyone at their own risk, no insurance, no guaranteed recovery, and no liability for lost funds.">
+ <link rel="canonical" href="https://three.ws/legal/agent-wallet">
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:title" content="Agent Wallet Agreement · three.ws">
+ <meta property="og:description" content="The agreement that governs every agent wallet on three.ws: deposits at your own risk, no insurance, no guaranteed recovery, no liability for lost funds.">
+ <meta property="og:url" content="https://three.ws/legal/agent-wallet">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=legal&amp;t=Agent+Wallet+Agreement&amp;d=Deposits+at+your+own+risk%2C+no+insurance%2C+no+guaranteed+recovery%2C+no+liability+for+lost+funds.&amp;p=%2Flegal%2Fagent-wallet">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:title" content="Agent Wallet Agreement · three.ws">
+ <meta name="twitter:description" content="Deposits at your own risk, no insurance, no guaranteed recovery, no liability for lost funds.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=legal&amp;t=Agent+Wallet+Agreement&amp;d=Deposits+at+your+own+risk%2C+no+insurance%2C+no+guaranteed+recovery%2C+no+liability+for+lost+funds.&amp;p=%2Flegal%2Fagent-wallet">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Agent Wallet Agreement","description":"The agreement that governs every agent wallet on three.ws.","url":"https://three.ws/legal/agent-wallet","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
+ <meta property="og:locale" content="en_US">
+ <meta property="og:image:alt" content="Agent Wallet Agreement, three.ws">
+ <meta name="twitter:site" content="@trythreews">
+</head>
+<body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+<main id="main-content" class="wrap" tabindex="-1">
+ <h1>Agent Wallet Agreement</h1>
+ <p class="meta">Effective: September 17, 2026 &nbsp;·&nbsp; Version 1 &nbsp;·&nbsp; <a href="/legal/tos">Terms of Service</a> &nbsp;·&nbsp; <a href="/legal/risk">Risk Disclosure</a> &nbsp;·&nbsp; <a href="/legal/agreements">Sign or review your agreements</a></p>
+
+ <div class="callout">
+ <p><strong>Plain summary:</strong> an agent wallet is experimental software, not a bank account. Anything you or anyone else deposits into one can be lost, completely and permanently, for reasons that include bugs, hacks, autonomous agent decisions, third-party failures, and the Service shutting down. Nothing is insured. We do not guarantee that funds can be withdrawn or recovered.</p>
+ <p><strong>three.ws is not responsible for any loss of funds held in, sent to, or sent from an agent wallet, for any reason.</strong> If you do not accept that, do not deposit.</p>
+ </div>
+
+ <p>This Agent Wallet Agreement ("Agreement") is a binding contract between you and the operator of three.ws ("three.ws", "we", "us", "our"). It governs every agent wallet on the three.ws service ("Service"), and every deposit, transfer, trade, payment, or other movement of funds or digital assets into, out of, or by an agent wallet. It is part of, and incorporated into, the <a href="/legal/tos">Terms of Service</a> ("Terms"), and it is read together with the <a href="/legal/risk">Risk Disclosure</a>. If this Agreement conflicts with the Terms on a matter concerning agent wallets, this Agreement controls.</p>
+
+ <p>Capitalized terms not defined here have the meaning given in the Terms. Read this Agreement in full before depositing. The English version controls over any translation.</p>
+
+ <h2>1. Definitions</h2>
+ <ul>
+ <li><strong>"Agent Wallet"</strong> means any blockchain address the Service generates for, assigns to, or associates with an agent, avatar, swarm, vault, master wallet, or other object on the Service, on any chain, together with the software that controls it.</li>
+ <li><strong>"Deposit"</strong> means any transfer of SOL, USDC, $THREE, or any other token, coin, NFT, or digital asset to an Agent Wallet address, by any person, by any means, whether through the Service's interface, a QR code, a wallet app, an exchange withdrawal, a smart contract, or a direct on-chain transfer.</li>
+ <li><strong>"Owner"</strong> means the account that controls the agent to which an Agent Wallet belongs.</li>
+ <li><strong>"Depositor"</strong> means any person who makes a Deposit, whether or not that person is the Owner or has an account.</li>
+ <li><strong>"Funds"</strong> means all assets held at, sent to, or sent from an Agent Wallet.</li>
+ </ul>
+
+ <h2>2. Experimental technology</h2>
+ <p>Agent Wallets are an experiment in autonomous, agent-controlled on-chain software. They are provided <strong>"as is" and "as available"</strong>, with all faults, and without warranties of any kind. They are under active development, may behave in ways nobody anticipated, and may change, be suspended, or be discontinued at any time. You acknowledge that you are choosing to use unproven technology, that you understand what that means, and that you are not relying on any statement by us, anywhere, that Agent Wallets are safe, secure, reliable, or fit for any purpose.</p>
+
+ <h2>3. Not a bank, not insured, not an investment</h2>
+ <ul>
+ <li>An Agent Wallet is <strong>not a bank account, deposit account, savings account, escrow, trust, or investment account</strong>. We are not a bank, broker, custodian bank, trustee, fiduciary, or investment adviser to you, and no fiduciary, trust, bailment, or escrow relationship arises from a Deposit.</li>
+ <li>Funds are <strong>not insured</strong> by the FDIC, SIPC, any deposit-guarantee scheme, or any government agency or private insurer, anywhere in the world.</li>
+ <li>Funds earn no interest from us, and nothing on the Service promises a return.</li>
+ <li>Each Agent Wallet is a public on-chain address. The blockchain's record of that address is the only authoritative record of what it holds; balances shown in the Service's interface are informational and may be delayed or wrong.</li>
+ </ul>
+
+ <h2>4. How custody works, and what that exposes you to</h2>
+ <p>Agent Wallets are custodial. Their private keys are generated and held, in encrypted form, by the Service so that agents can sign transactions without asking you. That design exposes Funds to risks that include, without limitation:</p>
+ <ul>
+ <li><strong>Software defects</strong> in the Service, its dependencies, or the programs it interacts with, which can send Funds to the wrong place, in the wrong amount, or at the wrong time.</li>
+ <li><strong>Security incidents</strong>, including intrusion into our systems or a provider's, theft or disclosure of key material, insider misuse, and attacks on the libraries and infrastructure we depend on.</li>
+ <li><strong>Loss of key material</strong>, including through encryption-key rotation errors, data corruption, or the loss of the secrets needed to decrypt a stored key. A wallet whose key cannot be decrypted cannot sign, and its Funds may be permanently inaccessible.</li>
+ <li><strong>Autonomous action</strong> by agents, strategies, snipers, autopilot, and delegated spending, which can trade, pay, or transfer Funds without asking again, including at a loss, while operating exactly as designed.</li>
+ <li><strong>Blockchain and third-party failure</strong>, including network halts, congestion, reorganizations, fee spikes, RPC and indexer outages, DEX, bridge, and launchpad failures, stablecoin de-pegs, token freezes or blacklisting by an issuer, and changes to the rules of any chain or protocol.</li>
+ <li><strong>Market loss</strong>: the value of any asset can fall to zero.</li>
+ <li><strong>Service discontinuation</strong>: the Service, or the Agent Wallet feature, may be shut down, temporarily or permanently, with or without notice.</li>
+ </ul>
+ <p>Guardrails such as spend limits, freezes, allowlists, custody proofs, and risk officers are best-effort software controls. They reduce some risks. They do not eliminate any, and they can fail.</p>
+
+ <h2>5. Deposits are made entirely at the Depositor's own risk</h2>
+ <ul>
+ <li><strong>Every Deposit is voluntary and at the sole risk of the Depositor.</strong> By making a Deposit, by any means, you accept this Agreement, whether or not you have an account, whether or not you clicked anything, and whether or not you read it first.</li>
+ <li><strong>Deposits are irreversible.</strong> We cannot cancel, reverse, or refund a Deposit. A Deposit to the wrong address, on the wrong chain, of an unsupported asset, or in the wrong amount may be permanently lost, and we have no obligation to recover it.</li>
+ <li><strong>Depositing into someone else's agent is a gift to that agent.</strong> A Depositor who funds an agent they do not own gives up all control of those Funds. The Owner and the agent decide what happens to them. The Depositor acquires no ownership, share, claim, return, refund right, or say in how the Funds are used, and has no claim against us for how they are used.</li>
+ <li><strong>Unsupported assets.</strong> Only assets the Service explicitly displays are supported. Anything else sent to an Agent Wallet may be invisible to the Service and unrecoverable.</li>
+ <li><strong>Keep balances small.</strong> Deposit only what you are actively using and can afford to lose entirely without hardship.</li>
+ </ul>
+
+ <h2>6. No guarantee of access, withdrawal, or recovery</h2>
+ <p>We do not guarantee that you will be able to access, withdraw, move, or recover any Funds at any time. Withdrawals and transfers may be delayed, limited, or impossible because of any of the risks in Section 4, because of a freeze or spend limit, because of legal process, or because we suspend an account or agent. We have no obligation to operate recovery tools, to rescue Funds from a wallet that cannot sign, to compensate you for Funds that cannot be reached, or to keep the Service running so that you can withdraw. If we discontinue Agent Wallets, we will make reasonable efforts to give notice and a window to withdraw where we can, but we do not promise either, and our failure to provide them does not make us liable for any loss.</p>
+
+ <h2>7. Your responsibilities</h2>
+ <ul>
+ <li>You are responsible for every setting you choose and every agent, strategy, sniper, autopilot, delegation, and integration you enable, and for everything it does with Funds.</li>
+ <li>You are responsible for securing your account, sessions, API keys, and connected wallets. Actions taken with your credentials are treated as yours.</li>
+ <li>You are responsible for confirming addresses, chains, and amounts before sending anything.</li>
+ <li>You are responsible for your own taxes, record-keeping, and legal compliance, including securities, commodities, anti-money-laundering, sanctions, and exchange-control laws where you live.</li>
+ <li>You will not use an Agent Wallet for any unlawful purpose, to hold proceeds of crime, to evade sanctions, or on behalf of anyone else in a way that would breach the Terms.</li>
+ </ul>
+
+ <h2>8. Eligibility</h2>
+ <p>You may use or deposit into an Agent Wallet only if you are at least 18 years old, of legal age to form a binding contract where you live, not located in or a resident of a jurisdiction subject to comprehensive United States sanctions, not on any restricted-party list, and permitted by the laws that apply to you to do so. By accepting this Agreement or making a Deposit, you represent that each of these is true.</p>
+
+ <h2>9. Assumption of risk and release</h2>
+ <p><strong>You expressly assume all risks of using Agent Wallets and of making Deposits, known and unknown, including every risk described in this Agreement and in the Risk Disclosure.</strong> To the maximum extent permitted by law, you release three.ws, its operator, owners, contributors, affiliates, service providers, and their respective officers, employees, and agents (the "Released Parties") from all claims, demands, and damages of every kind, known and unknown, arising out of or related to any Agent Wallet, Deposit, or Funds, including any loss of Funds. If you are a California resident, you waive California Civil Code Section 1542, which says: "A general release does not extend to claims that the creditor or releasing party does not know or suspect to exist in his or her favor at the time of executing the release and that, if known by him or her, would have materially affected his or her settlement with the debtor or released party." You waive any similar law in any other jurisdiction.</p>
+
+ <h2>10. No liability for loss of funds</h2>
+ <p class="caps">TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE RELEASED PARTIES ARE NOT RESPONSIBLE AND SHALL HAVE NO LIABILITY WHATSOEVER FOR ANY LOSS, THEFT, FREEZING, DEVALUATION, OR INACCESSIBILITY OF ANY FUNDS, OR FOR ANY OTHER DAMAGES ARISING OUT OF OR RELATED TO AGENT WALLETS, DEPOSITS, OR FUNDS, HOWEVER CAUSED, INCLUDING BY SOFTWARE DEFECTS, SECURITY INCIDENTS, LOSS OF KEY MATERIAL, AGENT BEHAVIOR, MARKET MOVEMENTS, THIRD-PARTY OR BLOCKCHAIN FAILURES, OR DISCONTINUATION OF THE SERVICE, AND WHETHER THE CLAIM IS BASED ON CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY, STATUTE, OR ANY OTHER THEORY, EVEN IF WE WERE ADVISED OF THE POSSIBILITY OF THE LOSS.</p>
+ <p>Where applicable law does not allow a liability to be fully excluded, that liability is limited to the smallest amount the law permits, and in any case is subject to the cap in the Limitation of Liability section of the Terms. Nothing in this Agreement excludes liability that cannot be excluded by law.</p>
+
+ <h2>11. Indemnification</h2>
+ <p>You will defend, indemnify, and hold harmless the Released Parties from any claim, loss, liability, penalty, and expense (including reasonable attorneys' fees) arising out of your use of an Agent Wallet, your Deposits, anything an agent you control does with Funds, your breach of this Agreement, or your violation of any law or third-party right.</p>
+
+ <h2>12. Suspension, freezing, and compliance</h2>
+ <p>We may, without liability, suspend an agent or account, restrict or freeze an Agent Wallet's ability to sign, decline or halt a transaction, or disable a feature, where we believe it is necessary to protect the Service or its users, to respond to a suspected security incident or abuse, or to comply with law, legal process, or a governmental request. We may disclose information about Agent Wallets and Funds where the law requires it.</p>
+
+ <h2>13. Electronic signature and records</h2>
+ <p>You agree that checking the acceptance boxes, typing your name, and pressing the sign button constitutes your electronic signature, has the same legal effect as a handwritten signature, and satisfies any requirement that this Agreement be in writing or signed, under the U.S. Electronic Signatures in Global and National Commerce Act and any similar law. We record each signature with the name you typed, the versions of the agreements you signed, a cryptographic fingerprint of the exact agreement text, the time, the feature you were using, your IP address, and your browser's user agent, and we retain that record for as long as your account exists and as long as the law requires afterward. You can review your signature records at <a href="/legal/agreements">/legal/agreements</a>. Declining to sign keeps the rest of the Service available; you simply cannot use real-funds features.</p>
+
+ <h2>14. Disputes</h2>
+ <p>Any dispute arising out of or related to this Agreement, an Agent Wallet, a Deposit, or Funds is subject to the informal-resolution, binding individual arbitration, class action waiver, governing law, and venue provisions of the <a href="/legal/tos">Terms of Service</a>, including the right to opt out of arbitration described there.</p>
+
+ <h2>15. Changes</h2>
+ <p>We may change this Agreement. Each version carries a version number and effective date at the top of this page. When a change is material, the version number increases and you must sign the new version before your next real-funds action. Deposits made after a change takes effect are governed by the version in effect at the time of the Deposit. If you do not want to accept a new version, you do not have to: email <a href="mailto:[email protected]">[email protected]</a> from the email address on your account, and we will make reasonable efforts to return the balance of your Agent Wallets to an address you control, less network fees, subject to Sections 6 and 12. Until then, the version you last accepted continues to govern your existing Funds.</p>
+
+ <h2>16. General</h2>
+ <p>If any provision of this Agreement is held unenforceable, it will be enforced to the maximum extent permissible and the rest of the Agreement remains in effect. Our failure to enforce a provision is not a waiver. Sections 3, 5, 6, and 9 through 14 survive termination of your account, discontinuation of the Service, and the closing of any Agent Wallet.</p>
+
+ <h2>17. Contact</h2>
+ <p>Questions about this Agreement: <a href="mailto:[email protected]">[email protected]</a>.</p>
+
+ <hr />
+ <p class="foot">three.ws · <a href="/legal/tos">Terms of Service</a> · <a href="/legal/risk">Risk Disclosure</a> · <a href="/legal/privacy">Privacy Policy</a> · <a href="/legal/agreements">Your signed agreements</a></p>
+</main>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/i18n.js"></script>
+</body>
+</html>
diff --git a/public/legal/agreements.html b/public/legal/agreements.html
new file mode 100644
index 000000000..35c430a1c
--- /dev/null
+++ b/public/legal/agreements.html
@@ -0,0 +1,268 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot, no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Real-Funds Agreements · three.ws</title>
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/tokens.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <style>
+ * { box-sizing: border-box; }
+ body {
+ font: 16px/1.7 -apple-system, system-ui, 'Segoe UI', sans-serif;
+ background: var(--bg-0);
+ color: var(--ink);
+ margin: 0;
+ }
+ .wrap { max-width: 760px; margin: 0 auto; padding: 48px 24px 80px; }
+ main.wrap:focus { outline: none; }
+ h1 { font-size: 32px; color: var(--ink-bright); margin: 0 0 6px; letter-spacing: -.02em; }
+ .lede { color: var(--ink-dim); font-size: 15px; margin: 0 0 32px; }
+ h2 { font-size: 18px; color: var(--ink-bright); margin: 40px 0 12px; }
+ p, li { color: var(--ink); font-size: 15px; }
+ a { color: var(--ink-bright); }
+ .card {
+ border: 1px solid var(--stroke);
+ background: var(--surface-1);
+ border-radius: 14px;
+ padding: 20px 22px;
+ }
+ .status { display: grid; gap: 14px; min-height: 132px; }
+ .status-head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
+ .pill {
+ display: inline-flex; align-items: center; gap: 6px;
+ font-size: 12px; font-weight: 600; letter-spacing: .02em;
+ padding: 3px 10px; border-radius: 999px;
+ border: 1px solid var(--stroke-strong); color: var(--ink-dim);
+ }
+ .pill[data-tone="ok"] { color: var(--success); border-color: color-mix(in srgb, var(--success) 45%, transparent); background: color-mix(in srgb, var(--success) 10%, transparent); }
+ .pill[data-tone="warn"] { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 45%, transparent); background: color-mix(in srgb, var(--warn) 10%, transparent); }
+ .pill[data-tone="danger"] { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 45%, transparent); background: color-mix(in srgb, var(--danger) 10%, transparent); }
+ .status-title { margin: 0; font-size: 17px; color: var(--ink-bright); font-weight: 600; }
+ .status-copy { margin: 0; color: var(--ink-dim); font-size: 14px; }
+ .actions { display: flex; gap: 10px; flex-wrap: wrap; }
+ .btn {
+ font: inherit; font-size: 14px; font-weight: 600;
+ display: inline-flex; align-items: center; justify-content: center;
+ padding: 9px 16px; border-radius: 10px; cursor: pointer; text-decoration: none;
+ border: 1px solid var(--stroke-strong); background: transparent; color: var(--ink);
+ transition: background .15s, border-color .15s, opacity .15s, transform .1s;
+ }
+ .btn:hover { background: var(--surface-2); border-color: var(--ink-faint); }
+ .btn:active { transform: translateY(1px); }
+ .btn:focus-visible { outline: 2px solid var(--focus-ring-color, var(--accent)); outline-offset: 2px; }
+ .btn-primary { background: var(--ink-bright); color: var(--bg-0); border-color: transparent; }
+ .btn-primary:hover { background: var(--ink-bright); opacity: .88; }
+ .btn[disabled] { opacity: .45; cursor: not-allowed; }
+ .docs { list-style: none; padding: 0; margin: 0; display: grid; gap: 10px; }
+ .docs li {
+ display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;
+ border: 1px solid var(--stroke); border-radius: 12px; padding: 12px 16px; margin: 0;
+ transition: border-color .15s;
+ }
+ .docs li:hover { border-color: var(--stroke-strong); }
+ .docs a { font-weight: 600; text-decoration: none; }
+ .docs a:hover { text-decoration: underline; }
+ .docs a:focus-visible { outline: 2px solid var(--focus-ring-color, var(--accent)); outline-offset: 2px; border-radius: 4px; }
+ .docs .ver { color: var(--ink-faint); font-size: 13px; }
+ .skeleton { background: var(--skeleton-base, var(--surface-2)); border-radius: 6px; animation: pulse 1.4s ease-in-out infinite; }
+ @keyframes pulse { 50% { opacity: .5; } }
+ @media (prefers-reduced-motion: reduce) { .skeleton { animation: none; } }
+ .history { width: 100%; border-collapse: collapse; font-size: 14px; }
+ .history th, .history td { text-align: left; padding: 10px 8px; border-bottom: 1px solid var(--stroke); vertical-align: top; }
+ .history th { color: var(--ink-faint); font-weight: 600; font-size: 12px; letter-spacing: .04em; text-transform: uppercase; }
+ .history td { color: var(--ink); }
+ .history .muted { color: var(--ink-faint); }
+ .table-wrap { overflow-x: auto; }
+ .callout {
+ border: 1px solid color-mix(in srgb, var(--warn) 35%, transparent);
+ background: color-mix(in srgb, var(--warn) 8%, var(--bg-0));
+ border-radius: 10px; padding: 14px 18px; margin: 0 0 28px;
+ }
+ .callout p { color: color-mix(in srgb, var(--warn) 40%, var(--ink)); margin: 0; font-size: 15px; }
+ .fade-in { animation: fade .2s ease-out; }
+ @keyframes fade { from { opacity: 0; transform: translateY(4px); } }
+ @media (prefers-reduced-motion: reduce) { .fade-in { animation: none; } }
+ code { font-family: var(--font-mono, ui-monospace, monospace); font-size: 13px; }
+ .foot { color: var(--ink-faint); font-size: 13px; margin-top: 48px; }
+ </style>
+
+ <meta name="description" content="Sign, and review, the agreements required before any real-funds action on three.ws: the Terms of Service, the Risk Disclosure, and the Agent Wallet Agreement.">
+ <link rel="canonical" href="https://three.ws/legal/agreements">
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:title" content="Real-Funds Agreements · three.ws">
+ <meta property="og:description" content="Sign and review the agreements required before any real-funds action on three.ws.">
+ <meta property="og:url" content="https://three.ws/legal/agreements">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=legal&amp;t=Real-Funds+Agreements&amp;d=Sign+and+review+the+agreements+required+before+any+real-funds+action.&amp;p=%2Flegal%2Fagreements">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:site" content="@trythreews">
+ <meta name="robots" content="index, follow">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Real-Funds Agreements","description":"Sign and review the agreements required before any real-funds action on three.ws.","url":"https://three.ws/legal/agreements","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+</head>
+<body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+<main id="main-content" class="wrap" tabindex="-1">
+ <h1>Real-Funds Agreements</h1>
+ <p class="lede">Before you deposit into an agent wallet, trade, send, withdraw, or pay with real funds on three.ws, you sign three agreements. Signing once covers every real-funds feature until one of the documents changes.</p>
+
+ <div class="callout">
+ <p><strong>three.ws is experimental technology.</strong> Anything held in, sent to, or sent from an agent wallet can be lost completely, nothing is insured, and three.ws is not responsible for any loss, for any reason.</p>
+ </div>
+
+ <section class="card status" id="status" aria-live="polite" aria-busy="true">
+ <div class="skeleton" style="height:22px;width:140px"></div>
+ <div class="skeleton" style="height:20px;width:70%"></div>
+ <div class="skeleton" style="height:38px;width:180px"></div>
+ </section>
+
+ <h2>What you sign</h2>
+ <ul class="docs" id="docs">
+ <li><a href="/legal/tos">Terms of Service</a><span class="ver">Version 3</span></li>
+ <li><a href="/legal/risk">Risk Disclosure</a><span class="ver">Version 2</span></li>
+ <li><a href="/legal/agent-wallet">Agent Wallet Agreement</a><span class="ver">Version 1</span></li>
+ </ul>
+
+ <section id="history-section" hidden>
+ <h2>Your signature history</h2>
+ <div class="table-wrap">
+ <table class="history">
+ <thead><tr><th scope="col">Signed</th><th scope="col">Signature</th><th scope="col">Version</th><th scope="col">From</th></tr></thead>
+ <tbody id="history"></tbody>
+ </table>
+ </div>
+ </section>
+
+ <h2>For developers and API users</h2>
+ <p>The same rule applies to API keys. A real-funds request from an account without a current signature is refused with HTTP 403 and <code>{"error":"risk_ack_required"}</code>, including a <code>sign_url</code> pointing here. Sign in with the account that owns the key and sign once; the next request goes through. See <a href="/docs/risk-acknowledgment">the real-funds agreement docs</a>.</p>
+
+ <p class="foot">Questions: <a href="mailto:[email protected]">[email protected]</a> · <a href="/legal">All policies</a></p>
+</main>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module">
+ import { ensureRiskAck, hasRiskAck, AGREEMENT_DOCUMENTS, RISK_ACK_VERSION, RISK_ACK_ENDPOINT } from '/risk-ack.js';
+
+ const statusEl = document.getElementById('status');
+ const docsEl = document.getElementById('docs');
+ const historySection = document.getElementById('history-section');
+ const historyBody = document.getElementById('history');
+
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+ const fmtDate = (iso) => {
+ try {
+ return new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
+ } catch {
+ return iso;
+ }
+ };
+
+ docsEl.innerHTML = AGREEMENT_DOCUMENTS.map(
+ (d) => `<li><a href="${esc(d.path)}">${esc(d.title)}</a><span class="ver">Version ${d.version}</span></li>`,
+ ).join('');
+
+ function renderStatus({ pill, tone, title, copy, actions }) {
+ statusEl.setAttribute('aria-busy', 'false');
+ statusEl.innerHTML = `
+ <div class="status-head fade-in"><span class="pill" data-tone="${tone}">${esc(pill)}</span></div>
+ <p class="status-title fade-in">${esc(title)}</p>
+ <p class="status-copy fade-in">${copy}</p>
+ <div class="actions fade-in">${actions}</div>`;
+ }
+
+ function renderHistory(rows) {
+ if (!Array.isArray(rows) || rows.length === 0) {
+ historySection.hidden = true;
+ return;
+ }
+ historyBody.innerHTML = rows
+ .map(
+ (r) => `<tr>
+ <td>${esc(fmtDate(r.signedAt))}</td>
+ <td><em>${esc(r.signatureName)}</em></td>
+ <td>${r.version}${r.current ? '' : ' <span class="muted">(superseded)</span>'}</td>
+ <td class="muted">${esc(r.path || r.context || 'three.ws')}</td>
+ </tr>`,
+ )
+ .join('');
+ historySection.hidden = false;
+ }
+
+ async function load() {
+ statusEl.setAttribute('aria-busy', 'true');
+ let status;
+ try {
+ const res = await fetch(`${RISK_ACK_ENDPOINT}?history=1`, { credentials: 'same-origin', headers: { accept: 'application/json' } });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ status = await res.json();
+ } catch {
+ renderStatus({
+ pill: 'Unavailable',
+ tone: 'danger',
+ title: 'We could not load your agreement status.',
+ copy: 'Check your connection and try again. Your existing signatures are unaffected.',
+ actions: '<button class="btn btn-primary" type="button" data-retry>Try again</button>',
+ });
+ statusEl.querySelector('[data-retry]').addEventListener('click', load);
+ return;
+ }
+
+ renderHistory(status.history);
+ const next = encodeURIComponent('/legal/agreements');
+
+ if (!status.authenticated && hasRiskAck()) {
+ renderStatus({
+ pill: 'Signed in this browser',
+ tone: 'ok',
+ title: 'You signed the real-funds agreements in this browser.',
+ copy: 'That covers this browser only. Sign in and your account will ask you to sign once more, so the signature is attached to your account for the app and the API.',
+ actions: `<a class="btn btn-primary" href="/login?next=${next}">Sign in</a>`,
+ });
+ } else if (!status.authenticated) {
+ renderStatus({
+ pill: 'Not signed in',
+ tone: 'warn',
+ title: 'Sign in to attach your signature to your account.',
+ copy: 'A signature made while signed in covers your account everywhere, including the API. You can also sign here without an account, for example before funding someone else’s agent; that signature covers this browser.',
+ actions: `<a class="btn btn-primary" href="/login?next=${next}">Sign in</a><button class="btn" type="button" data-sign>Sign without an account</button>`,
+ });
+ } else if (status.signed) {
+ renderStatus({
+ pill: 'Signed',
+ tone: 'ok',
+ title: `Signed by ${status.signatureName || 'you'} on ${fmtDate(status.signedAt)}.`,
+ copy: `Your account has signed version ${RISK_ACK_VERSION} of the real-funds agreements. Real-funds features are unlocked. If any document changes materially, you will be asked to sign again.`,
+ actions: '<a class="btn" href="/dashboard">Go to dashboard</a>',
+ });
+ } else {
+ renderStatus({
+ pill: 'Signature required',
+ tone: 'warn',
+ title: 'Your account has not signed the current agreements.',
+ copy: 'Until you sign, three.ws refuses real-funds actions from your account, in the app and through the API. Read each document, then sign once.',
+ actions: '<button class="btn btn-primary" type="button" data-sign>Review and sign</button>',
+ });
+ }
+
+ const signBtn = statusEl.querySelector('[data-sign]');
+ if (signBtn) {
+ signBtn.addEventListener('click', async () => {
+ signBtn.disabled = true;
+ const signed = await ensureRiskAck({ context: 'agreements-page', force: true });
+ signBtn.disabled = false;
+ if (signed) load();
+ });
+ }
+ }
+
+ load();
+ </script>
+ <script type="module" src="/i18n.js"></script>
+</body>
+</html>
diff --git a/public/legal/index.html b/public/legal/index.html
index d535f1bf8..30ae27c9a 100644
--- a/public/legal/index.html
+++ b/public/legal/index.html
@@ -99,11 +99,18 @@
<h2 data-i18n="legal_index.policies">Policies</h2>
<ul class="docs">
- <li data-i18n-html="legal_index.terms_of_service_the_agreement_between_you">
+ <li>
+ <a class="doc" href="/legal/agreements">
+ <span class="doc-title">Real-Funds Agreements</span>
+ <span class="doc-desc">Sign before depositing, trading, sending, or paying with real funds, and review every signature on your account.</span>
+ <span class="doc-date">Required before any real-funds action</span>
+ </a>
+ </li>
+ <li>
<a class="doc" href="/legal/tos">
<span class="doc-title">Terms of Service</span>
<span class="doc-desc">The agreement between you and three.ws: your account, acceptable use, payments and on-chain activity, liability, and the DMCA takedown process.</span>
- <span class="doc-date">Effective July 16, 2026</span>
+ <span class="doc-date">Effective September 17, 2026</span>
</a>
</li>
<li data-i18n-html="legal_index.privacy_policy_what_data_we_collect_why">
@@ -120,11 +127,18 @@
<span class="doc-date">Effective June 21, 2026</span>
</a>
</li>
- <li data-i18n-html="legal_index.risk_disclosure_read_before_using_any_real">
+ <li>
<a class="doc" href="/legal/risk">
<span class="doc-title">Risk Disclosure</span>
<span class="doc-desc">Read before using any real-funds feature. Experimental software, autonomous agents acting on your behalf, and total-loss risk.</span>
- <span class="doc-date">Effective July 3, 2026</span>
+ <span class="doc-date">Effective September 17, 2026</span>
+ </a>
+ </li>
+ <li>
+ <a class="doc" href="/legal/agent-wallet">
+ <span class="doc-title">Agent Wallet Agreement</span>
+ <span class="doc-desc">Governs every agent wallet and every deposit into one: experimental custodial software, no insurance, no guaranteed recovery, no liability for lost funds.</span>
+ <span class="doc-date">Effective September 17, 2026</span>
</a>
</li>
<li data-i18n-html="legal_index.end_user_license_agreement_license_terms_for">
diff --git a/public/legal/risk.html b/public/legal/risk.html
index d88fae28a..b617f679a 100644
--- a/public/legal/risk.html
+++ b/public/legal/risk.html
@@ -63,13 +63,13 @@
<script src="/nav.js"></script>
<main id="main-content" class="wrap" tabindex="-1">
<h1 data-i18n="legal_risk.risk_disclosure">Risk Disclosure</h1>
- <p class="meta" data-i18n-html="legal_risk.effective_july_3_2026_version_1_terms">Effective: July 3, 2026 &nbsp;·&nbsp; Version 1 &nbsp;·&nbsp; <a href="/legal/tos">Terms of Service</a> &nbsp;·&nbsp; <a href="/legal/privacy">Privacy Policy</a></p>
+ <p class="meta">Effective: September 17, 2026 &nbsp;·&nbsp; Version 2 &nbsp;·&nbsp; <a href="/legal/tos">Terms of Service</a> &nbsp;·&nbsp; <a href="/legal/agent-wallet">Agent Wallet Agreement</a> &nbsp;·&nbsp; <a href="/legal/privacy">Privacy Policy</a> &nbsp;·&nbsp; <a href="/legal/agreements">Sign or review your agreements</a></p>
<div class="callout">
- <p data-i18n-html="legal_risk.plain_summary_three_ws_is_experimental_softw"><strong>Plain summary:</strong> three.ws is experimental software — an attempt at innovation, not a financial product. Do not use real funds unless you understand and accept that you can lose all of them, and that three.ws is not responsible for any loss.</p>
+ <p><strong>Plain summary:</strong> three.ws is experimental software, an attempt at innovation, not a financial product. Do not use real funds, and do not deposit into any agent wallet, unless you understand and accept that you can lose all of them and that three.ws is not responsible for any loss, for any reason.</p>
</div>
- <p data-i18n="legal_risk.this_risk_disclosure_disclosure_applies_to_e">This Risk Disclosure ("Disclosure") applies to every feature of three.ws ("Service") that can move real money or real digital assets — including but not limited to agent wallets, trading, token sniping, automated strategies, autopilot, token launches, swaps, transfers, withdrawals, x402 payments, and fiat onramps ("Real-Funds Features"). Before first using a Real-Funds Feature you are asked to acknowledge this Disclosure. By accepting it, or by using any Real-Funds Feature, you agree to everything below.</p>
+ <p>This Risk Disclosure ("Disclosure") applies to every feature of three.ws ("Service") that can move real money or real digital assets, including but not limited to agent wallets and deposits into them, trading, token sniping, automated strategies, autopilot, token launches, swaps, transfers, withdrawals, x402 payments, and fiat onramps ("Real-Funds Features"). Before first using a Real-Funds Feature you must sign this Disclosure together with the <a href="/legal/tos">Terms of Service</a> and the <a href="/legal/agent-wallet">Agent Wallet Agreement</a>. By signing, or by using any Real-Funds Feature or making any deposit into an agent wallet, you agree to everything below.</p>
<p data-i18n-html="legal_risk.real_funds_features_are_available_only_to">Real-Funds Features are available only to users who are at least 18 years old and of legal age in their jurisdiction, as set out in the Eligibility section of the <a href="/legal/tos">Terms of Service</a>. This Disclosure is part of, and incorporated into, those Terms.</p>
@@ -98,7 +98,7 @@
</ul>
<h2 data-i18n="legal_risk.5_custody_and_security">5. Custody and security</h2>
- <p data-i18n="legal_risk.agent_wallets_on_the_service_are_custodial">Agent wallets on the Service are custodial: keys are held server-side so agents can sign autonomously. Custodial funds are exposed to platform risk, including compromise, operational error, and loss of key material. Self-custody wallets (e.g. Phantom) you connect remain entirely your responsibility — the Service never holds those keys, and cannot recover them, reverse your signatures, or restore funds lost to phishing or device compromise. Keep balances on the Service limited to what you are actively using.</p>
+ <p>Agent wallets on the Service are custodial: keys are held server-side so agents can sign autonomously. Custodial funds are exposed to platform risk, including compromise, operational error, loss of key material, and discontinuation of the Service. An agent wallet is not a bank account, and funds in it are not insured by the FDIC, SIPC, or any government or private insurer. Deposits are irreversible, may be made by anyone, and are made entirely at the depositor's own risk; we do not guarantee that deposited funds can be withdrawn or recovered. The <a href="/legal/agent-wallet">Agent Wallet Agreement</a> sets out these terms in full. Self-custody wallets (e.g. Phantom) you connect remain entirely your responsibility: the Service never holds those keys, and cannot recover them, reverse your signatures, or restore funds lost to phishing or device compromise. Keep balances on the Service limited to what you are actively using.</p>
<h2 data-i18n="legal_risk.6_assumption_of_risk_no_liability">6. Assumption of risk; no liability</h2>
<p data-i18n-html="legal_risk.you_use_real_funds_features_entirely_at"><strong>You use Real-Funds Features entirely at your own risk.</strong> To the maximum extent permitted by law, three.ws, its operators, contributors, and affiliates accept no responsibility and shall have no liability for any loss of funds, tokens, or value of any kind, however caused, including losses arising from software defects, agent behavior, market movements, third-party failures, security incidents, or your own configuration, whether based in contract, tort, or any other theory. This section supplements, and does not limit, the Limitation of Liability in the <a href="/legal/tos">Terms of Service</a>.</p>
@@ -110,7 +110,7 @@
<p data-i18n="legal_risk.you_are_solely_responsible_for_ensuring_that">You are solely responsible for ensuring that your use of Real-Funds Features is lawful where you live, including compliance with securities, tax, and exchange-control rules. The Service is not offered where such use would be unlawful. Real-Funds Features are not intended for persons under 18.</p>
<h2 data-i18n="legal_risk.9_how_acknowledgment_works">9. How acknowledgment works</h2>
- <p data-i18n="legal_risk.the_service_asks_you_to_accept_this">The Service asks you to accept this Disclosure once per browser before your first real-funds action. Your acceptance is versioned and recorded, including the date and the feature you were using. If this Disclosure changes materially, the version number increases and you will be asked to accept it again before your next real-funds action. Declining keeps you on the platform — you simply cannot execute real-funds actions until you accept.</p>
+ <p>Before your first real-funds action, and before an agent wallet's deposit address is shown to you, the Service asks you to sign this Disclosure, the Terms of Service, and the Agent Wallet Agreement: you confirm each one separately, confirm your eligibility, and type your name as your electronic signature. When you are signed in, the signature is recorded against your account and the Service's servers refuse real-funds actions from that account, including through the API, until a current signature is on file. Each signature record holds the name you typed, the document versions, a cryptographic fingerprint of the text you signed, the time, the feature you were using, your IP address, and your user agent. If any of these documents changes materially, its version increases and you must sign again before your next real-funds action. Declining keeps you on the platform; you simply cannot execute real-funds actions until you sign. You can review your signatures at <a href="/legal/agreements">/legal/agreements</a>.</p>
<h2 data-i18n="legal_risk.10_contact">10. Contact</h2>
<p data-i18n-html="legal_risk.questions_about_this_disclosure_legal_three">Questions about this Disclosure: <a href="mailto:[email protected]">[email protected]</a>.</p>
diff --git a/public/legal/tos.html b/public/legal/tos.html
index efecef772..f959bacab 100644
--- a/public/legal/tos.html
+++ b/public/legal/tos.html
@@ -57,12 +57,12 @@
<script src="/nav.js"></script>
<main id="main-content" class="wrap" tabindex="-1">
<h1 data-i18n="legal_tos.terms_of_service">Terms of Service</h1>
- <p class="meta" data-i18n-html="legal_tos.effective_july_16_2026_version_2_privacy">Effective: July 16, 2026 &nbsp;·&nbsp; Version 2 &nbsp;·&nbsp; <a href="/legal/privacy">Privacy Policy</a> &nbsp;·&nbsp; <a href="/legal/risk">Risk Disclosure</a></p>
+ <p class="meta">Effective: September 17, 2026 &nbsp;·&nbsp; Version 3 &nbsp;·&nbsp; <a href="/legal/privacy">Privacy Policy</a> &nbsp;·&nbsp; <a href="/legal/risk">Risk Disclosure</a> &nbsp;·&nbsp; <a href="/legal/agent-wallet">Agent Wallet Agreement</a> &nbsp;·&nbsp; <a href="/legal/agreements">Sign or review your agreements</a></p>
<p data-i18n="legal_tos.these_terms_of_service_terms_govern_your">These Terms of Service ("Terms") govern your access to and use of three.ws and its subdomains, APIs, SDKs, MCP connectors, and applications (together, the "Service"), operated by the operator of three.ws ("three.ws", "we", "us", "our"). Please read them carefully.</p>
<h2 data-i18n="legal_tos.1_acceptance_of_these_terms">1. Acceptance of These Terms</h2>
- <p data-i18n="legal_tos.you_accept_these_terms_by_any_of">You accept these Terms by any of the following: checking the agreement box when creating an account; signing a wallet sign-in message that references these Terms; clicking a button next to a notice that using the Service constitutes agreement; or continuing to use the Service after notice of updated Terms. We record the Terms version you accepted and when, and retain that record for the life of your account and as long as required for legal purposes.</p>
+ <p>You accept these Terms by any of the following: checking the agreement box when creating an account; signing a wallet sign-in message that references these Terms; signing the real-funds agreements described in Section 8; clicking a button next to a notice that using the Service constitutes agreement; or continuing to use the Service after notice of updated Terms. We record the Terms version you accepted and when, and retain that record for the life of your account and as long as required for legal purposes. You agree that checking an acceptance box, typing your name, or pressing a sign or accept button is your electronic signature and has the same legal effect as a handwritten one.</p>
<p data-i18n="legal_tos.if_you_do_not_agree_to_these">If you do not agree to these Terms, do not use the Service.</p>
<h2 data-i18n="legal_tos.2_eligibility">2. Eligibility</h2>
@@ -98,13 +98,14 @@
<p data-i18n-html="legal_tos.plan_access_is_tied_to_the_wallet">Plan access is tied to the wallet address or account that made the payment. If you lose access to that wallet, we cannot recover your subscription; contact <a href="mailto:[email protected]">[email protected]</a> with on-chain proof of ownership.</p>
<p data-i18n="legal_tos.we_reserve_the_right_to_change_plan">We reserve the right to change plan pricing with 30 days' notice. Existing paid subscriptions will not be affected until renewal.</p>
- <h2 data-i18n="legal_tos.8_real_funds_features_and_risk_disclosure">8. Real-Funds Features and Risk Disclosure</h2>
- <p data-i18n-html="legal_tos.the_risk_disclosure_is_part_of_these">The <a href="/legal/risk">Risk Disclosure</a> is part of these Terms and is incorporated by reference. Before first using a Real-Funds Feature you must acknowledge it. In summary, and without limiting it:</p>
+ <h2>8. Real-Funds Features, Agent Wallets, and Risk Disclosure</h2>
+ <p>The <a href="/legal/risk">Risk Disclosure</a> and the <a href="/legal/agent-wallet">Agent Wallet Agreement</a> are part of these Terms and are incorporated by reference. Before first using a Real-Funds Feature, and before depositing into any agent wallet, you must sign both, together with these Terms. The Service's servers refuse Real-Funds Features from an account that has not signed the current versions. Any deposit into an agent wallet, by anyone and by any means, is governed by the Agent Wallet Agreement whether or not the depositor signed it. In summary, and without limiting either document:</p>
<ul>
<li data-i18n-html="legal_tos.total_loss_is_possible_digital_assets_are"><strong>Total loss is possible.</strong> Digital assets are volatile and speculative; any amount you commit can be lost entirely, quickly, and permanently. Blockchain transactions are irreversible.</li>
<li data-i18n-html="legal_tos.nothing_on_the_service_is_financial_investme"><strong>Nothing on the Service is financial, investment, legal, accounting, or tax advice</strong>, or a recommendation to buy, sell, or hold any asset. We are not your broker, adviser, or fiduciary, and no fiduciary duty is created by your use of the Service.</li>
<li data-i18n-html="legal_tos.autonomous_features_act_on_your_instructions"><strong>Autonomous features act on your instructions.</strong> Features you enable (autopilot, strategies, agent delegation) can transact on your behalf without asking again. You are responsible for what you enable and for monitoring it.</li>
<li><strong>Platform fees are shown before you sign.</strong> Some Real-Funds Features carry a three.ws fee on top of network and third-party fees, for example 1% of the value of each trade three.ws builds or executes for you or your agents, including the dev buy when you launch a coin. The fee is shown in the interface before you approve, travels in the same transaction you sign, and is non-refundable once that transaction confirms.</li>
+ <li><strong>Agent wallets are experimental and uninsured.</strong> An agent wallet is custodial, experimental software, not a bank account. Funds in it are not insured, deposits are irreversible and at the depositor's own risk, and we do not guarantee that funds can be withdrawn or recovered. <strong>We are not responsible for any loss of funds held in, sent to, or sent from an agent wallet, for any reason</strong>, to the maximum extent permitted by law.</li>
<li data-i18n-html="legal_tos.taxes_are_yours_you_are_solely_responsible"><strong>Taxes are yours.</strong> You are solely responsible for determining and paying any taxes that apply to your transactions.</li>
</ul>
@@ -147,7 +148,7 @@
<p data-i18n="legal_tos.we_may_update_these_terms_each_version">We may update these Terms. Each version carries a version number and effective date at the top. We will notify you of material changes by posting a notice on the Service or by email, and your acceptance of the new version is recorded the next time you sign in or create an account. Your continued use after the effective date constitutes acceptance of the updated Terms.</p>
<h2 data-i18n="legal_tos.19_miscellaneous">19. Miscellaneous</h2>
- <p data-i18n-html="legal_tos.these_terms_together_with_the_privacy_policy">These Terms, together with the <a href="/legal/privacy">Privacy Policy</a>, the <a href="/legal/risk">Risk Disclosure</a>, and the <a href="/legal/content-policy">Content Policy</a>, are the entire agreement between you and three.ws regarding the Service. If any provision is found unenforceable, the remainder stays in effect. Our failure to enforce a provision is not a waiver. You may not assign these Terms without our consent; we may assign them in connection with a merger, acquisition, or sale of assets, with notice to you. We are not liable for delay or failure caused by events beyond our reasonable control.</p>
+ <p>These Terms, together with the <a href="/legal/privacy">Privacy Policy</a>, the <a href="/legal/risk">Risk Disclosure</a>, the <a href="/legal/agent-wallet">Agent Wallet Agreement</a>, and the <a href="/legal/content-policy">Content Policy</a>, are the entire agreement between you and three.ws regarding the Service. If any provision is found unenforceable, the remainder stays in effect. Our failure to enforce a provision is not a waiver. You may not assign these Terms without our consent; we may assign them in connection with a merger, acquisition, or sale of assets, with notice to you. We are not liable for delay or failure caused by events beyond our reasonable control.</p>
<h2 data-i18n="legal_tos.20_contact">20. Contact</h2>
<p data-i18n-html="legal_tos.questions_email_legal_three_ws">Questions? Email <a href="mailto:[email protected]">[email protected]</a>.</p>
diff --git a/public/risk-ack.js b/public/risk-ack.js
index b28e2ba26..87740848d 100644
Binary files a/public/risk-ack.js and b/public/risk-ack.js differ
diff --git a/public/x402.js b/public/x402.js
index 799494094..c5a7febaf 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -39,12 +39,12 @@
const VERSION = '0.2.0';
-// Real-funds gate: before the first payment, the user must accept the three.ws
-// Risk Disclosure (three.ws/legal/risk). Loaded lazily and failure-tolerant on
-// purpose — this modal is a drop-in embed on merchant sites, and a payment
-// must never brick because the gate module 404'd or was blocked. If risk-ack.js
-// can't load, degrade to a native confirm() with the same core wording,
-// remembered for the page session.
+// Real-funds gate: before the first payment, the user must sign the three.ws
+// real-funds agreements (three.ws/legal/agreements). Loaded lazily and
+// failure-tolerant on purpose: this modal is a drop-in embed on merchant sites,
+// and a payment must never brick because the gate module 404'd or was blocked.
+// If risk-ack.js can't load, degrade to a native confirm() with the same core
+// wording, remembered for the page session.
let _riskAckSessionOk = false;
async function ensureRiskAckSafe(context) {
@@ -58,11 +58,12 @@ async function ensureRiskAckSafe(context) {
if (_riskAckSessionOk) return true;
try {
_riskAckSessionOk = globalThis.confirm?.(
- 'Real funds — risk acknowledgment\n\n' +
- 'three.ws is experimental software. Losses can be total, fast, and irreversible; ' +
- 'nothing here is financial advice; and three.ws is not responsible for any losses. ' +
- 'Full text: three.ws/legal/risk\n\n' +
- 'Press OK to accept that you use real funds entirely at your own risk, or Cancel to stop.',
+ 'Real funds: sign the agreements\n\n' +
+ 'three.ws is experimental technology. By pressing OK you agree to the Terms of Service (three.ws/legal/tos), ' +
+ 'the Risk Disclosure (three.ws/legal/risk), and the Agent Wallet Agreement (three.ws/legal/agent-wallet). ' +
+ 'You confirm you are 18 or older and accept that funds can be lost completely for any reason, nothing is ' +
+ 'insured, and three.ws is not responsible for any loss.\n\n' +
+ 'Press OK to accept, or Cancel to stop.',
) === true;
} catch {
_riskAckSessionOk = false;
diff --git a/src/agent-wallet-hub/tabs/deposit.js b/src/agent-wallet-hub/tabs/deposit.js
index fe76555bc..0ca3f2eda 100644
--- a/src/agent-wallet-hub/tabs/deposit.js
+++ b/src/agent-wallet-hub/tabs/deposit.js
@@ -31,6 +31,7 @@ import { fetchAgentSolanaWallet, fetchAgentSolanaActivity } from '../../agent-so
import { renderQRToSVG } from '../../erc8004/qr.js';
import { buildSolanaPayUri } from '../../shared/solana-pay.js';
import { formatSol, timeAgo, explorerAddressUrl, explorerTxUrl } from '../util.js';
+import { ensureRiskAck, hasRiskAckVerified } from '../../shared/risk-ack.js';
// Balance is server-cached for 60s, so a faster poll just re-reads the cache.
// 15s keeps the "waiting for your deposit" loop feeling live without hammering RPC.
@@ -70,6 +71,13 @@ a.awh-dep-qr:focus-visible { outline: var(--focus-ring-width,2px) solid var(--fo
.awh-dep-amount-hint.is-err { color: var(--warn,#fbbf24); }
.awh-dep-how { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); line-height: 1.55; margin: 0; }
+.awh-dep-terms { margin-top: 8px; }
+.awh-dep-terms a, .awh-dep-gate a { color: var(--ink-bright,#fff); }
+.awh-dep-gate { display: flex; flex-direction: column; gap: 10px; margin-top: 12px; }
+.awh-dep-gate-h { margin: 0; font-weight: 600; color: var(--ink-bright,#fff); font-size: var(--text-md,.8125rem); }
+.awh-dep-gate-p { margin: 0; font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); line-height: 1.55; }
+.awh-dep-gate-docs { margin: 0; padding-left: 18px; font-size: var(--text-sm,.764rem); line-height: 1.7; }
+.awh-dep-gate-docs a:focus-visible { outline: 2px solid var(--focus-ring-color, currentColor); outline-offset: 2px; border-radius: 3px; }
.awh-dep-status { display: flex; align-items: center; gap: 10px; }
.awh-dep-dot { width: 9px; height: 9px; border-radius: 50%; flex: none; }
@@ -140,6 +148,11 @@ registerWalletTab({
// stale address remains fundable during an API error or old deployment.
depositsEnabled: null,
depositsDisabledReason: null,
+ // The deposit address stays hidden on mainnet until the visitor has
+ // signed the real-funds agreements (Agent Wallet Agreement included).
+ // null = not yet checked, so nothing fundable renders while unknown.
+ agreementSigned: null,
+ signing: false,
amount: '', // user-entered SOL amount for the QR/deep-link
amountError: false,
// Live confirmation tracking.
@@ -311,6 +324,11 @@ registerWalletTab({
return;
}
+ if (net !== 'devnet' && state.agreementSigned !== true) {
+ renderAgreementGate();
+ return;
+ }
+
const uri = solanaUri();
panel.innerHTML = `
<div class="awh-card">
@@ -356,6 +374,8 @@ registerWalletTab({
<strong>How to fund:</strong> scan the QR with your phone's wallet (Phantom, Solflare, Backpack…),
tap “Open in a wallet app” on mobile, or copy the address and send SOL from any wallet or exchange.
</p>
+ ${net === 'devnet' ? '' : `<p class="awh-dep-how awh-dep-terms">Deposits are irreversible, uninsured, and made entirely at your own risk under the
+ <a href="/legal/agent-wallet" target="_blank" rel="noopener">Agent Wallet Agreement</a>. three.ws is not responsible for any loss of funds sent to this wallet.</p>`}
</div>
<div class="awh-card" data-host="status" role="status" aria-live="polite">${statusBlock()}</div>
@@ -389,6 +409,44 @@ registerWalletTab({
amountInput?.addEventListener('input', onAmountInput);
}
+ function renderAgreementGate() {
+ const checking = state.agreementSigned === null;
+ panel.innerHTML = `
+ <div class="awh-card">
+ <div class="awh-dep-who">
+ ${avatar ? `<img class="awh-dep-who-av" src="${escapeHtml(avatar)}" alt="" loading="lazy" data-fallback="remove" />` : ''}
+ <div class="awh-dep-who-txt">Before you fund <strong>${escapeHtml(agentName)}</strong></div>
+ </div>
+ <div class="awh-dep-gate">
+ <p class="awh-dep-gate-h">Sign the real-funds agreements to see the deposit address.</p>
+ <p class="awh-dep-gate-p">Agent wallets are experimental, custodial software, not bank accounts. Anything sent here
+ can be lost completely (bugs, hacks, lost keys, agent decisions, the service shutting down), nothing is insured,
+ withdrawal is never guaranteed, and three.ws is not responsible for any loss. If you fund an agent you do not own,
+ those funds belong to that agent.</p>
+ <ul class="awh-dep-gate-docs">
+ <li><a href="/legal/agent-wallet" target="_blank" rel="noopener">Agent Wallet Agreement</a></li>
+ <li><a href="/legal/risk" target="_blank" rel="noopener">Risk Disclosure</a></li>
+ <li><a href="/legal/tos" target="_blank" rel="noopener">Terms of Service</a></li>
+ </ul>
+ <div class="awh-dep-actions">
+ <button class="awh-btn awh-btn--primary" type="button" data-act="sign" ${checking || state.signing ? 'disabled aria-busy="true"' : ''}>
+ ${checking ? 'Checking your agreements…' : state.signing ? 'Waiting for signature…' : 'Review and sign'}
+ </button>
+ </div>
+ </div>
+ </div>`;
+ panel.querySelector('[data-act="sign"]')?.addEventListener('click', async () => {
+ if (state.signing) return;
+ state.signing = true;
+ renderAgreementGate();
+ const signed = await ensureRiskAck({ context: 'deposit' });
+ state.signing = false;
+ if (destroyed) return;
+ state.agreementSigned = signed === true;
+ render();
+ });
+ }
+
function onAmountInput(e) {
const raw = e.target.value.trim();
state.amount = raw;
@@ -447,7 +505,11 @@ registerWalletTab({
}
async function loadInitial() {
- const res = await readBalance();
+ const [res, signed] = await Promise.all([
+ readBalance(),
+ state.agreementSigned === true ? true : hasRiskAckVerified(),
+ ]);
+ state.agreementSigned = signed === true;
state.depositsEnabled = res.depositsEnabled === true;
state.depositsDisabledReason = res.depositsDisabledReason || null;
if (res.ok) {
diff --git a/src/master-wallet.js b/src/master-wallet.js
index 2897fb411..df3510b38 100644
--- a/src/master-wallet.js
+++ b/src/master-wallet.js
@@ -36,6 +36,7 @@ import {
fundAgent,
} from './wallet-api.js';
import { openDepositSheet } from './wallet-deposit.js';
+import { ensureRiskAck } from './shared/risk-ack.js';
const root = document.getElementById('wlt-root');
const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
@@ -704,6 +705,7 @@ async function onReviewFund(form) {
async function onConfirm() {
const p = state.pending;
if (!p) return;
+ if (!(await ensureRiskAck({ context: p.kind === 'fund' ? 'fund-agent' : 'master-send' }))) return;
state.busy = true;
render();
const res =
@@ -745,6 +747,9 @@ async function onConfirm() {
async function onDeposit() {
const w = state.wallet;
if (!w) return;
+ // The deposit sheet reveals a custodial address; funding it is governed by
+ // the Agent Wallet Agreement, so the address is shown only after signing.
+ if (!(await ensureRiskAck({ context: 'deposit' }))) return;
let latest = null;
const arrival = await openDepositSheet({
solanaAddress: w.solana_address,
diff --git a/src/shared/agent-tip-modal.js b/src/shared/agent-tip-modal.js
index 1881c58a6..c5c8c9a19 100644
--- a/src/shared/agent-tip-modal.js
+++ b/src/shared/agent-tip-modal.js
@@ -17,6 +17,7 @@
import { tipAgent, TipError, TIP_TOKENS } from './agent-tip.js';
import { getWalletStatus } from './agent-wallet-chip.js';
+import { ensureRiskAck } from './risk-ack.js';
const STYLE_ID = 'tws-tip-modal-styles';
@@ -268,6 +269,9 @@ export function openTipModal(agent, opts = {}) {
async function send() {
if (state.sending || !(Number(state.amount) > 0)) return;
+ // A tip is a deposit into an agent wallet: governed by the Agent Wallet
+ // Agreement, so it waits for a signature like every other real-funds action.
+ if (network !== 'devnet' && !(await ensureRiskAck({ context: 'tip' }))) return;
state.error = null;
state.sending = 'connecting';
render();
diff --git a/src/shared/risk-ack.js b/src/shared/risk-ack.js
index 6325814b7..a61c1f83c 100644
--- a/src/shared/risk-ack.js
+++ b/src/shared/risk-ack.js
@@ -39,14 +39,19 @@ function _mod() {
return import(/* @vite-ignore */ `${origin}/risk-ack.js`);
}
-// Same core wording as RISK_ACK_CONFIRM_TEXT in public/risk-ack.js — inlined
-// because this path only runs when that module failed to load.
+// Same core wording as RISK_ACK_CONFIRM_TEXT in public/risk-ack.js, inlined
+// because this path only runs when that module failed to load. It records
+// nothing server-side (the module that records is the one that failed), so a
+// signed-in account is still refused by the server until it signs through the
+// real dialog; the degraded confirm only keeps anonymous flows usable.
const DEGRADED_CONFIRM_TEXT =
- 'Real funds — risk acknowledgment\n\n' +
- 'three.ws is experimental software. Losses can be total, fast, and irreversible; ' +
- 'autonomous features can trade and pay on your behalf without asking again; nothing here is financial advice; ' +
- 'and three.ws is not responsible for any losses. Full text: three.ws/legal/risk\n\n' +
- 'Press OK to accept that you use real funds entirely at your own risk, or Cancel to stop.';
+ 'Real funds: sign the agreements\n\n' +
+ 'three.ws is experimental technology. By pressing OK you agree to the Terms of Service (three.ws/legal/tos), ' +
+ 'the Risk Disclosure (three.ws/legal/risk), and the Agent Wallet Agreement (three.ws/legal/agent-wallet). ' +
+ 'You confirm you are 18 or older and that real-funds use is lawful where you live. You accept that anything ' +
+ 'you deposit, trade, or send can be lost completely for any reason, nothing is insured, and three.ws is not ' +
+ 'responsible for any loss.\n\n' +
+ 'Press OK to accept, or Cancel to stop.';
let _degradedSessionAck = false;
@@ -61,10 +66,10 @@ function _degradedConfirm() {
}
/**
- * Ensure the user has accepted the current Risk Disclosure — shows the
- * acknowledgment dialog if not. Resolves true when accepted, false when
- * declined; the caller must abort the money action on false. Never rejects.
- * @param {{context?: string}} [opts]
+ * Ensure the user has signed the current real-funds agreements, showing the
+ * signing dialog if not. Resolves true when signed, false when declined; the
+ * caller must abort the money action on false. Never rejects.
+ * @param {{context?: string, force?: boolean}} [opts]
* @returns {Promise<boolean>}
*/
export async function ensureRiskAck(opts) {
@@ -83,7 +88,7 @@ export async function ensureRiskAck(opts) {
}
}
-/** @returns {Promise<boolean>} whether the current disclosure version is already accepted. Never rejects. */
+/** @returns {Promise<boolean>} whether this browser holds a current signature. Never rejects. */
export async function hasRiskAck() {
try {
const m = await _mod();
@@ -92,3 +97,37 @@ export async function hasRiskAck() {
return _degradedSessionAck;
}
}
+
+/**
+ * Whether the visitor has signed, confirming the account's server record when
+ * signed in. Never prompts, never rejects.
+ * @returns {Promise<boolean>}
+ */
+export async function hasRiskAckVerified() {
+ try {
+ const m = await _mod();
+ return await m.hasRiskAckVerified();
+ } catch {
+ return _degradedSessionAck;
+ }
+}
+
+/**
+ * fetch() that opens the signing dialog when the server answers 403
+ * risk_ack_required, then retries once after the user signs. When the gate
+ * module cannot load, the original response is returned untouched so the
+ * caller's normal error handling shows the server's message.
+ * @param {RequestInfo|URL} input
+ * @param {RequestInit} [init]
+ * @param {{context?: string}} [opts]
+ * @returns {Promise<Response>}
+ */
+export async function fetchWithRiskAck(input, init, opts) {
+ let m;
+ try {
+ m = await _mod();
+ } catch {
+ return fetch(input, init);
+ }
+ return m.fetchWithRiskAck(input, init, opts);
+}
diff --git a/tests/api/legal-risk-ack.test.js b/tests/api/legal-risk-ack.test.js
index 2a3edba39..ae788c182 100644
--- a/tests/api/legal-risk-ack.test.js
+++ b/tests/api/legal-risk-ack.test.js
@@ -1,7 +1,8 @@
-// Risk Disclosure acceptance endpoint (POST /api/legal/risk-ack). The client
-// gate that calls it (public/risk-ack.js) is covered in tests/risk-ack.test.js;
-// this file covers the server side: what it accepts, what it refuses, and
-// whether it tells the caller the truth about the durable record.
+// Real-funds agreement endpoint (GET/POST /api/legal/risk-ack). The client
+// dialog that calls it (public/risk-ack.js) is covered in tests/risk-ack.test.js;
+// this file covers the server side: what counts as a complete signature, what
+// it refuses, whether it tells the caller the truth about the durable record,
+// and the status read the client cross-checks against.
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { Readable } from 'node:stream';
@@ -40,7 +41,8 @@ vi.mock('../../api/_lib/auth.js', () => ({
getSessionUser: vi.fn(async () => sessionState.user),
}));
-const { RISK_ACK_VERSION } = await import('../../public/risk-ack.js');
+const { RISK_ACK_VERSION, buildSignaturePayload } = await import('../../public/risk-ack.js');
+const { resetRealFundsAgreementCache } = await import('../../api/_lib/real-funds-agreement.js');
const { default: handler } = await import('../../api/legal/risk-ack.js');
// ── Helpers ───────────────────────────────────────────────────────────────────
@@ -83,129 +85,166 @@ async function invoke(body, opts) {
return { res, status: res.statusCode, body: json };
}
+const signatureRows = () => sqlState.calls.filter((c) => /insert into legal_signatures/.test(c.query));
const auditRows = () => sqlState.calls.filter((c) => /insert into audit_log/.test(c.query));
+const validSignature = (over = {}) => ({
+ ...buildSignaturePayload({ name: 'Ada Lovelace', context: 'deposit', path: '/agents/abc' }),
+ ...over,
+});
beforeEach(() => {
sqlState.queue = [];
sqlState.calls = [];
rlState.success = true;
sessionState.user = null;
+ resetRealFundsAgreementCache();
});
-// ── POST /api/legal/risk-ack ──────────────────────────────────────────────────
-
describe('POST /api/legal/risk-ack', () => {
- it('records an anonymous acceptance with its context and page', async () => {
- const { status, body } = await invoke({ version: RISK_ACK_VERSION, context: 'trade', path: '/create' });
+ it('records an anonymous signature with every document version, a text fingerprint, and the typed name', async () => {
+ const { status, body } = await invoke(validSignature());
expect(status).toBe(200);
- expect(body).toEqual({ ok: true, recorded: true });
- const rows = auditRows();
+ expect(body).toEqual({ ok: true, recorded: true, version: RISK_ACK_VERSION });
+ const rows = signatureRows();
expect(rows).toHaveLength(1);
- expect(rows[0].values[0]).toBeNull(); // user_id: anonymous
- expect(rows[0].values).toContain('risk-ack-accept');
- expect(rows[0].values).toContainEqual({ version: RISK_ACK_VERSION, context: 'trade', path: '/create' });
- expect(rows[0].values).toContain('203.0.113.7');
+ const v = rows[0].values;
+ expect(v[0]).toBeNull(); // user_id: anonymous
+ expect(v[1]).toBe(RISK_ACK_VERSION);
+ const docs = JSON.parse(v[2]);
+ for (const key of ['tos', 'risk', 'agentWallet']) {
+ expect(docs[key].version).toBeGreaterThanOrEqual(1);
+ expect(docs[key].sha256).toMatch(/^[0-9a-f]{64}$/);
+ }
+ expect(v[3]).toBe('Ada Lovelace');
+ expect(JSON.parse(v[4])).toEqual({ eligible: true, noLiability: true });
+ expect(v).toContain('deposit');
+ expect(v).toContain('203.0.113.7');
+ expect(auditRows()).toHaveLength(1);
+ expect(auditRows()[0].values).toContain('risk-ack-accept');
});
- it('attributes the acceptance to the signed-in user', async () => {
+ it('attributes the signature to the signed-in account', async () => {
sessionState.user = { id: 'user-42' };
- const { status, body } = await invoke({ version: RISK_ACK_VERSION, context: 'x402-pay' });
+ const { status } = await invoke(validSignature());
expect(status).toBe(200);
- expect(body.recorded).toBe(true);
- expect(auditRows()[0].values[0]).toBe('user-42');
+ expect(signatureRows()[0].values[0]).toBe('user-42');
});
- it('records anonymously when the session lookup fails', async () => {
+ it('signs anonymously when the session lookup fails', async () => {
const { getSessionUser } = await import('../../api/_lib/auth.js');
getSessionUser.mockRejectedValueOnce(new Error('expired token'));
- const { status, body } = await invoke({ version: RISK_ACK_VERSION });
+ const { status } = await invoke(validSignature());
expect(status).toBe(200);
- expect(body.recorded).toBe(true);
- expect(auditRows()[0].values[0]).toBeNull();
+ expect(signatureRows()[0].values[0]).toBeNull();
});
- it('refuses a disclosure version that does not exist', async () => {
- const { status, body } = await invoke({ version: RISK_ACK_VERSION + 1 });
+ it.each([
+ ['a stale version', { version: RISK_ACK_VERSION - 1 }, 'invalid_version'],
+ ['a future version', { version: RISK_ACK_VERSION + 1 }, 'invalid_version'],
+ ['a missing document', { documents: { tos: 3, risk: 2 } }, 'document_not_accepted'],
+ ['an outdated document version', { documents: { tos: 2, risk: 2, agentWallet: 1 } }, 'document_not_accepted'],
+ ['an unchecked attestation', { attestations: { eligible: true } }, 'attestation_missing'],
+ ['a truthy-but-not-true attestation', { attestations: { eligible: 'yes', noLiability: true } }, 'attestation_missing'],
+ ['no typed name', { signatureName: '' }, 'invalid_signature'],
+ ['a name with no letters', { signatureName: '---' }, 'invalid_signature'],
+ ])('refuses %s and records nothing', async (_label, over, code) => {
+ const { status, body } = await invoke(validSignature(over));
expect(status).toBe(400);
- expect(body.error).toBe('invalid_version');
+ expect(body.error).toBe(code);
+ expect(signatureRows()).toHaveLength(0);
expect(auditRows()).toHaveLength(0);
});
- it.each([
- [{}],
- [{ version: 0 }],
- [{ version: 1.5 }],
- [{ version: 'one' }],
- [{ version: null }],
- ])('refuses a malformed version %#', async (body) => {
- const { status } = await invoke(body);
+ it('refuses a non-object body', async () => {
+ const { status, body } = await invoke([1, 2]);
expect(status).toBe(400);
- expect(auditRows()).toHaveLength(0);
+ expect(body.error).toBe('invalid_body');
});
- // A body the endpoint could not read used to be reported as a bad `version`,
- // pointing the caller at a field that was never the problem.
- it('names the size limit rather than the version when the body is too large', async () => {
- const { status, body } = await invoke({ version: RISK_ACK_VERSION, pad: 'a'.repeat(11_000) });
+ it('names the size limit when the body is too large', async () => {
+ const { status, body } = await invoke(validSignature({ pad: 'a'.repeat(11_000) }));
expect(status).toBe(413);
expect(body.error).toBe('payload_too_large');
- expect(auditRows()).toHaveLength(0);
+ expect(signatureRows()).toHaveLength(0);
});
- it('names the content-type rather than the version when the body is not JSON', async () => {
- const { status, body } = await invoke(null, {
- contentType: 'application/x-www-form-urlencoded',
- raw: 'version=1',
- });
+ it('names the content-type when the body is not JSON', async () => {
+ const { status, body } = await invoke(null, { contentType: 'application/x-www-form-urlencoded', raw: 'version=2' });
expect(status).toBe(415);
expect(body.error).toBe('unsupported_media_type');
- expect(auditRows()).toHaveLength(0);
});
it('refuses an unparseable body', async () => {
const { status, body } = await invoke(null, { raw: '{oops' });
expect(status).toBe(400);
expect(body.error).toBe('bad_request');
- expect(auditRows()).toHaveLength(0);
});
it('drops a malformed context or path rather than storing it', async () => {
- const { status } = await invoke({
- version: RISK_ACK_VERSION,
- context: 'NOT A SLUG!',
- path: 'missing-leading-slash',
- });
+ const { status } = await invoke(validSignature({ context: 'NOT A SLUG!', path: 'no-leading-slash' }));
expect(status).toBe(200);
- expect(auditRows()[0].values).toContainEqual({ version: RISK_ACK_VERSION, context: null, path: null });
+ const v = signatureRows()[0].values;
+ expect(v[5]).toBeNull();
+ expect(v[6]).toBeNull();
});
- it('reports recorded:false when the durable write fails', async () => {
- // A deterministic SQL error, not a transient connection blip: db-retry
- // surfaces it on the first attempt instead of retrying.
- sqlState.queue = [new Error('relation "audit_log" does not exist')];
- const { status, body } = await invoke({ version: RISK_ACK_VERSION, context: 'trade' });
- expect(status).toBe(200);
- expect(body).toEqual({ ok: true, recorded: false });
- });
-
- it('rejects a non-POST method', async () => {
- const { status, body } = await invoke(null, { method: 'GET' });
- expect(status).toBe(405);
- expect(body.error).toBe('method_not_allowed');
+ it('answers 503 when the signature could not be stored, so the dialog asks again', async () => {
+ sqlState.queue = [new Error('relation "legal_signatures" does not exist')];
+ const { status, body } = await invoke(validSignature());
+ expect(status).toBe(503);
+ expect(body.error).toBe('signature_not_recorded');
+ expect(auditRows()).toHaveLength(0);
});
it('rate limits', async () => {
rlState.success = false;
- const { status } = await invoke({ version: RISK_ACK_VERSION });
+ const { status } = await invoke(validSignature());
expect(status).toBe(429);
- expect(auditRows()).toHaveLength(0);
+ expect(signatureRows()).toHaveLength(0);
});
- it('allows any origin, so the x402 embed on a merchant site can record', async () => {
- const { res, status } = await invoke({ version: RISK_ACK_VERSION }, { origin: 'https://merchant.example' });
+ it('allows any origin without credentials, so merchant-site embeds sign anonymously', async () => {
+ const { res, status } = await invoke(validSignature(), { origin: 'https://merchant.example' });
expect(status).toBe(200);
expect(res.headers['access-control-allow-origin']).toBe('*');
- // No credentials on a wildcard origin: cross-site acceptances stay anonymous.
expect(res.headers['access-control-allow-credentials']).toBeUndefined();
});
});
+
+describe('GET /api/legal/risk-ack', () => {
+ it('reports an anonymous visitor as unauthenticated and unsigned without touching the database', async () => {
+ const { status, body } = await invoke(null, { method: 'GET' });
+ expect(status).toBe(200);
+ expect(body).toMatchObject({ authenticated: false, signed: false, version: RISK_ACK_VERSION });
+ expect(body.documents.map((d) => d.key)).toEqual(['tos', 'risk', 'agentWallet']);
+ expect(sqlState.calls).toHaveLength(0);
+ });
+
+ it('reports a signed account with when and by whom', async () => {
+ sessionState.user = { id: 'user-42' };
+ sqlState.queue = [[{ created_at: '2026-09-17T18:00:00.000Z', signature_name: 'Ada Lovelace', context: 'deposit' }]];
+ const { status, body } = await invoke(null, { method: 'GET' });
+ expect(status).toBe(200);
+ expect(body).toMatchObject({ authenticated: true, signed: true, signedAt: '2026-09-17T18:00:00.000Z', signatureName: 'Ada Lovelace' });
+ expect(sqlState.calls[0].values).toContain(RISK_ACK_VERSION);
+ });
+
+ it('reports an unsigned account', async () => {
+ sessionState.user = { id: 'user-42' };
+ sqlState.queue = [[]];
+ const { body } = await invoke(null, { method: 'GET' });
+ expect(body).toMatchObject({ authenticated: true, signed: false, signedAt: null });
+ });
+
+ it('answers 503 rather than a false "unsigned" when the lookup fails', async () => {
+ sessionState.user = { id: 'user-42' };
+ sqlState.queue = [new Error('relation "legal_signatures" does not exist')];
+ const { status } = await invoke(null, { method: 'GET' });
+ expect(status).toBe(503);
+ });
+
+ it('rejects other methods', async () => {
+ const { status } = await invoke(null, { method: 'DELETE' });
+ expect(status).toBe(405);
+ });
+});
diff --git a/tests/real-funds-agreement.test.js b/tests/real-funds-agreement.test.js
new file mode 100644
index 000000000..fcdd55167
--- /dev/null
+++ b/tests/real-funds-agreement.test.js
@@ -0,0 +1,152 @@
+// requireRealFundsAgreement(): the server-side refusal every custodial money
+// endpoint calls. These tests pin what it lets through, what it refuses, how it
+// fails when the database does, and that the served agreement pages carry the
+// versions the signature records.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';
+
+const sqlState = { queue: [], calls: [] };
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ if (sqlState.queue.length === 0) return [];
+ const next = sqlState.queue.shift();
+ if (next instanceof Error) throw next;
+ return next;
+ }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const {
+ requireRealFundsAgreement,
+ resetRealFundsAgreementCache,
+ fingerprintDocumentHtml,
+ validateSignatureBody,
+ agreementRequirement,
+} = await import('../api/_lib/real-funds-agreement.js');
+const { AGREEMENT_DOCUMENTS, RISK_ACK_VERSION, buildSignaturePayload } = await import('../public/risk-ack.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+const req = { headers: {}, url: '/api/agents/abc/solana/withdraw' };
+
+beforeEach(() => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+ resetRealFundsAgreementCache();
+});
+
+describe('requireRealFundsAgreement', () => {
+ it('lets a signed account through', async () => {
+ sqlState.queue = [[{ created_at: new Date(), signature_name: 'Ada', context: 'trade' }]];
+ const res = makeRes();
+ await expect(requireRealFundsAgreement(req, res, { userId: 'u1', network: 'mainnet', context: 'withdraw' })).resolves.toBe(true);
+ expect(res.writableEnded).toBe(false);
+ expect(sqlState.calls[0].values).toEqual(['u1', RISK_ACK_VERSION]);
+ });
+
+ it('refuses an unsigned account with 403 risk_ack_required and a sign_url', async () => {
+ sqlState.queue = [[]];
+ const res = makeRes();
+ await expect(requireRealFundsAgreement(req, res, { userId: 'u1', context: 'withdraw' })).resolves.toBe(false);
+ expect(res.statusCode).toBe(403);
+ const body = JSON.parse(res.body);
+ expect(body.error).toBe('risk_ack_required');
+ expect(body.context).toBe('withdraw');
+ expect(body.version).toBe(RISK_ACK_VERSION);
+ expect(body.sign_url).toMatch(/\/legal\/agreements$/);
+ expect(body.documents.map((d) => d.key)).toEqual(['tos', 'risk', 'agentWallet']);
+ expect(body.error_description).toMatch(/Nothing was sent/);
+ });
+
+ it('exempts devnet without a lookup', async () => {
+ const res = makeRes();
+ await expect(requireRealFundsAgreement(req, res, { userId: 'u1', network: 'devnet' })).resolves.toBe(true);
+ expect(sqlState.calls).toHaveLength(0);
+ });
+
+ it('refuses with 401 when no user resolved', async () => {
+ const res = makeRes();
+ await expect(requireRealFundsAgreement(req, res, { userId: null })).resolves.toBe(false);
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('fails CLOSED with 503 when the lookup fails', async () => {
+ sqlState.queue = [new Error('relation "legal_signatures" does not exist')];
+ const res = makeRes();
+ await expect(requireRealFundsAgreement(req, res, { userId: 'u1' })).resolves.toBe(false);
+ expect(res.statusCode).toBe(503);
+ expect(JSON.parse(res.body).error).toBe('agreement_check_unavailable');
+ });
+
+ it('caches a signed result but never an unsigned one', async () => {
+ sqlState.queue = [[]];
+ await requireRealFundsAgreement(req, makeRes(), { userId: 'u2' });
+ sqlState.queue = [[{ created_at: new Date(), signature_name: 'Ada', context: null }]];
+ await expect(requireRealFundsAgreement(req, makeRes(), { userId: 'u2' })).resolves.toBe(true);
+ const lookups = sqlState.calls.length;
+ await expect(requireRealFundsAgreement(req, makeRes(), { userId: 'u2' })).resolves.toBe(true);
+ expect(sqlState.calls.length).toBe(lookups);
+ });
+});
+
+describe('validateSignatureBody', () => {
+ it('accepts exactly what the dialog sends', () => {
+ const parsed = validateSignatureBody(buildSignaturePayload({ name: 'Ada Lovelace', context: 'trade', path: '/x' }));
+ expect(parsed.ok).toBe(true);
+ expect(parsed.value.signatureName).toBe('Ada Lovelace');
+ });
+});
+
+describe('the served agreements', () => {
+ const files = { tos: 'public/legal/tos.html', risk: 'public/legal/risk.html', agentWallet: 'public/legal/agent-wallet.html' };
+
+ it.each(AGREEMENT_DOCUMENTS.map((d) => [d.key, d]))('%s shows the version the signature records', (key, doc) => {
+ const html = readFileSync(files[key], 'utf8');
+ expect(html).toMatch(new RegExp(`Version ${doc.version}\\b`));
+ });
+
+ it('the Agent Wallet Agreement states deposits are uninsured and three.ws is not responsible', () => {
+ const html = readFileSync(files.agentWallet, 'utf8');
+ expect(html).toMatch(/not insured/i);
+ expect(html).toMatch(/not responsible for any loss of funds/i);
+ expect(html).toMatch(/Deposit/);
+ });
+
+ it('fingerprints ignore whitespace but change with wording', () => {
+ const a = fingerprintDocumentHtml('<main>\n <p>Funds can be lost.</p>\n</main>');
+ const b = fingerprintDocumentHtml('<main><p>Funds can be lost.</p></main>');
+ const c = fingerprintDocumentHtml('<main><p>Funds cannot be lost.</p></main>');
+ expect(a).toBe(b);
+ expect(a).not.toBe(c);
+ });
+
+ it('agreementRequirement links every document on the app origin', () => {
+ const r = agreementRequirement();
+ expect(r.documents).toHaveLength(AGREEMENT_DOCUMENTS.length);
+ for (const d of r.documents) expect(d.url).toMatch(/^https?:\/\/.+\/legal\//);
+ });
+});
diff --git a/tests/risk-ack.test.js b/tests/risk-ack.test.js
index c2f31e3d5..50c7709f9 100644
--- a/tests/risk-ack.test.js
+++ b/tests/risk-ack.test.js
@@ -1,18 +1,15 @@
-// Risk acknowledgment gate — pure logic + storage behavior of public/risk-ack.js.
-// The DOM dialog itself is exercised in the browser; these tests pin down the
-// parts that decide whether a user gets prompted: record parsing, version
-// currency, and localStorage persistence semantics.
-
-import { describe, it, expect, beforeEach, afterEach } from 'vitest';
-import {
- parseAckRecord,
- isAckCurrent,
- hasRiskAck,
- ensureRiskAck,
- fallbackConfirmAck,
- RISK_ACK_VERSION,
- RISK_ACK_STORAGE_KEY,
-} from '../public/risk-ack.js';
+// Real-funds agreement gate: pure logic + storage and network behavior of
+// public/risk-ack.js. The DOM dialog itself is exercised in the browser; these
+// tests pin down what decides whether a person gets prompted and what a
+// signature sends: record parsing, version currency, signature validation, the
+// server-status cross-check, the degraded signing path, and fetchWithRiskAck.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+async function load() {
+ vi.resetModules();
+ return import('../public/risk-ack.js');
+}
function fakeStorage(initial = {}) {
const map = new Map(Object.entries(initial));
@@ -24,150 +21,199 @@ function fakeStorage(initial = {}) {
};
}
-const validRecord = () =>
- JSON.stringify({ version: RISK_ACK_VERSION, acceptedAt: '2026-07-03T12:00:00.000Z', context: 'trade' });
-
-describe('parseAckRecord', () => {
- it('parses a valid record', () => {
- const rec = parseAckRecord(validRecord());
- expect(rec).toEqual({ version: RISK_ACK_VERSION, acceptedAt: '2026-07-03T12:00:00.000Z', context: 'trade' });
- });
-
- it('keeps records without a context', () => {
- const rec = parseAckRecord(JSON.stringify({ version: 1, acceptedAt: '2026-07-03T12:00:00.000Z' }));
- expect(rec).toEqual({ version: 1, acceptedAt: '2026-07-03T12:00:00.000Z' });
- });
-
- it.each([
- [null],
- [undefined],
- [''],
- ['not json'],
- ['42'],
- ['"a string"'],
- [JSON.stringify({ acceptedAt: '2026-07-03T12:00:00.000Z' })], // no version
- [JSON.stringify({ version: 0, acceptedAt: '2026-07-03T12:00:00.000Z' })], // version < 1
- [JSON.stringify({ version: 1.5, acceptedAt: '2026-07-03T12:00:00.000Z' })], // non-integer
- [JSON.stringify({ version: '1', acceptedAt: 'garbage' })], // unparseable date
- [JSON.stringify({ version: 1 })], // no acceptedAt
- ])('rejects invalid input %#', (raw) => {
- expect(parseAckRecord(raw)).toBeNull();
- });
+function jsonResponse(status, body) {
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
+}
- it('coerces a numeric-string version', () => {
- const rec = parseAckRecord(JSON.stringify({ version: '2', acceptedAt: '2026-07-03T12:00:00.000Z' }));
- expect(rec?.version).toBe(2);
- });
+const saved = {};
+beforeEach(() => {
+ for (const k of ['localStorage', 'fetch', 'confirm', 'prompt', 'alert', 'document']) saved[k] = globalThis[k];
+ delete globalThis.document;
+});
+afterEach(() => {
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete globalThis[k];
+ else globalThis[k] = v;
+ }
});
-describe('isAckCurrent', () => {
- it('is false for null', () => {
- expect(isAckCurrent(null)).toBe(false);
+describe('pure helpers', () => {
+ it('parseAckRecord parses a valid record and rejects garbage', async () => {
+ const { parseAckRecord } = await load();
+ expect(parseAckRecord(JSON.stringify({ version: 2, acceptedAt: '2026-09-17T12:00:00.000Z', context: 'trade' }))).toEqual({
+ version: 2,
+ acceptedAt: '2026-09-17T12:00:00.000Z',
+ context: 'trade',
+ });
+ for (const raw of [null, '', 'not json', '42', JSON.stringify({ version: 0, acceptedAt: '2026-01-01' }), JSON.stringify({ version: 1.5, acceptedAt: '2026-01-01' }), JSON.stringify({ version: 2 })]) {
+ expect(parseAckRecord(raw)).toBeNull();
+ }
});
- it('is true when the record matches the current version', () => {
+ it('isAckCurrent: a version-1 acknowledgment no longer counts after the bump to the signature bundle', async () => {
+ const { isAckCurrent, RISK_ACK_VERSION } = await load();
+ expect(RISK_ACK_VERSION).toBeGreaterThanOrEqual(2);
+ expect(isAckCurrent({ version: 1 })).toBe(false);
expect(isAckCurrent({ version: RISK_ACK_VERSION })).toBe(true);
+ expect(isAckCurrent(null)).toBe(false);
});
- it('is true when the record is newer than required', () => {
- expect(isAckCurrent({ version: RISK_ACK_VERSION + 1 })).toBe(true);
+ it('normalizeSignatureName accepts real names and refuses non-signatures', async () => {
+ const { normalizeSignatureName, SIGNATURE_NAME_MAX } = await load();
+ expect(normalizeSignatureName(' Ada Lovelace ')).toBe('Ada Lovelace');
+ expect(normalizeSignatureName('李小龙')).toBe('李小龙');
+ expect(normalizeSignatureName('Zoë O’Brien')).toBe('Zoë O’Brien');
+ expect(normalizeSignatureName('A')).toBeNull();
+ expect(normalizeSignatureName('12345')).toBeNull();
+ expect(normalizeSignatureName(' ')).toBeNull();
+ expect(normalizeSignatureName('x'.repeat(SIGNATURE_NAME_MAX + 1))).toBeNull();
+ expect(normalizeSignatureName(42)).toBeNull();
});
- it('is false for a stale record — a disclosure version bump forces re-acknowledgment', () => {
- expect(isAckCurrent({ version: 1 }, 2)).toBe(false);
+ it('buildSignaturePayload covers every document and attestation at the current versions', async () => {
+ const { buildSignaturePayload, AGREEMENT_DOCUMENTS, AGREEMENT_ATTESTATIONS, RISK_ACK_VERSION } = await load();
+ const p = buildSignaturePayload({ name: 'Ada Lovelace', context: 'deposit', path: '/agents/x' });
+ expect(p.version).toBe(RISK_ACK_VERSION);
+ expect(Object.keys(p.documents).sort()).toEqual(AGREEMENT_DOCUMENTS.map((d) => d.key).sort());
+ for (const d of AGREEMENT_DOCUMENTS) expect(p.documents[d.key]).toBe(d.version);
+ for (const a of AGREEMENT_ATTESTATIONS) expect(p.attestations[a.key]).toBe(true);
+ expect(p).toMatchObject({ signatureName: 'Ada Lovelace', context: 'deposit', path: '/agents/x' });
});
-});
-describe('hasRiskAck / ensureRiskAck against storage', () => {
- let originalStorage;
+ it('the documents are exactly the Terms, the Risk Disclosure, and the Agent Wallet Agreement', async () => {
+ const { AGREEMENT_DOCUMENTS } = await load();
+ expect(AGREEMENT_DOCUMENTS.map((d) => d.path)).toEqual(['/legal/tos', '/legal/risk', '/legal/agent-wallet']);
+ });
- beforeEach(() => {
- originalStorage = globalThis.localStorage;
+ it('isRiskAckRequiredError recognizes only the server refusal', async () => {
+ const { isRiskAckRequiredError } = await load();
+ expect(isRiskAckRequiredError({ error: 'risk_ack_required' })).toBe(true);
+ expect(isRiskAckRequiredError({ error: 'forbidden' })).toBe(false);
+ expect(isRiskAckRequiredError(null)).toBe(false);
});
+});
- afterEach(() => {
- if (originalStorage === undefined) delete globalThis.localStorage;
- else globalThis.localStorage = originalStorage;
+describe('hasRiskAck / ensureRiskAck', () => {
+ it('a current local signature with no session passes without prompting', async () => {
+ const m = await load();
+ globalThis.localStorage = fakeStorage({
+ [m.RISK_ACK_STORAGE_KEY]: JSON.stringify({ version: m.RISK_ACK_VERSION, acceptedAt: '2026-09-17T00:00:00.000Z' }),
+ });
+ globalThis.fetch = vi.fn(async () => jsonResponse(200, { authenticated: false, signed: false, version: m.RISK_ACK_VERSION }));
+ await expect(m.ensureRiskAck({ context: 'trade' })).resolves.toBe(true);
});
- it('hasRiskAck is true when a current acceptance is stored', () => {
- globalThis.localStorage = fakeStorage({ [RISK_ACK_STORAGE_KEY]: validRecord() });
- expect(hasRiskAck()).toBe(true);
+ it('a local signature does not stand in for a signed-in account the server says is unsigned', async () => {
+ const m = await load();
+ const storage = fakeStorage({
+ [m.RISK_ACK_STORAGE_KEY]: JSON.stringify({ version: m.RISK_ACK_VERSION, acceptedAt: '2026-09-17T00:00:00.000Z' }),
+ });
+ globalThis.localStorage = storage;
+ globalThis.fetch = vi.fn(async () => jsonResponse(200, { authenticated: true, signed: false, version: m.RISK_ACK_VERSION }));
+ // No DOM in Node: the gate must fail CLOSED and drop the stale local record.
+ await expect(m.ensureRiskAck({ context: 'trade' })).resolves.toBe(false);
+ expect(storage.getItem(m.RISK_ACK_STORAGE_KEY)).toBeNull();
});
- it('hasRiskAck is false for a stale-version acceptance', () => {
+ it('an unreachable status endpoint falls back to the local record (the server still enforces)', async () => {
+ const m = await load();
globalThis.localStorage = fakeStorage({
- [RISK_ACK_STORAGE_KEY]: JSON.stringify({ version: RISK_ACK_VERSION - 1, acceptedAt: '2026-01-01T00:00:00.000Z' }),
+ [m.RISK_ACK_STORAGE_KEY]: JSON.stringify({ version: m.RISK_ACK_VERSION, acceptedAt: '2026-09-17T00:00:00.000Z' }),
+ });
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error('offline');
});
- // version - 1 can be 0 (invalid) or a genuinely stale version — both must gate.
- expect(hasRiskAck()).toBe(false);
+ await expect(m.hasRiskAckVerified()).resolves.toBe(true);
});
- it('hasRiskAck is false with corrupted storage contents', () => {
- globalThis.localStorage = fakeStorage({ [RISK_ACK_STORAGE_KEY]: '{broken' });
- expect(hasRiskAck()).toBe(false);
+ it('no signature and no DOM resolves false', async () => {
+ const m = await load();
+ globalThis.localStorage = fakeStorage();
+ await expect(m.ensureRiskAck({ context: 'trade' })).resolves.toBe(false);
+ await expect(m.hasRiskAckVerified()).resolves.toBe(false);
});
- it('hasRiskAck survives a throwing localStorage', () => {
+ it('hasRiskAck survives a throwing localStorage', async () => {
+ const m = await load();
globalThis.localStorage = {
- getItem() { throw new Error('denied'); },
+ getItem() {
+ throw new Error('denied');
+ },
};
- expect(hasRiskAck()).toBe(false);
- });
-
- it('ensureRiskAck resolves true immediately when already accepted', async () => {
- globalThis.localStorage = fakeStorage({ [RISK_ACK_STORAGE_KEY]: validRecord() });
- await expect(ensureRiskAck({ context: 'trade' })).resolves.toBe(true);
- });
-
- it('ensureRiskAck resolves false when unaccepted and no DOM is available', async () => {
- globalThis.localStorage = fakeStorage();
- // Node test env has no document — the gate must fail CLOSED (no ack, no money action).
- await expect(ensureRiskAck({ context: 'trade' })).resolves.toBe(false);
+ expect(m.hasRiskAck()).toBe(false);
});
});
-describe('fallbackConfirmAck — the degraded path when the dialog cannot render', () => {
- let originalStorage;
- let originalConfirm;
-
- beforeEach(() => {
- originalStorage = globalThis.localStorage;
- originalConfirm = globalThis.confirm;
- });
-
- afterEach(() => {
- if (originalStorage === undefined) delete globalThis.localStorage;
- else globalThis.localStorage = originalStorage;
- if (originalConfirm === undefined) delete globalThis.confirm;
- else globalThis.confirm = originalConfirm;
- });
-
- it('returns false when confirm() is unavailable — degraded gate still fails closed', () => {
- delete globalThis.confirm;
+describe('fallbackConfirmAck: signing when the dialog cannot render', () => {
+ it('records a full signature and persists it only after the server stored it', async () => {
+ const m = await load();
globalThis.localStorage = fakeStorage();
- expect(fallbackConfirmAck({ context: 'trade' })).toBe(false);
+ globalThis.confirm = () => true;
+ globalThis.prompt = () => ' Ada Lovelace ';
+ const calls = [];
+ globalThis.fetch = vi.fn(async (url, init) => {
+ calls.push({ url: String(url), init });
+ return jsonResponse(200, { ok: true, recorded: true, version: m.RISK_ACK_VERSION });
+ });
+ await expect(m.fallbackConfirmAck({ context: 'swap' })).resolves.toBe(true);
+ expect(calls).toHaveLength(1);
+ expect(calls[0].init.method).toBe('POST');
+ const body = JSON.parse(calls[0].init.body);
+ expect(body).toMatchObject({ version: m.RISK_ACK_VERSION, signatureName: 'Ada Lovelace', context: 'swap' });
+ const rec = m.parseAckRecord(globalThis.localStorage.getItem(m.RISK_ACK_STORAGE_KEY));
+ expect(m.isAckCurrent(rec)).toBe(true);
});
- it('accepting via confirm() persists a current, versioned record', () => {
+ it('an unrecorded signature is not treated as signed', async () => {
+ const m = await load();
globalThis.localStorage = fakeStorage();
globalThis.confirm = () => true;
- expect(fallbackConfirmAck({ context: 'swap' })).toBe(true);
- const rec = parseAckRecord(globalThis.localStorage.getItem(RISK_ACK_STORAGE_KEY));
- expect(isAckCurrent(rec)).toBe(true);
- expect(rec.context).toBe('swap');
+ globalThis.prompt = () => 'Ada Lovelace';
+ globalThis.alert = vi.fn();
+ globalThis.fetch = vi.fn(async () => jsonResponse(503, { error: 'signature_not_recorded', error_description: 'db down' }));
+ await expect(m.fallbackConfirmAck({ context: 'trade' })).resolves.toBe(false);
+ expect(globalThis.localStorage.getItem(m.RISK_ACK_STORAGE_KEY)).toBeNull();
+ expect(globalThis.alert).toHaveBeenCalled();
});
- it('cancelling confirm() returns false and stores nothing', () => {
+ it('cancelling, an empty name, or a missing confirm() all fail closed and send nothing', async () => {
+ const m = await load();
globalThis.localStorage = fakeStorage();
+ globalThis.fetch = vi.fn();
globalThis.confirm = () => false;
- expect(fallbackConfirmAck({ context: 'trade' })).toBe(false);
- expect(globalThis.localStorage.getItem(RISK_ACK_STORAGE_KEY)).toBeNull();
+ await expect(m.fallbackConfirmAck()).resolves.toBe(false);
+ globalThis.confirm = () => true;
+ globalThis.prompt = () => '';
+ await expect(m.fallbackConfirmAck()).resolves.toBe(false);
+ delete globalThis.confirm;
+ await expect(m.fallbackConfirmAck()).resolves.toBe(false);
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ });
+
+ it('a throwing confirm() cannot break the caller', async () => {
+ const m = await load();
+ globalThis.confirm = () => {
+ throw new Error('blocked');
+ };
+ await expect(m.fallbackConfirmAck()).resolves.toBe(false);
+ });
+});
+
+describe('fetchWithRiskAck', () => {
+ it('passes through anything that is not a risk_ack_required refusal', async () => {
+ const m = await load();
+ globalThis.fetch = vi.fn(async () => jsonResponse(403, { error: 'forbidden' }));
+ const res = await m.fetchWithRiskAck('/api/x', { method: 'POST' });
+ expect(res.status).toBe(403);
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
});
- it('a throwing confirm() cannot break the caller', () => {
+ it('returns the refusal untouched when the person does not sign', async () => {
+ const m = await load();
globalThis.localStorage = fakeStorage();
- globalThis.confirm = () => { throw new Error('blocked'); };
- expect(fallbackConfirmAck({ context: 'trade' })).toBe(false);
+ globalThis.fetch = vi.fn(async () => jsonResponse(403, { error: 'risk_ack_required' }));
+ const res = await m.fetchWithRiskAck('/api/x', { method: 'POST' });
+ expect(res.status).toBe(403);
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
});
});
diff --git a/vercel.json b/vercel.json
index f03c545c9..c443097b0 100644
--- a/vercel.json
+++ b/vercel.json
@@ -5618,6 +5618,14 @@
"src": "/legal/risk/?",
"dest": "/legal/risk.html"
},
+ {
+ "src": "/legal/agent-wallet/?",
+ "dest": "/legal/agent-wallet.html"
+ },
+ {
+ "src": "/legal/agreements/?",
+ "dest": "/legal/agreements.html"
+ },
{
"src": "/legal/nvidia-ngc-eula/?",
"dest": "/legal/nvidia-ngc-eula.html"