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: add x402 api-key-health, feed-health, rate-limit-probe, spend-session, telegram-health, wallet-connect endpoints and offer-receipt lib

nirholas5e3bc31fb56d
diff --git a/api/_lib/x402-offer-receipt.js b/api/_lib/x402-offer-receipt.js
new file mode 100644
index 000000000..6b6737533
--- /dev/null
+++ b/api/_lib/x402-offer-receipt.js
@@ -0,0 +1,123 @@
+// x402 Offer & Receipt — declaration helper + EIP-712 issuer module.
+//
+// Two concerns live here:
+//
+// offerReceiptDeclaration() — static capability declaration for the
+// 402 body's `extensions` map (uses OFFER_RECEIPT_SIGNING_PRIVATE_KEY /
+// OFFER_RECEIPT_JWK and the existing offer-receipt-issuer stack).
+//
+// issuer / signOffersForAccepts / signReceipt — EIP-712 signing primitives
+// keyed by X402_RECEIPT_SIGNING_KEY. `issuer` is null when the var is unset
+// (the no-op / rollback toggle — unset in Vercel to disable without
+// redeploying code). Signing key MUST NOT be any X402_PAY_TO_* wallet.
+
+import {
+ createEIP712OfferReceiptIssuer,
+ convertNetworkStringToCAIP2,
+ declareOfferReceiptExtension,
+} from '@x402/extensions/offer-receipt';
+import { privateKeyToAccount } from 'viem/accounts';
+
+import { env } from './env.js';
+
+// ── Static capability declaration (used by x402-spec.js / build402Body) ─────
+
+/**
+ * Returns the `extensions["offer-receipt"]` declaration fragment for the 402
+ * body when a signing key is configured, null otherwise.
+ */
+export function offerReceiptDeclaration() {
+ if (!env.OFFER_RECEIPT_SIGNING_PRIVATE_KEY && !env.OFFER_RECEIPT_JWK) return null;
+ return declareOfferReceiptExtension({
+ includeTxHash: false,
+ offerValiditySeconds: 60,
+ });
+}
+
+// ── EIP-712 signing primitives keyed by X402_RECEIPT_SIGNING_KEY ─────────────
+
+// Module-private SDK issuer. null when X402_RECEIPT_SIGNING_KEY is unset.
+let _sdkIssuer = null;
+
+function buildIssuer() {
+ const raw = process.env.X402_RECEIPT_SIGNING_KEY;
+ if (!raw) return null;
+
+ const trimmed = raw.trim();
+ const norm = trimmed.startsWith('0x') ? trimmed : `0x${trimmed}`;
+
+ // Validate length before passing to viem — a malformed key means the operator
+ // intended to enable signing but mis-configured it. Throw loudly at boot.
+ if (!/^0x[0-9a-fA-F]{64}$/.test(norm)) {
+ throw new Error(
+ 'x402_receipt_signing_key_invalid: X402_RECEIPT_SIGNING_KEY must be a ' +
+ '0x-prefixed 32-byte hex private key (64 hex chars after 0x). ' +
+ 'Generate with: node -e "console.log(require(\'viem/accounts\').generatePrivateKey())"',
+ );
+ }
+
+ const account = privateKeyToAccount(norm);
+ const signerAddress = account.address.toLowerCase();
+ const kid = `did:pkh:eip155:1:${signerAddress}#key-1`;
+ const signTypedData = (params) => account.signTypedData(params);
+
+ _sdkIssuer = createEIP712OfferReceiptIssuer(kid, signTypedData);
+
+ return { kid, signerAddress, sign: signTypedData };
+}
+
+/**
+ * One singleton issuer per process. Resolves to the EIP-712 issuer when
+ * X402_RECEIPT_SIGNING_KEY is set, otherwise null (feature disabled).
+ * @type {{ kid: string, signerAddress: string, sign: Function } | null}
+ */
+export const issuer = buildIssuer();
+
+/**
+ * Sign one offer per accept entry on a 402 response. Returns the array of
+ * signed offers in the wire shape consumed by extractOffersFromPaymentRequired
+ * on the client side. Returns [] when the issuer is null (feature disabled).
+ *
+ * @param {{ accepts: object[], resourceUrl: string, validitySeconds?: number }} opts
+ * @returns {Promise<object[]>}
+ */
+export async function signOffersForAccepts({ accepts, resourceUrl, validitySeconds = 60 }) {
+ if (!_sdkIssuer) return [];
+ const results = [];
+ for (let i = 0; i < accepts.length; i++) {
+ const a = accepts[i];
+ results.push(
+ await _sdkIssuer.issueOffer(resourceUrl, {
+ acceptIndex: i,
+ scheme: a.scheme,
+ network: convertNetworkStringToCAIP2(a.network),
+ asset: a.asset,
+ payTo: a.payTo,
+ amount: a.amount,
+ offerValiditySeconds: validitySeconds,
+ }),
+ );
+ }
+ return results;
+}
+
+/**
+ * Sign one receipt for a settled 200 response. Returns the signed receipt in
+ * the wire shape consumed by extractReceiptFromResponse on the client side.
+ * Returns null when the issuer is null (feature disabled) or when payer/network
+ * are absent — a normal condition for endpoints whose settlement skipped the
+ * facilitator (e.g. BSC `direct`).
+ *
+ * @param {{ resourceUrl: string, payer: string|null, network: string|null, txHash?: string, includeTxHash?: boolean }} opts
+ * @returns {Promise<object|null>}
+ */
+export async function signReceipt({ resourceUrl, payer, network, txHash, includeTxHash = false }) {
+ if (!_sdkIssuer) return null;
+ if (payer == null || network == null) return null;
+ return _sdkIssuer.issueReceipt(
+ resourceUrl,
+ payer,
+ convertNetworkStringToCAIP2(network),
+ includeTxHash ? txHash : undefined,
+ );
+}
diff --git a/api/x402/api-key-health.js b/api/x402/api-key-health.js
new file mode 100644
index 000000000..7bc5bd273
--- /dev/null
+++ b/api/x402/api-key-health.js
@@ -0,0 +1,195 @@
+// POST /api/x402/api-key-health
+//
+// API Key Validity Health Check — paid x402 endpoint that verifies the platform
+// has a valid key covering the requested access scope (default: "autonomous_loop").
+//
+// Body: { scope?: string } — scope to check (defaults to "autonomous_loop")
+//
+// Response:
+// { valid, scopes, expires_at, key_type, source, checked_at }
+//
+// Key resolution order:
+// 1. x402_subscriptions where meta.scope = <scope> or meta.scopes ∋ <scope>
+// → a dedicated subscription key for this scope; reports actual expiry.
+// 2. INTERNAL_API_KEY env var — internal service bypass; always valid, no expiry.
+// 3. Neither found → valid: false, scopes: []
+//
+// Downstream consumer:
+// autonomous-registry.js `api-key-validity-check` — the autonomous loop pays
+// this endpoint hourly to confirm its access lane is healthy and surfaces
+// hours_until_expiry in x402_autonomous_log.signal_data; storeValue raises a
+// Redis alert (x402:api-key-health:expiry-alert) when expiry < 24 h.
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import { sql } from '../_lib/db.js';
+import { env } from '../_lib/env.js';
+import { logger } from '../_lib/usage.js';
+
+const ROUTE = '/api/x402/api-key-health';
+const log = logger('x402-api-key-health');
+
+const DESCRIPTION =
+ 'API Key Validity Health Check — verifies that the platform has a valid, ' +
+ 'non-expired access key covering a given scope. Checks x402 subscription keys ' +
+ 'and the internal service key. Returns valid, scopes, expires_at, and key_type. ' +
+ 'Used by the autonomous loop to confirm its access lane is healthy before each tick. ' +
+ 'Pay-per-call in USDC on Solana or Base mainnet.';
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ scope: {
+ type: 'string',
+ description: 'Access scope to verify (e.g. "autonomous_loop", "internal")',
+ default: 'autonomous_loop',
+ },
+ },
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['valid', 'scopes', 'checked_at'],
+ properties: {
+ valid: { type: 'boolean' },
+ scopes: { type: 'array', items: { type: 'string' } },
+ expires_at: { type: ['string', 'null'] },
+ key_type: { type: ['string', 'null'] },
+ source: { type: ['string', 'null'] },
+ key_prefix: { type: ['string', 'null'] },
+ rate_limit_per_minute: { type: ['integer', 'null'] },
+ checked_at: { type: 'string', format: 'date-time' },
+ },
+};
+
+const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['health check', 'api key validation', 'autonomous loop', 'access control'],
+ input: {
+ type: 'json',
+ example: { scope: 'autonomous_loop' },
+ schema: INPUT_SCHEMA,
+ },
+ output: {
+ type: 'json',
+ example: {
+ valid: true,
+ scopes: ['internal', 'autonomous_loop', 'bypass_x402'],
+ expires_at: null,
+ key_type: 'internal',
+ source: 'env',
+ key_prefix: null,
+ rate_limit_per_minute: null,
+ checked_at: '2026-06-28T12:00:00Z',
+ },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+// Extract the scopes array from a subscription meta object.
+function extractScopes(meta) {
+ if (!meta || typeof meta !== 'object') return [];
+ if (Array.isArray(meta.scopes)) return meta.scopes.filter((s) => typeof s === 'string');
+ if (typeof meta.scope === 'string' && meta.scope) return [meta.scope];
+ return [];
+}
+
+// Look up the best active subscription for the requested scope.
+// Prefers non-expiring keys; among expiring ones, prefers the latest expires_at.
+async function resolveSubscription(scope) {
+ try {
+ const scopeJson = JSON.stringify([scope]);
+ const rows = await sql`
+ SELECT id, name, key_prefix, rate_limit_per_minute, expires_at, revoked_at, meta
+ FROM x402_subscriptions
+ WHERE revoked_at IS NULL
+ AND (expires_at IS NULL OR expires_at > now())
+ AND (
+ meta->>'scope' = ${scope}
+ OR meta->'scopes' @> ${scopeJson}::jsonb
+ )
+ ORDER BY
+ CASE WHEN expires_at IS NULL THEN 1 ELSE 0 END DESC,
+ expires_at DESC NULLS LAST
+ LIMIT 1
+ `;
+ return rows[0] || null;
+ } catch (err) {
+ log.warn('subscription_lookup_failed', { scope, message: err?.message });
+ return null;
+ }
+}
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ // $0.001 USDC = 1000 atomics. Override via X402_PRICE_API_KEY_HEALTH.
+ priceAtomics: priceFor('api-key-health', '1000'),
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ services: ['api-key-health'],
+ service: withService({
+ serviceName: 'three.ws API Key Health Check',
+ tags: ['health', 'api-key', 'autonomous', 'access-control'],
+ }),
+ async handler(req) {
+ const checkedAt = new Date().toISOString();
+ let body = {};
+ try { body = typeof req.body === 'object' ? req.body : JSON.parse(req.body || '{}'); } catch { /* use empty */ }
+ const scope = (typeof body?.scope === 'string' && body.scope.trim()) || 'autonomous_loop';
+
+ // 1. Check for a dedicated subscription key covering this scope.
+ const sub = await resolveSubscription(scope);
+ if (sub) {
+ const scopes = extractScopes(sub.meta);
+ if (!scopes.includes(scope)) scopes.unshift(scope);
+ return {
+ valid: true,
+ scopes,
+ expires_at: sub.expires_at ? new Date(sub.expires_at).toISOString() : null,
+ key_type: 'subscription',
+ source: 'x402_subscriptions',
+ key_prefix: sub.key_prefix || null,
+ rate_limit_per_minute: sub.rate_limit_per_minute ?? null,
+ checked_at: checkedAt,
+ };
+ }
+
+ // 2. Fall back to INTERNAL_API_KEY — always valid when configured, no expiry.
+ const internalKey = env.INTERNAL_API_KEY || process.env.INTERNAL_API_KEY;
+ if (internalKey && internalKey.length > 8) {
+ return {
+ valid: true,
+ scopes: ['internal', 'autonomous_loop', 'bypass_x402'],
+ expires_at: null,
+ key_type: 'internal',
+ source: 'env',
+ key_prefix: null,
+ rate_limit_per_minute: null,
+ checked_at: checkedAt,
+ };
+ }
+
+ // 3. No key found for this scope.
+ log.warn('api_key_health_no_key', { scope });
+ return {
+ valid: false,
+ scopes: [],
+ expires_at: null,
+ key_type: null,
+ source: null,
+ key_prefix: null,
+ rate_limit_per_minute: null,
+ checked_at: checkedAt,
+ };
+ },
+});
diff --git a/api/x402/feed-health.js b/api/x402/feed-health.js
new file mode 100644
index 000000000..1b887b2e1
--- /dev/null
+++ b/api/x402/feed-health.js
@@ -0,0 +1,240 @@
+// POST /api/x402/feed-health
+//
+// Paid RSS/JSON feed validation endpoint. For $0.001 USDC the server fetches
+// a named public feed, parses it, and returns a structural health verdict:
+// whether the feed is valid XML, how many items it contains, and whether the
+// latest entry's title matches the platform's canonical changelog record.
+//
+// Supported feeds:
+// changelog_rss — three.ws/changelog.xml — the public RSS 2.0 changelog feed
+//
+// The autonomous loop calls this every 5 minutes with { feed: "changelog_rss" }
+// to detect three failure modes before holders notice:
+// • The XML is broken (invalid syntax or unreachable URL)
+// • The item count drifts from the canonical source (build step skipped)
+// • The latest title diverges from the DB record (content went to the feed
+// but the merge step that writes public/changelog.json was not rerun)
+
+import { readFileSync } from 'node:fs';
+import { XMLParser } from 'fast-xml-parser';
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { env } from '../_lib/env.js';
+import { priceFor } from '../_lib/x402-prices.js';
+
+const ROUTE = '/api/x402/feed-health';
+const FETCH_TIMEOUT_MS = 8_000;
+
+const DESCRIPTION =
+ 'three.ws Feed Health Validator — fetches a named public feed (changelog RSS, ' +
+ 'sitemap, etc.) and returns a structural health verdict: { valid, item_count, ' +
+ 'latest_title }. Pays $0.001 USDC per check. Supported feeds: changelog_rss. ' +
+ 'The latest_title is cross-checked against the canonical changelog record so ' +
+ 'both a broken XML feed and a stale/diverged feed surface as valid:false.';
+
+const SUPPORTED_FEEDS = ['changelog_rss'];
+
+const INPUT_EXAMPLE = { feed: 'changelog_rss' };
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['feed'],
+ properties: {
+ feed: {
+ type: 'string',
+ enum: SUPPORTED_FEEDS,
+ description: 'Feed identifier. Currently: changelog_rss (three.ws/changelog.xml).',
+ },
+ },
+};
+
+const OUTPUT_EXAMPLE = {
+ feed: 'changelog_rss',
+ valid: true,
+ item_count: 1241,
+ latest_title: 'x402 Volume Analytics — the platform measures its own payment economy',
+ title_match: true,
+ fetch_ms: 312,
+ checked_at: '2026-06-28T12:00:00.000Z',
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['feed', 'valid', 'item_count', 'latest_title', 'title_match', 'checked_at'],
+ properties: {
+ feed: { type: 'string' },
+ valid: { type: 'boolean' },
+ item_count: { type: 'integer', minimum: 0 },
+ latest_title: { type: ['string', 'null'] },
+ title_match: { type: 'boolean' },
+ fetch_ms: { type: ['integer', 'null'] },
+ error: { type: 'string' },
+ checked_at: { type: 'string', format: 'date-time' },
+ },
+};
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'POST', bodyExample: INPUT_EXAMPLE },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+const xmlParser = new XMLParser({ ignoreAttributes: false, parseTagValue: true });
+
+// Read the canonical changelog record from the compiled public asset. The file
+// is bundled into the Vercel deployment alongside the API so readFileSync is
+// safe here. We load it once per cold start — it only changes on deploy.
+let _changelogEntries = null;
+function getChangelogEntries() {
+ if (_changelogEntries) return _changelogEntries;
+ try {
+ const raw = readFileSync(
+ new URL('../../public/changelog.json', import.meta.url),
+ 'utf8',
+ );
+ const parsed = JSON.parse(raw);
+ _changelogEntries = Array.isArray(parsed?.entries) ? parsed.entries : [];
+ } catch {
+ _changelogEntries = [];
+ }
+ return _changelogEntries;
+}
+
+async function validateChangelogRss(origin) {
+ const url = `${origin}/changelog.xml`;
+ const start = Date.now();
+
+ let xmlText;
+ try {
+ const res = await fetch(url, {
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ headers: { accept: 'application/rss+xml, application/xml, text/xml' },
+ });
+ if (!res.ok) {
+ return {
+ valid: false,
+ item_count: 0,
+ latest_title: null,
+ title_match: false,
+ fetch_ms: Date.now() - start,
+ error: `HTTP ${res.status} fetching ${url}`,
+ };
+ }
+ xmlText = await res.text();
+ } catch (err) {
+ return {
+ valid: false,
+ item_count: 0,
+ latest_title: null,
+ title_match: false,
+ fetch_ms: Date.now() - start,
+ error: `Fetch failed: ${err?.message || String(err)}`,
+ };
+ }
+
+ const fetchMs = Date.now() - start;
+
+ let parsed;
+ try {
+ parsed = xmlParser.parse(xmlText);
+ } catch (err) {
+ return {
+ valid: false,
+ item_count: 0,
+ latest_title: null,
+ title_match: false,
+ fetch_ms: fetchMs,
+ error: `XML parse failed: ${err?.message || String(err)}`,
+ };
+ }
+
+ const channel = parsed?.rss?.channel;
+ if (!channel) {
+ return {
+ valid: false,
+ item_count: 0,
+ latest_title: null,
+ title_match: false,
+ fetch_ms: fetchMs,
+ error: 'RSS channel element missing from parsed document',
+ };
+ }
+
+ // fast-xml-parser coerces a single <item> to an object rather than an array.
+ const rawItems = channel.item;
+ const items = Array.isArray(rawItems)
+ ? rawItems
+ : rawItems != null
+ ? [rawItems]
+ : [];
+
+ const itemCount = items.length;
+ const latestTitle = typeof items[0]?.title === 'string'
+ ? items[0].title.trim()
+ : items[0]?.title != null
+ ? String(items[0].title).trim()
+ : null;
+
+ // Cross-check against the canonical compiled record.
+ const entries = getChangelogEntries();
+ const expectedTitle = entries.length > 0 ? (entries[0].title || null) : null;
+ const titleMatch = latestTitle != null && expectedTitle != null
+ ? latestTitle === expectedTitle
+ : false;
+
+ return {
+ valid: true,
+ item_count: itemCount,
+ latest_title: latestTitle,
+ title_match: titleMatch,
+ fetch_ms: fetchMs,
+ };
+}
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: priceFor('feed-health', '1000'),
+ networks: ['solana'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Feed Health',
+ tags: ['rss', 'feed', 'health', 'changelog', 'validation'],
+ }),
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+ async handler({ req }) {
+ const body = req.body || {};
+ const feed = String(body.feed || '').trim();
+
+ if (!SUPPORTED_FEEDS.includes(feed)) {
+ const err = new Error(
+ `unsupported feed "${feed}". Supported: ${SUPPORTED_FEEDS.join(', ')}.`,
+ );
+ err.status = 400;
+ err.code = 'unsupported_feed';
+ throw err;
+ }
+
+ const origin = (env.APP_ORIGIN || 'https://three.ws').replace(/\/$/, '');
+ const result = await validateChangelogRss(origin);
+
+ return {
+ feed,
+ ...result,
+ checked_at: new Date().toISOString(),
+ };
+ },
+});
diff --git a/api/x402/rate-limit-probe.js b/api/x402/rate-limit-probe.js
new file mode 100644
index 000000000..644de652b
--- /dev/null
+++ b/api/x402/rate-limit-probe.js
@@ -0,0 +1,249 @@
+// POST /api/x402/rate-limit-probe
+//
+// Paid capacity probe ($0.001 USDC) that returns current rate-limit status for
+// any x402 autonomous-loop target endpoint. The autonomous loop pays this canary
+// before scheduling high-frequency oracle calls — if remaining_calls is low,
+// lower-priority entries yield their slot so oracle throughput is preserved.
+//
+// Body: { endpoint: "/api/x402/crypto-intel" }
+//
+// Response:
+// endpoint — echoed from body
+// remaining_calls — floor(remaining_capacity_atomic / price_atomic)
+// reset_at — next UTC midnight (daily-cap reset)
+// limit — floor(daily_cap_atomic / price_atomic)
+// daily_cap_atomic — autonomous loop daily USDC budget (atomics)
+// daily_spent_atomic — spend so far today (atomics)
+// remaining_capacity_atomic — cap - spent
+// price_atomic — 402 challenge price for the target endpoint
+// cooldown_active — true if any matching registry entry is in cooldown
+// cooldown_ttl_seconds — longest cooldown TTL remaining (seconds); null if none
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import { getRedis } from '../_lib/redis.js';
+import { env } from '../_lib/env.js';
+import { getSelfRegistry, DAILY_CAP_ATOMIC } from '../_lib/x402/autonomous-registry.js';
+
+const ROUTE = '/api/x402/rate-limit-probe';
+const COOLDOWN_PREFIX = 'x402:auto:last:';
+const DAILY_SPEND_PREFIX = 'x402:auto:daily:';
+
+// Default price for the target endpoint when the live 402 probe fails.
+// $0.01 USDC = 10 000 atomics — correct for crypto-intel, a reasonable fallback
+// for any comparably priced oracle endpoint.
+const DEFAULT_PRICE_ATOMIC = 10_000;
+
+const DESCRIPTION =
+ 'Rate-Limit Capacity Probe — pay $0.001 USDC to learn how many more calls the ' +
+ 'x402 autonomous loop can make to a target endpoint today before hitting its daily ' +
+ 'USDC spend cap. Returns remaining_calls, reset_at, and cooldown_active so agents ' +
+ 'can throttle dynamically instead of discovering the cap by failure.';
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['endpoint'],
+ properties: {
+ endpoint: {
+ type: 'string',
+ description: 'Relative path of the target x402 endpoint, e.g. "/api/x402/crypto-intel".',
+ pattern: '^/api/',
+ },
+ },
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['endpoint', 'remaining_calls', 'reset_at', 'limit'],
+ properties: {
+ endpoint: { type: 'string' },
+ remaining_calls: { type: 'integer', minimum: 0 },
+ reset_at: { type: 'string', format: 'date-time' },
+ limit: { type: 'integer', minimum: 0 },
+ daily_cap_atomic: { type: 'integer' },
+ daily_spent_atomic: { type: 'integer' },
+ remaining_capacity_atomic: { type: 'integer' },
+ price_atomic: { type: 'integer' },
+ cooldown_active: { type: 'boolean' },
+ cooldown_ttl_seconds: { type: ['integer', 'null'] },
+ },
+};
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'json', example: { endpoint: '/api/x402/crypto-intel' } },
+ output: {
+ type: 'json',
+ example: {
+ endpoint: '/api/x402/crypto-intel',
+ remaining_calls: 42,
+ reset_at: '2026-06-29T00:00:00.000Z',
+ limit: 500,
+ daily_cap_atomic: 5000000,
+ daily_spent_atomic: 4580000,
+ remaining_capacity_atomic: 420000,
+ price_atomic: 10000,
+ cooldown_active: false,
+ cooldown_ttl_seconds: null,
+ },
+ },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+// Compute the next UTC midnight (the moment the daily cap resets).
+function nextUtcMidnight() {
+ const now = new Date();
+ const midnight = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1));
+ return midnight.toISOString();
+}
+
+// Today's daily spend key used by the autonomous loop.
+function dailySpendKey() {
+ return `${DAILY_SPEND_PREFIX}${new Date().toISOString().slice(0, 10)}`;
+}
+
+// Probe the target endpoint (no payment header) to learn its 402 challenge price.
+// Returns the smallest price_atomic across all offered accepts, or null on failure.
+async function probeEndpointPrice(origin, endpoint) {
+ try {
+ const url = `${origin}${endpoint}`;
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({}),
+ signal: AbortSignal.timeout(5000),
+ });
+ if (res.status !== 402) return null;
+ const body = await res.json();
+ // x402 v2 wire format: { accepts: [{ amount, ... }] }
+ // Also handle legacy { requirements: [...] }
+ const accepts = body?.accepts || body?.requirements;
+ if (!Array.isArray(accepts) || !accepts.length) return null;
+ const prices = accepts
+ .map((a) => parseInt(a.amount, 10))
+ .filter((n) => Number.isFinite(n) && n > 0);
+ if (!prices.length) return null;
+ return Math.min(...prices);
+ } catch {
+ return null;
+ }
+}
+
+// Read the current daily spend for the autonomous loop from Redis.
+async function readDailySpent(redis) {
+ if (!redis) return 0;
+ try {
+ const val = await redis.get(dailySpendKey());
+ return val ? Number(val) : 0;
+ } catch {
+ return 0;
+ }
+}
+
+// Find all registry entries whose `path` matches the target endpoint (prefix match
+// so /api/x402/crypto-intel matches both exact entries and ?query-param variants).
+function matchingEntries(endpoint) {
+ const registry = getSelfRegistry();
+ return registry.filter((e) => {
+ if (!e.path) return false;
+ const base = e.path.split('?')[0];
+ return base === endpoint;
+ });
+}
+
+// Read the maximum cooldown TTL (in seconds) across matching registry entries.
+// Returns { active: boolean, ttl_seconds: number|null }.
+async function readCooldownState(redis, entries) {
+ if (!redis || !entries.length) return { active: false, ttl_seconds: null };
+ try {
+ const ttls = await Promise.all(
+ entries.map((e) => redis.ttl(`${COOLDOWN_PREFIX}${e.id}`)),
+ );
+ // ttl() returns: -2 = key absent, -1 = no expiry, N = seconds remaining
+ const active = ttls.filter((t) => t > 0);
+ if (!active.length) return { active: false, ttl_seconds: null };
+ return { active: true, ttl_seconds: Math.max(...active) };
+ } catch {
+ return { active: false, ttl_seconds: null };
+ }
+}
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: priceFor('rate-limit-probe', '1000'),
+ networks: ['base', 'solana'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Rate-Limit Probe',
+ tags: ['rate-limit', 'capacity', 'autonomous-loop', 'health', 'oracle'],
+ }),
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ const body = req.body || {};
+ const endpoint = typeof body.endpoint === 'string' ? body.endpoint.trim() : '';
+
+ if (!endpoint) {
+ const err = new Error('"endpoint" is required');
+ err.status = 400;
+ err.code = 'missing_endpoint';
+ throw err;
+ }
+ if (!endpoint.startsWith('/api/')) {
+ const err = new Error('"endpoint" must be a relative /api/ path');
+ err.status = 400;
+ err.code = 'invalid_endpoint';
+ throw err;
+ }
+
+ const origin = env.APP_ORIGIN || 'https://three.ws';
+ const redis = getRedis();
+
+ // Run the live 402 price probe and Redis reads in parallel.
+ const [livePrice, dailySpentAtomic, matchEntries] = await Promise.all([
+ probeEndpointPrice(origin, endpoint),
+ readDailySpent(redis),
+ Promise.resolve(matchingEntries(endpoint)),
+ ]);
+
+ const priceAtomic = livePrice ?? DEFAULT_PRICE_ATOMIC;
+ const { active: cooldownActive, ttl_seconds: cooldownTtlSeconds } =
+ await readCooldownState(redis, matchEntries);
+
+ const capAtomic = DAILY_CAP_ATOMIC;
+ const remainingCapacityAtomic = Math.max(0, capAtomic - dailySpentAtomic);
+ const remainingCalls = priceAtomic > 0
+ ? Math.floor(remainingCapacityAtomic / priceAtomic)
+ : 0;
+ const limit = priceAtomic > 0
+ ? Math.floor(capAtomic / priceAtomic)
+ : 0;
+
+ return {
+ endpoint,
+ remaining_calls: remainingCalls,
+ reset_at: nextUtcMidnight(),
+ limit,
+ daily_cap_atomic: capAtomic,
+ daily_spent_atomic: dailySpentAtomic,
+ remaining_capacity_atomic: remainingCapacityAtomic,
+ price_atomic: priceAtomic,
+ cooldown_active: cooldownActive,
+ cooldown_ttl_seconds: cooldownTtlSeconds,
+ };
+ },
+});
diff --git a/api/x402/spend-session.js b/api/x402/spend-session.js
new file mode 100644
index 000000000..f25a4d532
--- /dev/null
+++ b/api/x402/spend-session.js
@@ -0,0 +1,159 @@
+// POST /api/x402/spend-session
+//
+// Paid endpoint: Spend Session Audit — $0.005 USDC per call.
+//
+// Queries the platform's payment_sessions ledger and returns a live snapshot
+// of all agent spend sessions: how many are currently active, how much budget
+// remains across them, and how many have expired (in the last 24h).
+//
+// The autonomous loop calls this every 15 minutes (mode:"audit") to watch for
+// a spike in expired_count — a leading indicator that session cleanup is broken
+// or agents are not renewing sessions before they lapse. Signal recorded to
+// x402_autonomous_log.signal_data and the health pipeline.
+//
+// Request body:
+// { "mode": "audit" } — aggregate session health snapshot (only mode today)
+//
+// Response (mode=audit):
+// {
+// mode: "audit",
+// active_count: <int>, — sessions with status='active', expires_at > now
+// exhausted_count: <int>, — sessions with status='exhausted'
+// expired_count_24h: <int>, — sessions that expired in the last 24 hours
+// total_budget_remaining_usdc: <number>, — sum of (budget_usdc - spent_usdc) / 1e6, active sessions
+// avg_budget_remaining_usd: <number|null>,— average remaining per active session
+// total_spent_usdc: <number>, — total USDC spent across all active sessions
+// ts: <ISO string>
+// }
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import { sql } from '../_lib/db.js';
+
+const ROUTE = '/api/x402/spend-session';
+
+const DESCRIPTION =
+ 'three.ws Spend Session Audit — pay $0.005 USDC per call to receive a live ' +
+ 'snapshot of all agent payment-session health on the platform: active session ' +
+ 'count, total remaining USDC budget, and how many sessions expired in the last ' +
+ '24 hours. An expired_count spike signals that agents are not renewing sessions ' +
+ 'before they lapse or that the session-expiry sweep is failing.';
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ mode: {
+ type: 'string',
+ enum: ['audit'],
+ default: 'audit',
+ description: 'Audit mode: returns aggregate session health snapshot.',
+ },
+ },
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ mode: { type: 'string' },
+ active_count: { type: 'integer', description: 'Sessions currently active and not expired.' },
+ exhausted_count: { type: 'integer', description: 'Sessions with status exhausted.' },
+ expired_count_24h: { type: 'integer', description: 'Sessions that expired in the last 24 hours.' },
+ total_budget_remaining_usdc: { type: 'number', description: 'Sum of remaining budget (USD) across active sessions.' },
+ avg_budget_remaining_usd: { type: ['number', 'null'], description: 'Average remaining budget per active session.' },
+ total_spent_usdc: { type: 'number', description: 'Total USDC spent across all active sessions.' },
+ ts: { type: 'string', format: 'date-time' },
+ },
+};
+
+const PRICE_ATOMICS = priceFor('spend-session', '5000'); // $0.005 USDC default
+
+export default paidEndpoint(
+ {
+ route: ROUTE,
+ priceAtomics: PRICE_ATOMICS,
+ networks: ['base', 'solana'],
+ description: DESCRIPTION,
+ inputSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ inputExample: { mode: 'audit' },
+ outputExample: {
+ mode: 'audit',
+ active_count: 14,
+ exhausted_count: 2,
+ expired_count_24h: 1,
+ total_budget_remaining_usdc: 3.42,
+ avg_budget_remaining_usd: 0.244,
+ total_spent_usdc: 0.88,
+ ts: '2026-06-28T12:00:00.000Z',
+ },
+ bazaarSchema: buildBazaarSchema({
+ route: ROUTE,
+ name: 'Spend Session Audit',
+ description: DESCRIPTION,
+ priceAtomics: PRICE_ATOMICS,
+ inputSchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ inputExample: { mode: 'audit' },
+ }),
+ accessControl: installAccessControl({ route: ROUTE }),
+ service: withService(ROUTE),
+ },
+ async (req, body) => {
+ const mode = body?.mode ?? 'audit';
+ if (mode !== 'audit') {
+ return { status: 400, body: { error: 'invalid_mode', message: 'Only mode="audit" is supported.' } };
+ }
+
+ // Active sessions: status='active' and not yet expired
+ const [activeSummary] = await sql`
+ SELECT
+ count(*) AS active_count,
+ coalesce(sum(budget_usdc - spent_usdc), 0) AS remaining_atomics,
+ coalesce(sum(spent_usdc), 0) AS spent_atomics,
+ coalesce(avg(budget_usdc - spent_usdc), null) AS avg_remaining_atomics
+ FROM payment_sessions
+ WHERE status = 'active'
+ AND expires_at > now()
+ `;
+
+ // Exhausted sessions
+ const [exhaustedSummary] = await sql`
+ SELECT count(*) AS exhausted_count
+ FROM payment_sessions
+ WHERE status = 'exhausted'
+ `;
+
+ // Sessions that expired naturally (status changed to 'expired') in the last 24h
+ const [expiredSummary] = await sql`
+ SELECT count(*) AS expired_count_24h
+ FROM payment_sessions
+ WHERE status = 'expired'
+ AND updated_at >= now() - interval '24 hours'
+ `;
+
+ const activeCount = Number(activeSummary?.active_count ?? 0);
+ const exhaustedCount = Number(exhaustedSummary?.exhausted_count ?? 0);
+ const expiredCount24h = Number(expiredSummary?.expired_count_24h ?? 0);
+ const remainingAtomics = BigInt(activeSummary?.remaining_atomics ?? 0);
+ const spentAtomics = BigInt(activeSummary?.spent_atomics ?? 0);
+ const avgRemainingAtomics = activeSummary?.avg_remaining_atomics != null
+ ? Number(activeSummary.avg_remaining_atomics)
+ : null;
+
+ return {
+ mode: 'audit',
+ active_count: activeCount,
+ exhausted_count: exhaustedCount,
+ expired_count_24h: expiredCount24h,
+ total_budget_remaining_usdc: Number(remainingAtomics) / 1e6,
+ avg_budget_remaining_usd: avgRemainingAtomics != null ? avgRemainingAtomics / 1e6 : null,
+ total_spent_usdc: Number(spentAtomics) / 1e6,
+ ts: new Date().toISOString(),
+ };
+ },
+);
diff --git a/api/x402/telegram-health.js b/api/x402/telegram-health.js
new file mode 100644
index 000000000..198fc3db0
--- /dev/null
+++ b/api/x402/telegram-health.js
@@ -0,0 +1,230 @@
+// POST /api/x402/telegram-health
+//
+// Changelog Telegram Bot Health Check — verifies that the platform bot can
+// reach the Telegram API and is correctly configured, so new changelog entries
+// will actually reach $THREE holders when `npm run changelog:push` runs.
+//
+// Body: { bot: "changelog" }
+// bot — which platform bot to probe. Only "changelog" is defined today;
+// the field is required so callers are explicit about intent and
+// future bots (e.g. "oracle", "ops") can share the same endpoint.
+//
+// Response: { bot, reachable, bot_id, bot_username, latency_ms, checked_at }
+// reachable — true when Telegram API returned a valid bot record
+// bot_id — numeric Telegram user_id of the bot (null if unreachable)
+// bot_username — @handle (null if unreachable)
+// latency_ms — round-trip to api.telegram.org (null on timeout/error)
+// checked_at — ISO-8601 timestamp of this probe
+//
+// Why pay-per-call? The check confirms the TELEGRAM_BOT_TOKEN is valid and
+// the bot is live; that proof is worth $0.001 USDC to any agent that needs
+// to know whether the changelog delivery channel is healthy before attempting
+// a push. Also: keeping the endpoint in the x402 bazaar makes the health
+// signal discoverable and auditable in x402_autonomous_log.
+//
+// Alert convention: when unreachable, the handler writes a Redis key
+// `x402:telegram-health:alert` (TTL 25 min) so the ops dashboard and the
+// changelog-push script can detect a degraded channel without a DB query.
+//
+// Env:
+// TELEGRAM_BOT_TOKEN — bot token from @BotFather (same token used
+// by scripts/changelog-telegram.mjs and
+// /api/pump/deliver-telegram.js)
+// TELEGRAM_CHANGELOG_CHAT_ID — changelog channel id (used only for context
+// in error messages, not for sending)
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import { getRedis } from '../_lib/redis.js';
+
+const ROUTE = '/api/x402/telegram-health';
+const TELEGRAM_API = 'https://api.telegram.org';
+const PROBE_TIMEOUT_MS = 8000;
+
+// Redis key written when the changelog bot is unreachable.
+const ALERT_KEY = 'x402:telegram-health:alert';
+const ALERT_TTL_S = 25 * 60; // 25 min — longer than the 5-min probe cooldown
+
+const VALID_BOTS = new Set(['changelog']);
+
+const DESCRIPTION =
+ 'Changelog Telegram Bot Health Check — pays $0.001 USDC to verify that the ' +
+ 'three.ws platform bot can reach the Telegram API and is alive. Returns ' +
+ '{ reachable, bot_id, bot_username, latency_ms }. If unreachable, new changelog ' +
+ 'entries will not reach $THREE holders until the bot is restored.';
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['bot'],
+ properties: {
+ bot: {
+ type: 'string',
+ enum: ['changelog'],
+ description: 'Which platform bot to probe.',
+ },
+ },
+ additionalProperties: false,
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['bot', 'reachable', 'checked_at'],
+ properties: {
+ bot: { type: 'string' },
+ reachable: { type: 'boolean' },
+ bot_id: { type: ['integer', 'null'] },
+ bot_username: { type: ['string', 'null'] },
+ latency_ms: { type: ['integer', 'null'] },
+ reason: { type: ['string', 'null'] },
+ checked_at: { type: 'string', format: 'date-time' },
+ },
+};
+
+const OUTPUT_EXAMPLE = {
+ bot: 'changelog',
+ reachable: true,
+ bot_id: 7234567890,
+ bot_username: 'three_ws_bot',
+ latency_ms: 142,
+ reason: null,
+ checked_at: '2026-06-28T12:00:00.000Z',
+};
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: {
+ type: 'http',
+ method: 'POST',
+ bodyType: 'json',
+ body: { bot: 'changelog' },
+ },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+// Probe the Telegram Bot API's getMe endpoint and return a health record.
+// Never throws — an unreachable Telegram API IS the health verdict.
+async function probeTelegramBot() {
+ const token = process.env.TELEGRAM_BOT_TOKEN;
+ const checkedAt = new Date().toISOString();
+
+ if (!token) {
+ return {
+ reachable: false,
+ bot_id: null,
+ bot_username: null,
+ latency_ms: null,
+ reason: 'TELEGRAM_BOT_TOKEN not configured',
+ checked_at: checkedAt,
+ };
+ }
+
+ const t0 = Date.now();
+ let data = null;
+ let latencyMs = null;
+ let reason = null;
+
+ try {
+ const r = await fetch(`${TELEGRAM_API}/bot${token}/getMe`, {
+ method: 'GET',
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
+ });
+ latencyMs = Date.now() - t0;
+ data = await r.json().catch(() => null);
+ if (!r.ok || !data?.ok) {
+ reason = data?.description || `HTTP ${r.status}`;
+ }
+ } catch (err) {
+ latencyMs = Date.now() - t0;
+ reason = err?.name === 'TimeoutError' || err?.name === 'AbortError'
+ ? `timeout after ${PROBE_TIMEOUT_MS}ms`
+ : (err?.message || 'network_error');
+ }
+
+ const botInfo = data?.result || null;
+ const reachable = !!botInfo && !reason;
+
+ return {
+ reachable,
+ bot_id: botInfo?.id ?? null,
+ bot_username: botInfo?.username ?? null,
+ latency_ms: latencyMs,
+ reason: reachable ? null : reason,
+ checked_at: checkedAt,
+ };
+}
+
+// Write or clear the ops alert key so the ops dashboard and changelog-push
+// can detect channel degradation without a DB query.
+async function updateAlert(reachable, details) {
+ let redis = null;
+ try { redis = await getRedis(); } catch { return; }
+ if (!redis) return;
+ try {
+ if (!reachable) {
+ await redis.set(
+ ALERT_KEY,
+ JSON.stringify({
+ reason: details.reason,
+ bot_id: details.bot_id,
+ latency_ms: details.latency_ms,
+ checked_at: details.checked_at,
+ }),
+ { EX: ALERT_TTL_S },
+ );
+ } else {
+ await redis.del(ALERT_KEY);
+ }
+ } catch {
+ // Redis write failure must never surface as an endpoint error.
+ }
+}
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ // $0.001 USDC = 1000 atomics. Override via X402_PRICE_TELEGRAM_HEALTH.
+ priceAtomics: priceFor('telegram-health', '1000'),
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ services: ['telegram-health'],
+ service: withService({
+ serviceName: 'three.ws Telegram Bot Health',
+ tags: ['health', 'telegram', 'bot', 'changelog', 'canary'],
+ }),
+
+ async handler({ req }) {
+ // Parse body — require { bot: "changelog" }.
+ let bot = null;
+ try {
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
+ if (body.bot && typeof body.bot === 'string') bot = body.bot.trim();
+ } catch { /* leave bot null */ }
+
+ if (!bot || !VALID_BOTS.has(bot)) {
+ throw Object.assign(
+ new Error(`bot must be one of: ${[...VALID_BOTS].join(', ')}`),
+ { status: 400, code: 'invalid_bot' },
+ );
+ }
+
+ const health = await probeTelegramBot();
+ // Fire-and-forget alert update — never delays the response.
+ updateAlert(health.reachable, health).catch(() => {});
+
+ return { bot, ...health };
+ },
+});
diff --git a/api/x402/wallet-connect.js b/api/x402/wallet-connect.js
new file mode 100644
index 000000000..8d7698a81
--- /dev/null
+++ b/api/x402/wallet-connect.js
@@ -0,0 +1,190 @@
+// POST /api/x402/wallet-connect
+//
+// Wallet Connection Session Health Check.
+//
+// mode: "health" → tests whether the SIWS (Sign-In With Solana) session
+// initiation path is operational end-to-end: fires a real GET request to
+// /api/auth/siws/nonce against the platform origin, validates the returned
+// nonce structure (22 alphanumeric chars, future expiry, domain binding),
+// measures the roundtrip latency, and returns { session_created, latency_ms }.
+//
+// session_created: true — a valid challenge was issued, meaning wallet
+// connect handshakes CAN be initiated right now (the auth gateway, DB
+// write path, and CSRF layer are all alive).
+// session_created: false — the nonce endpoint returned an unexpected status,
+// a malformed challenge, or timed out (> 3s). Wallet connect is degraded.
+//
+// The autonomous loop pays this probe every 5 min and records the verdict to
+// x402_autonomous_log (signal_data: { session_created, latency_ms }). A Redis
+// alert key (x402:wallet-connect:alert) is set on degradation and cleared on
+// recovery — same convention as the forge-health and DID-sweep alerts.
+//
+// Pay-per-call: $0.001 USDC on Solana or Base mainnet.
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import { env } from '../_lib/env.js';
+
+const ROUTE = '/api/x402/wallet-connect';
+
+// Probe aborts after this many ms — a nonce round-trip slower than this
+// is already degraded from a user-experience standpoint.
+const PROBE_TIMEOUT_MS = 3000;
+
+// Latency above which the session-initiation path is flagged as slow even
+// if it succeeds — used to populate the `slow` field in the response.
+const SLOW_LATENCY_MS = 1000;
+
+function platformOrigin() {
+ return env.APP_ORIGIN || 'https://three.ws';
+}
+
+// Validate the nonce payload returned by /api/auth/siws/nonce. A conformant
+// nonce is a 22-char alphanumeric string with a future expiry — exactly what
+// a Phantom/Backpack wallet needs to construct a SIWS message.
+function isValidNonce(body) {
+ if (!body || typeof body !== 'object') return false;
+ const { nonce, expiresAt } = body;
+ if (typeof nonce !== 'string' || !/^[A-Za-z0-9]{22}$/.test(nonce)) return false;
+ if (!expiresAt || Date.parse(expiresAt) <= Date.now()) return false;
+ return true;
+}
+
+// Probe the SIWS nonce endpoint. Returns a plain object with the verdict
+// so the handler never throws — errors are captured as session_created:false.
+async function probeNonce() {
+ const t0 = Date.now();
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
+ try {
+ const res = await fetch(`${platformOrigin()}/api/auth/siws/nonce`, {
+ method: 'GET',
+ headers: { accept: 'application/json' },
+ signal: controller.signal,
+ });
+ const latencyMs = Date.now() - t0;
+ if (!res.ok) {
+ return { session_created: false, latency_ms: latencyMs, slow: false, nonce_valid: false, domain: null, reason: `nonce_http_${res.status}` };
+ }
+ const body = await res.json().catch(() => null);
+ const valid = isValidNonce(body);
+ return {
+ session_created: valid,
+ latency_ms: latencyMs,
+ slow: latencyMs > SLOW_LATENCY_MS,
+ nonce_valid: valid,
+ domain: typeof body?.domain === 'string' ? body.domain : null,
+ reason: valid ? null : 'invalid_nonce_shape',
+ };
+ } catch (err) {
+ const latencyMs = Date.now() - t0;
+ if (err?.name === 'AbortError') {
+ return { session_created: false, latency_ms: latencyMs, slow: true, nonce_valid: false, domain: null, reason: 'timeout' };
+ }
+ return { session_created: false, latency_ms: latencyMs, slow: false, nonce_valid: false, domain: null, reason: err?.message || 'fetch_error' };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+const DESCRIPTION =
+ 'Wallet Connection Session Health Check — probes the SIWS (Sign-In With ' +
+ 'Solana) session initiation path: issues a real nonce challenge against the ' +
+ 'platform auth gateway, validates its structure and expiry, and measures ' +
+ 'roundtrip latency. Returns { session_created, latency_ms }. Pay-per-call ' +
+ 'in USDC on Solana or Base mainnet.';
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['mode'],
+ properties: {
+ mode: { type: 'string', enum: ['health'] },
+ },
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['mode', 'session_created', 'latency_ms', 'checked_at'],
+ properties: {
+ mode: { type: 'string' },
+ session_created: { type: 'boolean' },
+ latency_ms: { type: ['integer', 'null'] },
+ slow: { type: ['boolean', 'null'] },
+ nonce_valid: { type: ['boolean', 'null'] },
+ domain: { type: ['string', 'null'] },
+ reason: { type: ['string', 'null'] },
+ checked_at: { type: 'string', format: 'date-time' },
+ },
+};
+
+const OUTPUT_EXAMPLE = {
+ mode: 'health',
+ session_created: true,
+ latency_ms: 83,
+ slow: false,
+ nonce_valid: true,
+ domain: 'three.ws',
+ reason: null,
+ checked_at: '2026-06-28T00:00:00Z',
+};
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'POST', bodySchema: INPUT_SCHEMA },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({ method: 'POST', bodySchema: INPUT_SCHEMA, outputSchema: OUTPUT_SCHEMA }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: priceFor('wallet-connect-health', '1000'), // $0.001 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ services: ['wallet-connect-health'],
+ service: withService({
+ serviceName: 'three.ws Wallet Connect Session Health',
+ tags: ['health', 'wallet', 'siws', 'session', 'auth', 'canary'],
+ }),
+ async handler({ req }) {
+ let mode = 'health';
+ try {
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ const raw = Buffer.concat(chunks).toString('utf8');
+ if (raw) {
+ const body = JSON.parse(raw);
+ if (body && typeof body.mode === 'string') {
+ mode = body.mode.trim().toLowerCase().slice(0, 32);
+ }
+ }
+ } catch {
+ // Malformed body — default to health mode.
+ }
+
+ const checkedAt = new Date().toISOString();
+
+ if (mode !== 'health') {
+ return { mode, session_created: false, latency_ms: null, slow: null, nonce_valid: null, domain: null, reason: 'unknown_mode', checked_at: checkedAt };
+ }
+
+ const probe = await probeNonce();
+ return {
+ mode,
+ session_created: probe.session_created,
+ latency_ms: probe.latency_ms,
+ slow: probe.slow,
+ nonce_valid: probe.nonce_valid,
+ domain: probe.domain,
+ reason: probe.reason,
+ checked_at: checkedAt,
+ };
+ },
+});
diff --git a/tests/api/x402-pump-trending-score.test.js b/tests/api/x402-pump-trending-score.test.js
new file mode 100644
index 000000000..29640be96
--- /dev/null
+++ b/tests/api/x402-pump-trending-score.test.js
@@ -0,0 +1,253 @@
+/**
+ * Unit tests for the pump_trending score engine (pump-trending-score.js)
+ * and the extractSignal shape used by the autonomous registry entry
+ * `crypto-intel-pump-trending` (USE-047).
+ *
+ * Pure helpers (scorePressure, buildPumpTrendingSignal) are tested without
+ * any network calls. extractSignal is exercised against a real payload
+ * produced by buildPumpTrendingSignal to prove the registry entry correctly
+ * lifts the actionable fields into oracle_intel_signals.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ scorePressure,
+ buildPumpTrendingSignal,
+ WHALE_SOL_THRESHOLD,
+} from '../../api/_lib/x402/pump-trending-score.js';
+
+// Mirror the inline extractSignal from the autonomous registry entry for
+// crypto-intel-pump-trending (id: 'crypto-intel-pump-trending').
+// Any change to extractSignal in autonomous-registry.js must be reflected here.
+function extractSignal(r) {
+ return {
+ topic: 'pump_trending',
+ signal: r?.signal ?? null,
+ headline: r?.headline ?? null,
+ confidence: r?.confidence ?? null,
+ buy_pressure: r?.buy_pressure ?? null,
+ total_volume_sol: r?.total_volume_sol ?? null,
+ whale_buy_count: r?.whale_buy_count ?? 0,
+ top_mint: r?.top_mint ?? null,
+ trending_mints: Array.isArray(r?.trending_mints) ? r.trending_mints.slice(0, 5) : [],
+ whale_buys: Array.isArray(r?.whale_buys) ? r.whale_buys.slice(0, 5) : [],
+ };
+}
+
+// ── helpers ───────────────────────────────────────────────────────────────────
+
+function makeMint(i) {
+ return 'M'.repeat(32) + String(i).padStart(12, '0');
+}
+
+function makeCoin(i) {
+ return {
+ mint: makeMint(i),
+ symbol: `TOK${i}`,
+ name: `Token ${i}`,
+ market_cap_usd: 1_000_000 * (10 - i),
+ market_cap_sol: 10_000 * (10 - i),
+ rank: i + 1,
+ complete: false,
+ };
+}
+
+function makeTrade({ type = 'buy', amountSol = 1 } = {}) {
+ return { type, amountSol, amountUsd: amountSol * 150, userAddress: 'TRADER' };
+}
+
+// ── scorePressure ─────────────────────────────────────────────────────────────
+
+describe('scorePressure', () => {
+ it('counts buys and sells correctly', () => {
+ const coinTrades = [
+ {
+ mint: makeMint(0),
+ trades: [makeTrade({ type: 'buy' }), makeTrade({ type: 'sell' }), makeTrade({ type: 'buy' })],
+ },
+ ];
+ const s = scorePressure(coinTrades);
+ expect(s.totalBuys).toBe(2);
+ expect(s.totalSells).toBe(1);
+ expect(s.buyPressure).toBeCloseTo(2 / 3);
+ });
+
+ it('detects whale buys at or above the threshold', () => {
+ const mint = makeMint(0);
+ const coinTrades = [
+ {
+ mint,
+ trades: [
+ makeTrade({ type: 'buy', amountSol: WHALE_SOL_THRESHOLD }),
+ makeTrade({ type: 'buy', amountSol: WHALE_SOL_THRESHOLD - 0.1 }),
+ makeTrade({ type: 'buy', amountSol: WHALE_SOL_THRESHOLD + 10 }),
+ ],
+ },
+ ];
+ const s = scorePressure(coinTrades);
+ expect(s.whaleBuys).toHaveLength(2);
+ expect(s.whaleBuys.every((w) => w.mint === mint)).toBe(true);
+ expect(s.whaleBuys.every((w) => w.sol_amount >= WHALE_SOL_THRESHOLD)).toBe(true);
+ });
+
+ it('does not count sells as whale buys', () => {
+ const coinTrades = [
+ {
+ mint: makeMint(0),
+ trades: [makeTrade({ type: 'sell', amountSol: WHALE_SOL_THRESHOLD + 100 })],
+ },
+ ];
+ const s = scorePressure(coinTrades);
+ expect(s.whaleBuys).toHaveLength(0);
+ expect(s.totalBuys).toBe(0);
+ });
+
+ it('handles empty trade lists without throwing', () => {
+ const s = scorePressure([{ mint: makeMint(0), trades: [] }]);
+ expect(s.buyPressure).toBe(0.5);
+ expect(s.totalVolumeSol).toBe(0);
+ expect(s.whaleBuys).toHaveLength(0);
+ });
+
+ it('sums volume across multiple coins', () => {
+ const coinTrades = [
+ { mint: makeMint(0), trades: [makeTrade({ type: 'buy', amountSol: 3 })] },
+ { mint: makeMint(1), trades: [makeTrade({ type: 'buy', amountSol: 7 })] },
+ ];
+ const s = scorePressure(coinTrades);
+ expect(s.totalVolumeSol).toBeCloseTo(10);
+ expect(s.totalBuys).toBe(2);
+ });
+});
+
+// ── buildPumpTrendingSignal ───────────────────────────────────────────────────
+
+describe('buildPumpTrendingSignal', () => {
+ const COINS = Array.from({ length: 10 }, (_, i) => makeCoin(i));
+
+ it('returns bullish signal when buy pressure >= 65%', () => {
+ const score = { totalBuys: 13, totalSells: 7, buyPressure: 0.65, totalVolumeSol: 20, whaleBuys: [] };
+ const r = buildPumpTrendingSignal(COINS, score);
+ expect(r.signal).toBe('bullish');
+ expect(r.topic).toBe('pump_trending');
+ expect(r.confidence).toBeGreaterThan(0.55);
+ });
+
+ it('returns bearish signal when buy pressure <= 40%', () => {
+ const score = { totalBuys: 4, totalSells: 6, buyPressure: 0.40, totalVolumeSol: 10, whaleBuys: [] };
+ const r = buildPumpTrendingSignal(COINS, score);
+ expect(r.signal).toBe('bearish');
+ });
+
+ it('returns neutral signal for balanced flow', () => {
+ const score = { totalBuys: 10, totalSells: 10, buyPressure: 0.50, totalVolumeSol: 10, whaleBuys: [] };
+ const r = buildPumpTrendingSignal(COINS, score);
+ expect(r.signal).toBe('neutral');
+ });
+
+ it('includes trending_mints (up to 10), top_mint, and whale_buys', () => {
+ const whale = { mint: makeMint(0), sol_amount: 10, usd_amount: 1500, trader: 'WHALE' };
+ const score = { totalBuys: 8, totalSells: 2, buyPressure: 0.8, totalVolumeSol: 50, whaleBuys: [whale] };
+ const r = buildPumpTrendingSignal(COINS, score);
+ expect(r.trending_mints).toHaveLength(10);
+ expect(r.top_mint).toBe(COINS[0].mint);
+ expect(r.whale_buys).toHaveLength(1);
+ expect(r.whale_buy_count).toBe(1);
+ expect(r.buy_pressure).toBeCloseTo(0.8);
+ expect(r.total_volume_sol).toBeCloseTo(50);
+ });
+
+ it('caps confidence at 0.92 regardless of buy pressure extremity', () => {
+ const score = { totalBuys: 100, totalSells: 0, buyPressure: 1.0, totalVolumeSol: 100, whaleBuys: [] };
+ const r = buildPumpTrendingSignal(COINS, score);
+ expect(r.confidence).toBeLessThanOrEqual(0.92);
+ });
+
+ it('includes ts as an ISO date string', () => {
+ const score = { totalBuys: 5, totalSells: 5, buyPressure: 0.5, totalVolumeSol: 0, whaleBuys: [] };
+ const r = buildPumpTrendingSignal(COINS, score);
+ expect(typeof r.ts).toBe('string');
+ expect(() => new Date(r.ts)).not.toThrow();
+ });
+});
+
+// ── extractSignal (registry entry shape) ────────────────────────────────────
+
+describe('extractSignal — pump_trending registry entry', () => {
+ const COINS = Array.from({ length: 12 }, (_, i) => makeCoin(i));
+ const BULLISH_SCORE = {
+ totalBuys: 14, totalSells: 6, buyPressure: 0.7,
+ totalVolumeSol: 42, whaleBuys: [
+ { mint: makeMint(0), sol_amount: 8, usd_amount: 1200, trader: 'W1' },
+ { mint: makeMint(1), sol_amount: 6, usd_amount: 900, trader: 'W2' },
+ { mint: makeMint(2), sol_amount: 5, usd_amount: 750, trader: 'W3' },
+ { mint: makeMint(3), sol_amount: 5, usd_amount: 750, trader: 'W4' },
+ { mint: makeMint(4), sol_amount: 7, usd_amount: 1050, trader: 'W5' },
+ { mint: makeMint(5), sol_amount: 9, usd_amount: 1350, trader: 'W6' }, // 6 whales total
+ ],
+ };
+
+ it('extracts all required oracle signal fields from a real payload', () => {
+ const payload = buildPumpTrendingSignal(COINS, BULLISH_SCORE);
+ const sig = extractSignal(payload);
+
+ expect(sig.topic).toBe('pump_trending');
+ expect(['bullish', 'bearish', 'neutral']).toContain(sig.signal);
+ expect(typeof sig.headline).toBe('string');
+ expect(sig.confidence).toBeGreaterThan(0);
+ expect(sig.confidence).toBeLessThanOrEqual(1);
+ expect(typeof sig.buy_pressure).toBe('number');
+ expect(typeof sig.total_volume_sol).toBe('number');
+ expect(typeof sig.whale_buy_count).toBe('number');
+ expect(typeof sig.top_mint).toBe('string');
+ });
+
+ it('caps trending_mints at 5 even when the payload has 10', () => {
+ const payload = buildPumpTrendingSignal(COINS, BULLISH_SCORE);
+ expect(payload.trending_mints).toHaveLength(10); // raw payload has 10
+ const sig = extractSignal(payload);
+ expect(sig.trending_mints).toHaveLength(5); // registry caps at 5
+ });
+
+ it('caps whale_buys at 5 even when the payload has 6', () => {
+ const payload = buildPumpTrendingSignal(COINS, BULLISH_SCORE);
+ expect(payload.whale_buys).toHaveLength(6); // raw payload kept all 6 (≤10)
+ const sig = extractSignal(payload);
+ expect(sig.whale_buys).toHaveLength(5); // registry caps at 5
+ });
+
+ it('returns zero whale_buy_count and empty arrays on a null response', () => {
+ const sig = extractSignal(null);
+ expect(sig.topic).toBe('pump_trending');
+ expect(sig.signal).toBeNull();
+ expect(sig.headline).toBeNull();
+ expect(sig.confidence).toBeNull();
+ expect(sig.buy_pressure).toBeNull();
+ expect(sig.total_volume_sol).toBeNull();
+ expect(sig.whale_buy_count).toBe(0);
+ expect(sig.top_mint).toBeNull();
+ expect(sig.trending_mints).toEqual([]);
+ expect(sig.whale_buys).toEqual([]);
+ });
+
+ it('returns zero whale_buy_count when payload has none', () => {
+ const score = { totalBuys: 5, totalSells: 5, buyPressure: 0.5, totalVolumeSol: 5, whaleBuys: [] };
+ const payload = buildPumpTrendingSignal(COINS.slice(0, 5), score);
+ const sig = extractSignal(payload);
+ expect(sig.whale_buy_count).toBe(0);
+ expect(sig.whale_buys).toHaveLength(0);
+ });
+
+ it('trending_mints entries have mint, symbol, name, market_cap_usd, rank fields', () => {
+ const score = { totalBuys: 7, totalSells: 3, buyPressure: 0.7, totalVolumeSol: 10, whaleBuys: [] };
+ const payload = buildPumpTrendingSignal(COINS, score);
+ const sig = extractSignal(payload);
+ for (const m of sig.trending_mints) {
+ expect(typeof m.mint).toBe('string');
+ expect(typeof m.symbol).toBe('string');
+ expect(typeof m.name).toBe('string');
+ expect(typeof m.market_cap_usd).toBe('number');
+ expect(typeof m.rank).toBe('number');
+ }
+ });
+});