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.

x402 pay/intel hardening, agent-trade guards, communities + bounties polish, changelog regen

nirholasc72e1aa2d4bc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bcf178aa4..5db8b0137 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-19
- **AR & half-body avatar export fixed for compressed models** — View-in-AR (USDZ for iOS Quick Look) and the half-body VR-seat export now work for avatars that ship with meshopt or Draco geometry compression. Previously these exports silently failed on compressed GLBs because the loader had no decoder registered; the pipeline now loads the meshopt and Draco decoders before parsing, so every avatar — including the compressed ones produced by the server-side bake — converts cleanly. (`/gallery`) `[fix]`
+- **IBM sites can now embed three.ws pages** — We extended the sitewide clickjacking protection to allow IBM properties to frame three.ws. Any page on ibm.com (and its subdomains) may now load three.ws pages inside an iframe — useful for the IBM x402 demo and other IBM-hosted integrations — while every other external site is still refused by default. Sign-in, wallet, dashboard and OAuth consent pages remain hard-locked and cannot be framed by anyone, including IBM. The avatar, widget and walk embeds continue to work on any site as before. `[security, improvement]`
## 2026-06-18
diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.js
index 48f627be7..6619eb195 100644
--- a/api/_lib/agent-trade-guards.js
+++ b/api/_lib/agent-trade-guards.js
@@ -484,6 +484,123 @@ export async function enforceSpendLimit({
return { ok: true, limits: lim, dailySpentUsd };
}
+/**
+ * Atomically enforce the per-agent USD spend policy AND reserve a pending custody
+ * row, under a per-agent advisory lock. This closes the TOCTOU that
+ * `enforceSpendLimit` + a post-settle `recordSpend` leaves open: without the lock,
+ * K concurrent calls all read the same pre-spend 24h total, all pass the daily
+ * ceiling, and all settle — turning a $X/day cap into $X·K. Mirrors the proven
+ * `reserveSpend` pattern in agent-spend-policy.js (which already protects the SOL
+ * outflow path).
+ *
+ * Returns { ok: true, reservationId, dailySpentUsd } on success — finalize the
+ * reservation with `updateCustodyEvent(reservationId, { status, signature })` after
+ * settlement, or `releaseSpendReservation(reservationId)` if the spend never moved.
+ * @throws {SpendLimitError} on per-tx breach, daily breach, or withdraw-allowlist miss.
+ */
+export async function reserveSpendUsd({
+ agentId,
+ userId,
+ meta,
+ limits,
+ category,
+ usdValue,
+ destination,
+ network = 'mainnet',
+ asset = 'USDC',
+ rowMeta = {},
+}) {
+ const lim = limits || getSpendLimits(meta);
+
+ // Withdraw allowlist — destination gate (same as enforceSpendLimit).
+ if (category === 'withdraw' && lim.withdraw_allowlist.length > 0) {
+ const dest = typeof destination === 'string' ? destination.trim() : '';
+ if (!dest || !lim.withdraw_allowlist.includes(dest)) {
+ throw new SpendLimitError(
+ 'destination_not_allowed',
+ 'That destination is not on this agent’s withdraw allowlist. Add it under Limits & Safety, or send to an allowed address.',
+ { destination: dest || null, allowlist_size: lim.withdraw_allowlist.length },
+ );
+ }
+ }
+
+ const hasUsd = typeof usdValue === 'number' && Number.isFinite(usdValue) && usdValue >= 0;
+
+ // Per-transaction ceiling (no lock needed — a single value vs a constant).
+ if (lim.per_tx_usd != null && hasUsd && usdValue > lim.per_tx_usd + 1e-9) {
+ throw new SpendLimitError(
+ 'per_tx_exceeded',
+ `This ${category} is $${usdValue.toFixed(2)}, over the per-transaction limit of $${lim.per_tx_usd.toFixed(2)}.`,
+ { usd: usdValue, per_tx_usd: lim.per_tx_usd },
+ );
+ }
+
+ const metaJson = JSON.stringify(rowMeta ?? {});
+
+ // No daily ceiling, or an unpriceable spend: just reserve a pending row (it
+ // can't gate a cap it has no number for) so the ledger still reflects it.
+ if (lim.daily_usd == null || !hasUsd) {
+ const reservationId = await recordCustodyEvent({
+ agentId, userId, eventType: 'spend', category, network, asset,
+ usd: hasUsd ? usdValue : null, destination, status: 'pending', meta: rowMeta,
+ });
+ return { ok: true, reservationId, dailySpentUsd: null };
+ }
+
+ // Atomic daily-cap reserve: the advisory xact lock serializes concurrent spends
+ // per agent, and the INSERT…SELECT only materializes the pending row when the
+ // rolling 24h total plus this spend stays within the cap — check + reserve are
+ // one statement, so two requests can never both pass on the same stale total.
+ const rows = await sql`
+ WITH locked AS (
+ SELECT pg_advisory_xact_lock(hashtextextended(${String(agentId)}, 0))
+ ),
+ spent AS (
+ SELECT COALESCE(SUM(usd), 0)::float8 AS s
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId}
+ AND network = ${network}
+ AND event_type = 'spend'
+ AND status IN ('ok', 'pending', 'confirmed')
+ AND usd IS NOT NULL
+ AND created_at > now() - interval '24 hours'
+ )
+ INSERT INTO agent_custody_events
+ (agent_id, user_id, event_type, category, network, asset, usd, destination, status, meta)
+ SELECT ${agentId}, ${userId ?? null}, 'spend', ${category}, ${network}, ${asset},
+ ${usdValue}, ${destination ?? null}, 'pending', ${metaJson}::jsonb
+ FROM spent, locked
+ WHERE spent.s + ${usdValue}::float8 <= ${lim.daily_usd}::float8 + 1e-9
+ RETURNING id, (SELECT s FROM spent) AS spent_before
+ `;
+
+ if (!rows.length) {
+ // Re-read the total for an accurate error message (outside the lock is fine).
+ const dailySpentUsd = await getDailySpendUsd(agentId, network);
+ throw new SpendLimitError(
+ 'daily_exceeded',
+ `This ${category} would bring today’s spend to $${(dailySpentUsd + usdValue).toFixed(2)}, over the daily limit of $${lim.daily_usd.toFixed(2)}.`,
+ { usd: usdValue, spent_usd: dailySpentUsd, daily_usd: lim.daily_usd },
+ );
+ }
+
+ return { ok: true, reservationId: rows[0].id, dailySpentUsd: Number(rows[0].spent_before || 0) };
+}
+
+/**
+ * Release a USD spend reservation that never resulted in a settled payment, so it
+ * stops counting toward the daily cap. Marks the pending row 'failed' rather than
+ * deleting it, preserving the audit trail.
+ */
+export async function releaseSpendReservation(reservationId, reason = 'spend_aborted') {
+ if (!reservationId) return;
+ await sql`
+ UPDATE agent_custody_events
+ SET status = 'failed', reason = ${reason}, updated_at = now()
+ WHERE id = ${reservationId} AND status = 'pending'
+ `;
+}
+
const CUSTODY_COLUMNS = [
'agent_id', 'user_id', 'event_type', 'category', 'network', 'asset',
'amount_lamports', 'amount_raw', 'usd', 'destination', 'signature',
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index 37d6d6d0f..c6c355adb 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -55,9 +55,12 @@ import {
hashPaymentProof,
hashRequestPayload,
paymentIdentifierExtension,
+ reserveSlot,
+ releaseSlot,
storeResponse,
writeCachedResponse,
writeConflict,
+ writeInflight,
} from './x402/payment-identifier-server.js';
import { authenticateSiwx, declareSiwxExtensionFor, recordSiwxPayment } from './siwx-server.js';
import { normalizeAddress } from './siwx-storage.js';
@@ -667,6 +670,10 @@ export function paidEndpoint(spec) {
// transient verify/settle failure never locks a legitimate payer out of
// retrying the same payment.
const paymentId = clientPaymentId || (paymentHash ? `proof:${paymentHash}` : null);
+ // Track whether THIS request owns the in-flight reservation, so we only
+ // release it on a failure path (never delete another request's slot or a
+ // stored response).
+ let ownsReservation = false;
if (paymentId) {
const lookup = await checkCache({ route, paymentId, payloadHash, paymentHash });
if (lookup.kind === 'hit') {
@@ -680,12 +687,36 @@ export function paidEndpoint(spec) {
reason: lookup.reason,
});
}
+ if (lookup.kind === 'inflight') {
+ return writeInflight(res);
+ }
+ // Atomically claim the slot. The check above + the deferred storeResponse
+ // (written only AFTER settle) left a window where N concurrent requests
+ // carrying the same X-PAYMENT all missed the cache, all ran the paid
+ // handler (side effects) and all settled before the first response was
+ // stored. The NX reservation closes it: only the winner proceeds; the rest
+ // observe the in-flight marker (or, once it finishes, the cached response).
+ ownsReservation = await reserveSlot({ route, paymentId, ttlSeconds: pidTtlSeconds });
+ if (!ownsReservation) {
+ const recheck = await checkCache({ route, paymentId, payloadHash, paymentHash });
+ if (recheck.kind === 'hit') return writeCachedResponse(res, recheck.entry);
+ if (recheck.kind === 'conflict') {
+ return writeConflict(res, {
+ route,
+ attemptedHash: recheck.attemptedHash,
+ existingHash: recheck.existingHash,
+ reason: recheck.reason,
+ });
+ }
+ return writeInflight(res);
+ }
}
let verified;
try {
verified = await verifyPayment({ paymentHeader, requirements, builderCode });
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route, paymentId });
if (err.status === 402) return send402(res, { ...challenge, error: err.message });
return respondError(res, err.status || 502, err.code || 'verify_failed', err);
}
@@ -699,6 +730,7 @@ export function paidEndpoint(spec) {
payer: verified.payer,
});
} catch (err) {
+ if (ownsReservation) await releaseSlot({ route, paymentId });
if (err instanceof X402Error && err.status === 402) {
return send402(res, { ...challenge, error: err.message });
}
@@ -706,8 +738,13 @@ export function paidEndpoint(spec) {
}
// Handler may end the response itself (e.g. binary body); only settle +
- // emit JSON when it returned a value and didn't already flush.
- if (res.writableEnded) return;
+ // emit JSON when it returned a value and didn't already flush. This path
+ // stores no cache entry, so release the in-flight reservation rather than
+ // leaving a marker that would wedge same-payment retries for the full TTL.
+ if (res.writableEnded) {
+ if (ownsReservation) await releaseSlot({ route, paymentId });
+ return;
+ }
let settled;
try {
@@ -727,6 +764,7 @@ export function paidEndpoint(spec) {
userAgent: req.headers?.['user-agent']?.slice(0, 512) || null,
metadata: { error: err.message, code: err.code },
});
+ if (ownsReservation) await releaseSlot({ route, paymentId });
return respondError(res, err.status || 502, err.code || 'settle_failed', err);
}
diff --git a/api/_lib/x402.js b/api/_lib/x402.js
index 9232abe9e..8b77aff3f 100644
--- a/api/_lib/x402.js
+++ b/api/_lib/x402.js
@@ -186,8 +186,23 @@ export async function consumeIntent(intentId) {
*/
export async function manifestOnly(res, opts) {
const validUntil = Math.floor(Date.now() / 1000) + (opts.validForSec || 900);
- const payments = opts.agent.meta?.payments || opts.agent.payments;
- const { recipient, recipient_name } = await resolveRecipient({ agent: opts.agent, payments });
+
+ // Prefer an explicit payout `recipient` (resolved from agent_payout_wallets /
+ // the agent's own wallet_address by the caller). Only when none is supplied do
+ // we fall back to resolving the agent's configured meta receiver via SNS — this
+ // keeps pre-payout-wallet agents working unchanged.
+ let recipient = opts.recipient ?? null;
+ let recipient_name = null;
+ if (recipient) {
+ const metaName = opts.agent.meta?.sns_domain || null;
+ recipient_name = metaName
+ ? (metaName.endsWith('.sol') ? metaName : `${metaName}.sol`)
+ : null;
+ } else {
+ const payments = opts.agent.meta?.payments || opts.agent.payments;
+ ({ recipient, recipient_name } = await resolveRecipient({ agent: opts.agent, payments }));
+ }
+
return json(res, 200, {
version: X402_VERSION,
kind: 'agent-skill',
@@ -195,6 +210,7 @@ export async function manifestOnly(res, opts) {
skill: opts.skill,
amount: String(opts.amount),
currency: opts.currency,
+ chain: opts.chain ?? 'solana',
recipient,
recipient_name,
valid_until: validUntil,
diff --git a/api/_lib/x402/payment-identifier-server.js b/api/_lib/x402/payment-identifier-server.js
index 59192960f..eacbd6a53 100644
--- a/api/_lib/x402/payment-identifier-server.js
+++ b/api/_lib/x402/payment-identifier-server.js
@@ -222,5 +222,23 @@ export function writeConflict(res, { route, attemptedHash, existingHash, reason
);
}
+// Write a 409 telling a concurrent caller the same payment is already being
+// processed. Retry-After:1 nudges well-behaved clients to poll for the cached
+// response rather than re-submitting (which would conflict on the proof hash).
+export function writeInflight(res) {
+ res.statusCode = 409;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('x-x402-idempotent', 'in-flight');
+ res.setHeader('retry-after', '1');
+ res.end(
+ JSON.stringify({
+ error: 'payment_in_flight',
+ error_description:
+ 'a request with this payment is already being processed; retry shortly to receive the cached response',
+ }),
+ );
+}
+
export { hashRequestPayload, hashPaymentProof } from './idempotency-cache.js';
export const ttlSeconds = envTtl;
diff --git a/api/agents/by-address/[addr].js b/api/agents/by-address/[addr].js
index f8521e275..357f2a90a 100644
--- a/api/agents/by-address/[addr].js
+++ b/api/agents/by-address/[addr].js
@@ -62,7 +62,7 @@ async function queryChain(addr, chainId, meta) {
try {
provider = await evmFallbackProvider(chainId, { primaryUrl: meta.rpc });
} catch {
- return [];
+ return { agents: [], truncated: false };
}
const registry = new Contract(meta.registry, ENUM_ABI, provider);
@@ -70,13 +70,18 @@ async function queryChain(addr, chainId, meta) {
try {
count = Number(await withTimeout(registry.balanceOf(addr), RPC_TIMEOUT));
} catch {
- return [];
+ return { agents: [], truncated: false };
}
- if (count === 0) return [];
+ if (count === 0) return { agents: [], truncated: false };
+
+ // Cap enumeration so one wallet with a huge balance can't fan a single HTTP
+ // request into thousands of upstream RPC calls (DoS / Helius-burn).
+ const enumCount = Math.min(count, MAX_ENUM);
+ const truncated = count > MAX_ENUM;
const agentIds = await Promise.all(
- Array.from({ length: count }, (_, i) =>
+ Array.from({ length: enumCount }, (_, i) =>
withTimeout(registry.tokenOfOwnerByIndex(addr, BigInt(i)), RPC_TIMEOUT).catch(
() => null,
),
@@ -102,7 +107,7 @@ async function queryChain(addr, chainId, meta) {
});
}
- return results;
+ return { agents: results, truncated };
}
export default wrap(async (req, res) => {
@@ -166,7 +171,8 @@ export default wrap(async (req, res) => {
chains.map(({ id, meta }) => queryChain(raw, id, meta)),
);
- const agents = settled.flatMap((r) => (r.status === 'fulfilled' ? r.value : []));
+ const agents = settled.flatMap((r) => (r.status === 'fulfilled' ? r.value.agents : []));
+ const truncated = settled.some((r) => r.status === 'fulfilled' && r.value.truncated);
cacheSet(cacheKey, agents);
- return json(res, 200, { agents });
+ return json(res, 200, { agents, truncated });
});
diff --git a/api/agents/talk.js b/api/agents/talk.js
index 49ec891f9..f6b291891 100644
--- a/api/agents/talk.js
+++ b/api/agents/talk.js
@@ -29,7 +29,6 @@ const ALLOWED_MODELS = new Set([
'claude-sonnet-4-5',
'claude-sonnet-4-6',
'claude-opus-4-7',
- 'claude-3-5-haiku-20241022',
]);
const bodySchema = z.object({
diff --git a/api/agents/x402/[action].js b/api/agents/x402/[action].js
index 134175627..cccfac409 100644
--- a/api/agents/x402/[action].js
+++ b/api/agents/x402/[action].js
@@ -7,6 +7,7 @@ import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_l
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { parse, isUuid } from '../../_lib/validate.js';
import { emit402, verifyPaid, consumeIntent, manifestOnly } from '../../_lib/x402.js';
+import { resolvePayoutAddress } from '../../_lib/payout.js';
import { calculateFee } from '../../_lib/fee.js';
import { insertNotification } from '../../_lib/notify.js';
import { hasSkillAccess, consumeTrialUse, logSkillUsage } from '../../_lib/skill-access.js';
@@ -40,11 +41,22 @@ async function priceFor(agent, skill) {
`;
if (row) return { amount: String(row.amount), currency: row.currency_mint, chain: row.chain };
+ return metaPrice(agent, skill);
+}
+
+// Legacy pricing: agents priced via meta.skill_prices (or a meta default) before
+// the agent_skill_prices marketplace migration. Both invoke and manifest fall
+// back to this so pre-migration agents keep working.
+function metaPrice(agent, skill) {
const prices = agent.meta?.skill_prices || {};
const fromMap = prices[skill];
- if (fromMap?.amount && fromMap?.currency) return fromMap;
+ if (fromMap?.amount && fromMap?.currency) {
+ return { amount: String(fromMap.amount), currency: fromMap.currency, chain: fromMap.chain ?? 'solana' };
+ }
const defaultPrice = agent.meta?.payments?.default_price;
- if (defaultPrice?.amount && defaultPrice?.currency) return defaultPrice;
+ if (defaultPrice?.amount && defaultPrice?.currency) {
+ return { amount: String(defaultPrice.amount), currency: defaultPrice.currency, chain: defaultPrice.chain ?? 'solana' };
+ }
return null;
}
@@ -235,24 +247,43 @@ async function handleManifest(req, res) {
await sql`select id, name, meta from agent_identities where id = ${agent_id} and deleted_at is null limit 1`;
if (!agent) return error(res, 404, 'not_found', 'agent not found');
- // Manifest is callable as long as the skill is priced — either in the
- // canonical agent_skill_prices table or the legacy meta.skill_prices map.
- const [hasMarketplacePrice] = await sql`
- SELECT 1 FROM agent_skill_prices WHERE agent_id = ${agent.id} AND skill = ${skill} AND is_active = true
+ // Canonical pricing lives in agent_skill_prices. Fetch the row regardless of
+ // is_active so we can distinguish "deactivated" (skill_not_available) from
+ // "never priced" (skill_not_priced).
+ const [priceRow] = await sql`
+ SELECT amount, currency_mint, chain, is_active
+ FROM agent_skill_prices
+ WHERE agent_id = ${agent.id} AND skill = ${skill}
`;
- const hasMetaPrice = !!(
- agent.meta?.skill_prices?.[skill] || agent.meta?.payments?.default_price
- );
- if (!hasMarketplacePrice && !hasMetaPrice) {
- return error(res, 409, 'no_payments', 'this skill is not priced');
- }
- const price = await priceFor(agent, skill);
- if (!price) {
- // Defensive — the no-payments precheck above should have caught this.
- return error(res, 409, 'no_payments', 'this skill is not priced');
+ let price;
+ if (priceRow) {
+ if (!priceRow.is_active) {
+ return error(res, 404, 'skill_not_available', 'this skill is not currently available');
+ }
+ price = { amount: String(priceRow.amount), currency: priceRow.currency_mint, chain: priceRow.chain };
+ } else {
+ // Legacy meta-priced agents predate the marketplace table. The invoke path
+ // still honors them, so the manifest must surface them too.
+ price = metaPrice(agent, skill);
+ if (!price) {
+ return error(res, 404, 'skill_not_priced', 'this skill is not priced');
+ }
}
- return manifestOnly(res, { agent, skill, amount: price.amount, currency: price.currency });
+
+ // payTo resolves from the owner's configured payout wallet for this chain
+ // (agent_payout_wallets), falling back to the agent's own wallet_address.
+ // When neither is set, manifestOnly falls back to the agent's meta receiver.
+ const recipient = await resolvePayoutAddress(agent.id, price.chain || 'solana');
+
+ return manifestOnly(res, {
+ agent,
+ skill,
+ amount: price.amount,
+ currency: price.currency,
+ chain: price.chain,
+ recipient,
+ });
}
// ── dispatcher ────────────────────────────────────────────────────────────────
diff --git a/api/brain/chat.js b/api/brain/chat.js
index 6bf7b61c7..43a624bf6 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -99,7 +99,7 @@ const PROVIDERS = {
maxOutput: 8192,
description: 'Fastest Claude. Low latency, high throughput.',
native: () => (env.ANTHROPIC_API_KEY ? createAnthropic({ apiKey: env.ANTHROPIC_API_KEY })('claude-haiku-4-5-20251001') : null),
- openrouterModel: 'anthropic/claude-3.5-haiku',
+ openrouterModel: 'anthropic/claude-haiku-4.5',
},
'gpt-4o': {
label: 'GPT-4o',
diff --git a/api/oracle/follow.js b/api/oracle/follow.js
index 5141b8e9e..cb709b20d 100644
--- a/api/oracle/follow.js
+++ b/api/oracle/follow.js
@@ -36,7 +36,11 @@ export default wrap(async (req, res) => {
const ip = clientIp(req);
// ── GET — check follow status ─────────────────────────────────────────────
- if (method(req, res, ['GET'], { silent: true })) {
+ // Branch on req.method directly: the shared method() helper writes a 405 and
+ // ends the response on the first mismatch, so calling it per-branch (GET first)
+ // would 405 every POST/DELETE before its branch was reached. A single trailing
+ // 405 below covers unsupported verbs.
+ if (req.method === 'GET' || req.method === 'HEAD') {
const rl = await limits.publicIp(ip);
if (!rl.success) return rateLimited(res, rl);
@@ -61,12 +65,12 @@ export default wrap(async (req, res) => {
}
// ── POST — subscribe or update ────────────────────────────────────────────
- if (method(req, res, ['POST'], { silent: true })) {
+ if (req.method === 'POST') {
const rl = await limits.oracleFollowIp(ip);
if (!rl.success) return rateLimited(res, rl);
- const body = await readJson(req, res);
- if (!body) return;
+ const body = await readJson(req).catch(() => null);
+ if (!body) return error(res, 400, 'invalid_json', 'request body must be valid JSON');
const agentId = (body.agent_id || '').trim();
const chatId = (body.chat_id || '').trim();
@@ -106,12 +110,12 @@ export default wrap(async (req, res) => {
}
// ── DELETE — unsubscribe ──────────────────────────────────────────────────
- if (method(req, res, ['DELETE'], { silent: true })) {
+ if (req.method === 'DELETE') {
const rl = await limits.publicIp(ip);
if (!rl.success) return rateLimited(res, rl);
- const body = await readJson(req, res);
- if (!body) return;
+ const body = await readJson(req).catch(() => null);
+ if (!body) return error(res, 400, 'invalid_json', 'request body must be valid JSON');
const agentId = (body.agent_id || '').trim();
const chatId = (body.chat_id || '').trim();
diff --git a/api/users/[username].js b/api/users/[username].js
index fb6fdecd2..939ee576f 100644
--- a/api/users/[username].js
+++ b/api/users/[username].js
@@ -16,7 +16,7 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
const [user] = await sql`
- select id, display_name, username, created_at, referral_code, wallet_address
+ select id, display_name, username, created_at, wallet_address
from users
where lower(username) = ${username} and deleted_at is null
limit 1
@@ -269,7 +269,6 @@ export default wrap(async (req, res) => {
user: {
username: user.username,
display_name: user.display_name || user.username,
- referral_code: user.referral_code,
wallet_address: user.wallet_address,
created_at: user.created_at,
},
diff --git a/api/x402-pay.js b/api/x402-pay.js
index 540b06f3f..3653e4491 100644
--- a/api/x402-pay.js
+++ b/api/x402-pay.js
@@ -47,7 +47,7 @@ import { sql } from './_lib/db.js';
import { logger } from './_lib/usage.js';
import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
import { recoverSolanaAgentKeypair } from './_lib/agent-wallet.js';
-import { enforceSpendLimit, SpendLimitError, recordSpend } from './_lib/agent-trade-guards.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';
@@ -556,17 +556,24 @@ async function runExternalFlow({ url, method, body, emit, buyer, spendGuard, ser
});
// Per-agent spend policy — enforced BEFORE the payment is built/signed so a
- // breach moves no funds.
+ // breach moves no funds. reserveSpendUsd atomically checks the cap AND writes a
+ // pending ledger row under a per-agent lock, so concurrent calls can't all pass
+ // the same stale daily total and overspend the cap. Finalize/release below.
+ let spendReservationId = null;
if (spendGuard) {
try {
- await enforceSpendLimit({
+ const reservation = await reserveSpendUsd({
agentId: spendGuard.agentId,
+ userId: spendGuard.userId,
meta: spendGuard.meta,
category: 'x402',
usdValue: spendUsd,
destination: accept.payTo,
network: 'mainnet',
+ asset: 'USDC',
+ rowMeta: { url, service: serviceLabel || resource.serviceName || null, resource: resource.url },
});
+ spendReservationId = reservation.reservationId;
} catch (e) {
if (e instanceof SpendLimitError) {
throw Object.assign(new Error(e.message), { status: e.status, code: e.code, detail: e.detail });
@@ -600,6 +607,11 @@ async function runExternalFlow({ url, method, body, emit, buyer, spendGuard, ser
const paidJson = safeJsonParse(paid.text) ?? paid.text;
if (!paid.ok) {
if (paid.status === 402) {
+ // Explicit pre-settlement rejection: no funds moved, so release the
+ // reservation — it must not count toward the daily cap. (The
+ // settle_uncertain path below deliberately KEEPS the reservation:
+ // chain state is unknown, so we conservatively count it as spent.)
+ if (spendReservationId) await releaseSpendReservation(spendReservationId, 'payment_rejected_402');
throw Object.assign(
new Error('the service rejected the payment before settlement; no funds were transferred'),
{ status: 402, code: 'payment_required', detail: typeof paidJson === 'object' ? paidJson : null },
@@ -622,24 +634,14 @@ async function runExternalFlow({ url, method, body, emit, buyer, spendGuard, ser
explorer: tx ? `https://solscan.io/tx/${tx}` : null,
});
- // Record the agent's x402 spend into the shared custody ledger so it counts
- // toward the per-agent daily ceiling and shows in the wallet's payment activity.
- if (spendGuard) {
- void recordSpend({
- agentId: spendGuard.agentId,
- userId: spendGuard.userId,
- category: 'x402',
- network: 'mainnet',
- asset: 'USDC',
- usd: spendUsd,
- destination: accept.payTo,
- signature: tx,
+ // Finalize the pending reservation written before signing: flip it to
+ // confirmed/ok and attach the tx signature. It already counts toward the daily
+ // cap (written under the advisory lock), so this just records the outcome.
+ if (spendReservationId) {
+ void updateCustodyEvent(spendReservationId, {
status: tx ? 'confirmed' : 'ok',
- meta: {
- url,
- service: serviceLabel || resource.serviceName || null,
- resource: resource.url,
- },
+ signature: tx,
+ meta: { settledAt: new Date(tSettled).toISOString() },
}).catch((err) => log.warn('x402_external_spend_record_failed', { message: err?.message }));
}
@@ -712,16 +714,21 @@ async function runFlow({ tool, args, emit, buyer: buyerOverride, resourceUrl, sp
// breach moves no funds. USDC is dollar-denominated (6 decimals), so the
// payment amount converts straight to the USD ceiling unit.
const spendUsd = Number(accept.amount) / 1e6;
+ let spendReservationId = null;
if (spendGuard) {
try {
- await enforceSpendLimit({
+ const reservation = await reserveSpendUsd({
agentId: spendGuard.agentId,
+ userId: spendGuard.userId,
meta: spendGuard.meta,
category: 'x402',
usdValue: spendUsd,
destination: accept.payTo,
network: spendGuard.network || 'mainnet',
+ asset: 'USDC',
+ rowMeta: { tool },
});
+ spendReservationId = reservation.reservationId;
} catch (e) {
if (e instanceof SpendLimitError) {
throw Object.assign(new Error(e.message), { status: e.status, code: e.code, detail: e.detail });
@@ -756,6 +763,8 @@ async function runFlow({ tool, args, emit, buyer: buyerOverride, resourceUrl, sp
emit('dispatched', { dispatch_ms: tDispatched - tVerified });
if (rpcResp?.error) {
+ // Dispatch failed before settlement — no funds moved, release the reservation.
+ if (spendReservationId) await releaseSpendReservation(spendReservationId, 'mcp_dispatch_error');
throw Object.assign(
new Error(rpcResp.error.message || 'mcp_dispatch_error'),
{ status: 502, mcpError: rpcResp.error },
@@ -784,20 +793,12 @@ async function runFlow({ tool, args, emit, buyer: buyerOverride, resourceUrl, sp
void recordFeedEntry(feedEntry).catch((err) => {
log.warn('feed_record_failed', { tx: settled.transaction, message: err?.message });
});
- // Record the agent's x402 spend into the shared custody ledger so it counts
- // toward the per-agent daily ceiling and shows in the custody audit trail.
- if (spendGuard) {
- void recordSpend({
- agentId: spendGuard.agentId,
- userId: spendGuard.userId,
- category: 'x402',
- network: spendGuard.network || 'mainnet',
- asset: 'USDC',
- usd: spendUsd,
- destination: accept.payTo,
- signature: settled.transaction || null,
+ // Finalize the pending reservation written before signing: it already counts
+ // toward the daily cap (reserved under the advisory lock); attach the outcome.
+ if (spendReservationId) {
+ void updateCustodyEvent(spendReservationId, {
status: settled.transaction ? 'confirmed' : 'ok',
- meta: { tool },
+ signature: settled.transaction || null,
}).catch((err) => log.warn('x402_spend_record_failed', { message: err?.message }));
}
if (settled.transaction) {
diff --git a/api/x402/crypto-intel.js b/api/x402/crypto-intel.js
index d5241c142..0e31dbdd5 100644
--- a/api/x402/crypto-intel.js
+++ b/api/x402/crypto-intel.js
@@ -164,17 +164,13 @@ export default paidEndpoint({
try { live = await fetchLivePrice(coinId); } catch { /* offline fallback */ }
if (!live || live.change_24h == null) {
- return {
- topic,
- headline: `${topic.toUpperCase()} — live data unavailable, signal estimated`,
- signal: 'neutral',
- price_usd: null,
- change_24h: null,
- rationale: `CoinGecko rate-limited this request. ` +
- `Signal is estimated from trend memory; retry in 60 s for a live quote.`,
- confidence: 0.4,
- ts: new Date().toISOString(),
- };
+ // Paid endpoint — never charge for a fabricated signal. Throw so the
+ // paidEndpoint wrapper returns a 503 BEFORE settlement; the buyer is
+ // not charged and can retry once the live price feed recovers.
+ throw Object.assign(new Error(`live market data for ${topic} is temporarily unavailable`), {
+ status: 503,
+ code: 'data_unavailable',
+ });
}
const { signal, headline, rationale, confidence } = buildSignal(topic, live.price_usd, live.change_24h);
diff --git a/api/x402/three-intel.js b/api/x402/three-intel.js
index e632d6217..c9a44dfbd 100644
--- a/api/x402/three-intel.js
+++ b/api/x402/three-intel.js
@@ -154,22 +154,14 @@ export default paidEndpoint({
try { live = await fetchThreeMarket(mint); } catch { /* upstream hiccup */ }
if (!live || live.change_24h == null) {
- return {
- mint,
- symbol: 'THREE',
- price_usd: live?.price_usd ?? null,
- change_24h: null,
- market_cap_usd: live?.market_cap_usd ?? null,
- liquidity_usd: live?.liquidity_usd ?? null,
- volume_24h_usd: live?.volume_24h_usd ?? null,
- signal: 'neutral',
- headline: 'THREE — live data unavailable, signal estimated',
- rationale:
- 'DexScreener rate-limited this request. ' +
- 'Signal is estimated from trend memory; retry in 60 s for a live quote.',
- confidence: 0.4,
- ts: new Date().toISOString(),
- };
+ // Live data is unavailable (DexScreener hiccup/rate-limit). This is a
+ // paid endpoint — never charge for a fabricated signal. Throw so the
+ // paidEndpoint wrapper returns a 503 BEFORE settlement runs; the buyer
+ // is not charged and can retry once live data is back.
+ throw Object.assign(new Error('live THREE market data is temporarily unavailable'), {
+ status: 503,
+ code: 'data_unavailable',
+ });
}
const { signal, headline, rationale, confidence } = buildSignal(live);
diff --git a/data/changelog.json b/data/changelog.json
index 43f0f2af4..f12b7bb42 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$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-06-19",
+ "title": "IBM sites can now embed three.ws pages",
+ "summary": "We extended the sitewide clickjacking protection to allow IBM properties to frame three.ws. Any page on ibm.com (and its subdomains) may now load three.ws pages inside an iframe — useful for the IBM x402 demo and other IBM-hosted integrations — while every other external site is still refused by default. Sign-in, wallet, dashboard and OAuth consent pages remain hard-locked and cannot be framed by anyone, including IBM. The avatar, widget and walk embeds continue to work on any site as before.",
+ "tags": [
+ "security",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-19",
"title": "AR & half-body avatar export fixed for compressed models",
diff --git a/docs/audit/WIRING-UX-AUDIT-2026-06-18.md b/docs/audit/WIRING-UX-AUDIT-2026-06-18.md
index e01de8ea8..f3ba5a867 100644
--- a/docs/audit/WIRING-UX-AUDIT-2026-06-18.md
+++ b/docs/audit/WIRING-UX-AUDIT-2026-06-18.md
@@ -42,14 +42,18 @@ All items below are fixed in this pass unless marked otherwise.
### Missing / broken UI states ("every state is designed")
-| # | File | Issue | Fix |
+Several of these were **overstated by the audit pass** — verified against the
+real code, the surfaces already had error states. Each was checked; only genuine
+gaps were changed (verify-before-fix).
+
+| # | File | Verified reality | Action |
|---|---|---|---|
-| F7 | `src/agents-directory.js` | Primary discovery page renders blank grid on fetch failure | visible error + retry ✅ |
-| F8 | `src/leaderboard.js` | Blank board on first-load failure | explicit error state + retry ✅ |
-| F10 | `src/marketplace.js` | `loadPublicAvatars()` skeletons render forever on error | error state + flag flip ✅ |
-| F11 | `src/bounties.js` | Load-more pagination failures silent | inline error on load-more failure ✅ |
-| F12 | `src/communities.js` | Per-coin profile fetch fails silently | error message in coin-profile container ✅ |
-| F13 | `src/collection.js` | No error state for subscription/collection lists | error banner + retry ✅ |
+| F7 | `public/agents/boot.js` (consumer of `agents-directory.js`) | Already rendered an "Error loading agents" empty-state on failure, but it was **not actionable** (no retry) and stale error copy leaked into the next empty render | Added Retry button + restore default empty copy ✅ |
+| F8 | `src/leaderboard.js` | **Already correct** — first-load failure renders an error state with a Retry button (`lb-retry`, lines 184-192). Audit claim was wrong | No change (verified) ✅ |
+| F10 | `src/marketplace.js` | **Already correct** — `loadPublicAvatars()` flips the loaded flag and renders a retryable error state (lines 570-581). Audit claim was stale | No change (verified) ✅ |
+| F11 | `src/bounties.js` | Load-more failure swapped the button to a bare "Retry" with no explanation | Button now reads "Couldn't load more — tap to retry" ✅ |
+| F12 | `src/communities.js` + `pages/communities.html` | A network/5xx coin-profile failure showed "Coin not found", conflating error with a real 404 | Distinguish 5xx/network from 404; show "Couldn't load this coin" + Retry ✅ |
+| F13 | `src/collection.js` | Handled the `!ok` path, but a `Promise.all`/`.json()` **rejection** (offline) left skeletons rendering forever (no `.catch` on `load()`) | Wrapped network + parse in try/catch with shared retryable error helper ✅ |
### Backend boundary hardening
diff --git a/pages/communities.html b/pages/communities.html
index 96612d74e..bda9a120e 100644
--- a/pages/communities.html
+++ b/pages/communities.html
@@ -329,8 +329,9 @@
</div>
<div class="coin-profile-empty" id="coin-profile-empty" hidden>
- <p>That coin couldn't be found on pump.fun.</p>
+ <p id="coin-profile-empty-msg">That coin couldn't be found on pump.fun.</p>
<p class="coin-empty-sub" id="coin-profile-empty-mint"></p>
+ <button type="button" id="coin-profile-retry" class="ghost-btn" hidden style="margin-top:14px">Retry</button>
</div>
<div class="coin-profile-body" id="coin-profile-body" hidden>
diff --git a/public/changelog.json b/public/changelog.json
index ac3b7c0be..0ccdc22ad 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T00:01:31.490Z",
+ "generated_at": "2026-06-19T00:19:16.950Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -16,6 +16,17 @@
"fix"
]
},
+ {
+ "date": "2026-06-19",
+ "type": "update",
+ "title": "IBM sites can now embed three.ws pages",
+ "summary": "We extended the sitewide clickjacking protection to allow IBM properties to frame three.ws. Any page on ibm.com (and its subdomains) may now load three.ws pages inside an iframe — useful for the IBM x402 demo and other IBM-hosted integrations — while every other external site is still refused by default. Sign-in, wallet, dashboard and OAuth consent pages remain hard-locked and cannot be framed by anyone, including IBM. The avatar, widget and walk embeds continue to work on any site as before.",
+ "link": null,
+ "tags": [
+ "security",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-18",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 6483f1e67..7e831f6a4 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>fix</category>
<description>View-in-AR (USDZ for iOS Quick Look) and the half-body VR-seat export now work for avatars that ship with meshopt or Draco geometry compression. Previously these exports silently failed on compressed GLBs because the loader had no decoder registered; the pipeline now loads the meshopt and Draco decoders before parsing, so every avatar — including the compressed ones produced by the server-side bake — converts cleanly.</description>
</item>
+ <item>
+ <title>IBM sites can now embed three.ws pages</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-19:IBM sites can now embed three.ws pages</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>security</category>
+ <description>We extended the sitewide clickjacking protection to allow IBM properties to frame three.ws. Any page on ibm.com (and its subdomains) may now load three.ws pages inside an iframe — useful for the IBM x402 demo and other IBM-hosted integrations — while every other external site is still refused by default. Sign-in, wallet, dashboard and OAuth consent pages remain hard-locked and cannot be framed by anyone, including IBM. The avatar, widget and walk embeds continue to work on any site as before.</description>
+ </item>
<item>
<title>Agent economy demos now show honest run status</title>
<link>https://three.ws/live</link>
diff --git a/public/features.json b/public/features.json
index b71a5ea1d..3d558dc8d 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T00:01:31.477Z",
+ "generated_at": "2026-06-19T00:19:16.797Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/bounties.js b/src/bounties.js
index c99842502..47aded23f 100644
--- a/src/bounties.js
+++ b/src/bounties.js
@@ -174,7 +174,7 @@ async function load(reset = false) {
if (query && nextCursor && !scanning) scanForSearch();
} catch (err) {
if (reset) grid().innerHTML = errorState(err.message);
- else setLoadMore('Retry', false);
+ else setLoadMore('Couldn’t load more — tap to retry', false);
}
}
diff --git a/src/communities.js b/src/communities.js
index 4125fa62c..7aab0b39b 100644
--- a/src/communities.js
+++ b/src/communities.js
@@ -338,10 +338,15 @@ async function loadCoinProfile(mint) {
$('coin-profile-empty').hidden = true;
let coin = null;
+ let loadFailed = false;
try {
const r = await fetch(`/api/pump/coin?mint=${encodeURIComponent(mint)}`, { headers: { accept: 'application/json' } });
if (r.ok) coin = await r.json();
+ // A 5xx (or any non-404 non-ok) is a transient failure, not a real "missing
+ // coin" — track it so we offer a retry instead of a misleading "not found".
+ else if (r.status !== 404) loadFailed = true;
} catch (err) {
+ loadFailed = true;
log.warn('[communities] coin profile', err?.message ?? err);
}
@@ -352,9 +357,25 @@ async function loadCoinProfile(mint) {
$('coin-profile-skeleton').hidden = true;
$('coin-profile-empty').hidden = false;
$('coin-profile-empty-mint').textContent = mint;
- document.title = 'Coin not found · three.ws';
+ const retryBtn = $('coin-profile-retry');
+ if (loadFailed) {
+ // Couldn't reach the feed — distinguish from a genuine 404 and let the
+ // user retry the same mint without re-navigating.
+ $('coin-profile-empty-msg').textContent = 'Couldn’t load this coin right now.';
+ document.title = 'Couldn’t load coin · three.ws';
+ if (retryBtn) {
+ retryBtn.hidden = false;
+ retryBtn.onclick = () => loadCoinProfile(mint);
+ }
+ } else {
+ $('coin-profile-empty-msg').textContent = 'That coin couldn’t be found on pump.fun.';
+ document.title = 'Coin not found · three.ws';
+ if (retryBtn) retryBtn.hidden = true;
+ }
return;
}
+ const retryBtn = $('coin-profile-retry');
+ if (retryBtn) retryBtn.hidden = true;
renderCoinProfile(coin);
// Live market data + trades enrich the page once the core render is up.
diff --git a/src/dashboard-next/pages/monetize.js b/src/dashboard-next/pages/monetize.js
index cd69fc1f1..287437029 100644
--- a/src/dashboard-next/pages/monetize.js
+++ b/src/dashboard-next/pages/monetize.js
@@ -106,7 +106,7 @@ async function loadAndRender(host, me, agents) {
const [
revenue, withdrawalsResp, walletsResp, summary, plans,
- mineSubs, earningsResp, pricesResp, monWalletResp, monRevenueResp,
+ mineSubs, earningsResp, pricesResp, monWalletResp, monRevenueResp, feeInfo,
] = await Promise.all([
safe(() => get(`/api/billing/revenue?from=${encodeURIComponent(since30)}&granularity=day`)),
safe(() => get('/api/billing/withdrawals?limit=50')),
@@ -120,8 +120,14 @@ async function loadAndRender(host, me, agents) {
selectedAgentId ? safe(() => get(`/api/monetization/prices?${agentParam}`)) : Promise.resolve(null),
selectedAgentId ? safe(() => get(`/api/monetization/wallet?${agentParam}`)) : Promise.resolve(null),
selectedAgentId ? safe(() => get(`/api/monetization/revenue?${agentParam}&period=all`)) : Promise.resolve(null),
+ safe(() => get('/api/billing/fee-info')),
]);
+ // Platform fee, used to show agent owners their net per-payment take when
+ // pricing skills. Fall back to the documented 2.5% default if the rate
+ // endpoint is unreachable so the UI never renders a misleading "0% fee".
+ const feeBps = Number.isFinite(Number(feeInfo?.fee_bps)) ? Number(feeInfo.fee_bps) : 250;
+
// If every primary revenue surface failed to load, the page would otherwise
// render an all-zero hero and empty panels with no signal that the data is
// simply unreachable. Surface a single retryable error instead.
@@ -163,7 +169,7 @@ async function loadAndRender(host, me, agents) {
host.appendChild(renderHero({ available, revenue, creatorPlans, subscribedTo, pendingRoyaltyAtomics, monRevenue }));
if (selectedAgentId) {
- host.appendChild(renderSkillPricing(skillPrices, selectedAgentId, host, me, agents));
+ host.appendChild(renderSkillPricing(skillPrices, selectedAgentId, host, me, agents, feeBps));
host.appendChild(renderPayoutWalletPanel(monWallet, selectedAgentId, host, me, agents, wallets));
}
@@ -275,17 +281,20 @@ function heroCard({ title, value, sub, color, button }) {
// -- Skill Pricing Panel --
-function renderSkillPricing(prices, agentId, host, me, agents) {
+function renderSkillPricing(prices, agentId, host, me, agents, feeBps = 250) {
const panel = document.createElement('div');
panel.className = 'dn-panel';
let skillPrices = [...prices];
+ const feePercent = (feeBps / 100).toFixed(feeBps % 100 === 0 ? 0 : 1);
+ const netOf = (price) => Math.max(0, price * (1 - feeBps / 10_000));
+
function paint() {
panel.innerHTML = `
<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:14px">
<div>
<div class="dn-panel-title">Skill Pricing</div>
- <div class="dn-panel-sub" style="margin:2px 0 0">Set per-call prices for your agent's skills. Callers pay in USDC.</div>
+ <div class="dn-panel-sub" style="margin:2px 0 0">Set per-call prices for your agent's skills. Callers pay in USDC — the platform takes ${esc(feePercent)}% per payment.</div>
</div>
<button class="dn-btn primary" data-action="add-price">+ Add Pricing</button>
</div>
@@ -322,6 +331,9 @@ function renderSkillPricing(prices, agentId, host, me, agents) {
<input type="number" min="0" step="0.000001" class="mon-input mon-input-sm"
value="${esc(String(p.price_usdc ?? p.price ?? 0))}"
data-field="price" data-idx="${idx}" aria-label="Price" />
+ <div class="mon-fee-note" data-slot="fee-note" data-idx="${idx}">
+ You receive ${esc(formatNetUsdc(netOf(Number(p.price_usdc ?? p.price ?? 0))))} after ${esc(feePercent)}% fee
+ </div>
</td>
<td style="text-align:center">
<label class="mon-toggle" title="${active ? 'Active' : 'Inactive'}">
@@ -344,13 +356,27 @@ function renderSkillPricing(prices, agentId, host, me, agents) {
}
panel.querySelector('[data-action="add-price"]').addEventListener('click', () => {
- openAddPriceModal(agentId, (saved) => {
+ openAddPriceModal(agentId, feeBps, (saved) => {
skillPrices.push(saved);
paint();
toastMonetize('Skill price added');
});
});
+ // Live-update the "you receive" note as the owner edits a price so the
+ // net take is always in sync with what they're typing.
+ panel.querySelectorAll('input[data-field="price"]').forEach((input) => {
+ input.addEventListener('input', () => {
+ const idx = input.dataset.idx;
+ const note = panel.querySelector(`[data-slot="fee-note"][data-idx="${idx}"]`);
+ if (!note) return;
+ const val = parseFloat(input.value);
+ note.textContent = Number.isFinite(val) && val >= 0
+ ? `You receive ${formatNetUsdc(netOf(val))} after ${feePercent}% fee`
+ : `Enter a valid price`;
+ });
+ });
+
panel.querySelectorAll('[data-action="save-price"]').forEach(btn => {
btn.addEventListener('click', async () => {
const idx = Number(btn.dataset.idx);
@@ -407,7 +433,9 @@ function renderSkillPricing(prices, agentId, host, me, agents) {
return panel;
}
-function openAddPriceModal(agentId, onSaved) {
+function openAddPriceModal(agentId, feeBps, onSaved) {
+ const feePercent = (feeBps / 100).toFixed(feeBps % 100 === 0 ? 0 : 1);
+ const netOf = (price) => Math.max(0, price * (1 - feeBps / 10_000));
const overlay = document.createElement('div');
overlay.className = 'mon-overlay';
overlay.innerHTML = `
@@ -422,6 +450,7 @@ function openAddPriceModal(agentId, onSaved) {
<label class="mon-field">
<span class="mon-label">Price per call (USDC)</span>
<input data-slot="price" type="number" min="0" step="0.000001" placeholder="0.001" class="mon-input" />
+ <span data-slot="fee-note" class="mon-fee-note">Platform fee: ${esc(feePercent)}% — set a price to see your net take.</span>
</label>
<label style="display:flex;align-items:center;gap:10px;margin-bottom:18px;cursor:pointer">
@@ -443,9 +472,17 @@ function openAddPriceModal(agentId, onSaved) {
const priceEl = overlay.querySelector('[data-slot="price"]');
const activeEl = overlay.querySelector('[data-slot="active"]');
const errorEl = overlay.querySelector('[data-slot="error"]');
+ const feeNoteEl = overlay.querySelector('[data-slot="fee-note"]');
const submitBtn = overlay.querySelector('[data-action="submit"]');
skillEl.focus();
+ priceEl.addEventListener('input', () => {
+ const val = parseFloat(priceEl.value);
+ feeNoteEl.textContent = Number.isFinite(val) && val > 0
+ ? `Platform fee: ${feePercent}% — you receive ${formatNetUsdc(netOf(val))} per call.`
+ : `Platform fee: ${feePercent}% — set a price to see your net take.`;
+ });
+
const close = () => { overlay.remove(); document.removeEventListener('keydown', onKey); };
const onKey = (e) => { if (e.key === 'Escape') close(); };
document.addEventListener('keydown', onKey);
@@ -788,6 +825,16 @@ function renderSkillLegend(bySkill) {
.join('');
}
+// Format a human-denominated USDC amount (not atomics) for the net-take note.
+// Skill prices range from sub-cent (0.001) to dollars, so show enough precision
+// to keep tiny per-call prices meaningful without trailing-zero noise on whole cents.
+function formatNetUsdc(amount) {
+ const n = Number(amount);
+ if (!Number.isFinite(n) || n <= 0) return '$0.00';
+ const decimals = n < 0.01 ? 6 : n < 1 ? 4 : 2;
+ return `$${n.toFixed(decimals)}`;
+}
+
function humanizeSkill(skill) {
if (!skill) return 'Other';
const map = {
@@ -1999,6 +2046,7 @@ function injectStyles() {
.mon-field { display: flex; flex-direction: column; gap: 6px; margin-bottom: 14px; }
.mon-label { font-size: 12px; color: var(--nxt-ink-dim); font-weight: 500; }
.mon-hint { font-size: 11.5px; color: var(--nxt-ink-fade); }
+.mon-fee-note { display: block; font-size: 11px; color: var(--nxt-ink-fade); margin-top: 4px; font-variant-numeric: tabular-nums; }
.mon-error { font-size: 12.5px; color: var(--nxt-danger); min-height: 18px; margin-bottom: 10px; }
.mon-form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
diff --git a/vercel.json b/vercel.json
index 5e8610e92..e96ef8046 100644
--- a/vercel.json
+++ b/vercel.json
@@ -198,10 +198,9 @@
"headers": {
"strict-transport-security": "max-age=63072000; includeSubDomains; preload",
"x-content-type-options": "nosniff",
- "x-frame-options": "SAMEORIGIN",
"referrer-policy": "strict-origin-when-cross-origin",
"permissions-policy": "accelerometer=(), autoplay=(self), bluetooth=(), camera=(), display-capture=(), encrypted-media=(self), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(self), serial=(), usb=(), xr-spatial-tracking=(self)",
- "content-security-policy": "base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://ajax.googleapis.com https://s3.tradingview.com https://platform.twitter.com https://3d-agent.vercel.app https://three.ws; worker-src 'self' blob:; frame-ancestors 'self'; report-uri /api/client-errors"
+ "content-security-policy": "base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://ajax.googleapis.com https://s3.tradingview.com https://platform.twitter.com https://3d-agent.vercel.app https://three.ws; worker-src 'self' blob:; frame-ancestors 'self' https://*.ibm.com; report-uri /api/client-errors"
},
"continue": true
},