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.

Wallet pay tab, agent accessories, cosmetics, x402 routing + trade-guard tests, changelog

nirholasd6ead35947a2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1962a3cab..65c2cf0ba 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +42,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The disco dance floor in coin worlds works again** — Every coin world has a disco pad beside the totem that pulses to a shared beat and crossfades dancers in lockstep. A wiring gap meant the world tried to listen for a beat the connection didn't know about, which threw an error the moment you entered and left the pad dark. The beat is now delivered properly: step onto the pad, hit Dance, and you and everyone else standing on it move to the same animation on the same beat, with the floor and lights pulsing in time. (`/play`) `[fix]`
- **The homepage avatar now prays, then walks** — Tap “🙏 Pray” on the homepage hero and the avatar finishes the prayer and rises straight into a walk — one smooth motion instead of snapping back to a standing idle at the end of the clip. After the walk plays out, the avatar eases back into its gentle idle-and-stroll rhythm. The other one-tap emotes (wave, dance, jump, and the rest) also return to that ambient motion now instead of freezing on their last frame. `[improvement]`
- **The Pole Club walk-in is full of people now** — Walking up to the Pole Club, you used to move through the alley, the gallery, and the clubhouse completely alone. Now every room is full: each one is populated with a live crowd built from our avatars — the bundled looks plus public avatars from the gallery — grounded on the floor and moving for real. Near the entrance they lean, chill, and idle; deeper in, more of them are dancing, so the energy builds as you get closer to the stage. The crowd lines your route instead of blocking it, and the head-count scales to your device so it stays smooth on phones and goes big on desktop. (`/club`) `[feature, improvement]`
+- **The x402 demo we built with IBM now runs under a locked-down security policy** — The live x402 demo we made with IBM was hardened so it can be hosted on a strict corporate site. It no longer pulls fonts or the 3D model viewer from Google's CDN — both now ship with the page from three.ws — so it loads cleanly under a strict Content-Security-Policy and even inside an iframe, with no blocked requests. Paying with MetaMask on Base needs nothing but three.ws; if a locked-down host blocks the small library the Solana path loads, the page now says so plainly and the Base button keeps working. The 3D viewer also loads only once you actually forge a model, so the page opens lighter. We published the exact policy and hosting steps for IBM's web team. (`/ibm/x402-demo`) `[improvement, security]`
- **Tip a dancer for a Pole Twerk and she works the pole** — The Club stage has a new headline move: Pole Twerk, now the default style on every pole. Tip a dancer for it and instead of facing the crowd like the other styles, she turns into the pole and works it with her back to the room — a real pole-dancer twerk, not a free-floor one — set to its own track. Pick it (or any other style) from the dropdown on each pole before you tip; all the existing dances are still there. (`/club`) `[feature]`
- **Tipping a dancer goes straight to the wallet now** — Tapping Tip in the Pole Club used to open a three-step “Before you go on-chain” explainer first, and dismissing it cancelled the tip entirely — so first-time visitors couldn't pay without sitting through the wizard. That gate is gone. Tip now opens the wallet-and-amount checkout directly, where you pick Phantom or a browser wallet, see the exact USDC amount, and approve with one signature. The checkout already shows everything the explainer did, so there's no reason to stack a lecture in front of a fraction-of-a-cent tip. (`/club`) `[improvement]`
- **Tipping a dancer in the Club is now one tap** — In the Pole Club, paying a dancer used to pop an extra step that made you pick your wallet before anything happened — annoying when you just want to tip and watch her dance, and worse when tipping pole after pole. Now, when a single wallet is detected, hitting Tip goes straight to the signature: approve the $0.001 USDC and she takes the pole. The same shortcut applies to the cover charge at the door. If you have more than one wallet installed you still get to choose, and the free re-entry option for returning guests is untouched. (`/club`) `[improvement]`
@@ -49,6 +50,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **You can move the moment a Coin Communities world loads** — On phones, the first-time welcome card in /play covered the whole screen — including the movement joystick — so new players tapped the stick and nothing happened until they dismissed the intro. The welcome card is now a non-blocking overlay: the joystick (and look-drag) stay live behind it and sit crisp on top, so you can start walking the instant the world appears, whether you read the intro first or not. (`/play`) `[fix]`
- **Your $THREE holder tier now shows across the site** — Holding $THREE is now visible everywhere you are. A holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) on every page and links to the full tier breakdown. On Forge, choosing the High quality tier now shows a clear, designed panel instead of a silent block: holders see an "Unlocked" badge and generate straight away, while everyone else gets a "Get $THREE" path, the exact reason (sign in, link a wallet, or hold more), and a one-tap switch back to free Draft or Standard — no dead ends and no raw errors. (`/forge`) `[feature, improvement]`
- **Your agent and its answer now sit together in chat** — When an agent replied with a 3D avatar — especially while it was thinking or forging several models at once — the avatar used to float off on its own with a big empty gap, while the reasoning note and the tool buttons drifted down beside its feet. The agent now stands next to its own response: the avatar is framed tighter so it fills its space instead of hovering in the void, and its thinking note and tool calls line up with it as one tidy block. It reads as a single reply whether you're in the normal view or have a tool's details open in the side panel. (`/chat`) `[improvement]`
+- **Your agent can now pay for paid APIs from its own wallet** — The wallet's new Pay tab lets your agent buy from the x402 marketplace in USDC straight from its own Solana wallet — never a shared platform account. Search the bazaar for a paid service (or paste an endpoint), see the live price and exactly what you're buying before you commit, then pay; you watch the payment get built, signed by the agent, and settled on-chain, and get the receipt with a transaction link. Every payment is checked against the agent's own spend limits first, and if the wallet is short on USDC it tells you and sends you to fund it instead of failing mid-pay. A running Payment activity list shows what the agent paid for, to whom, and when. Whenever an agent is in context, payments always come from that agent's wallet. (`/agents`) `[feature]`
+- **Your agent can now trade from its own wallet — with real guardrails** — Fund your agent's wallet and let it buy and sell pump.fun coins straight from that wallet, signed for you on the server — no wallet popup per trade. Every trade runs through the same safety checks the auto-sniper uses, now shared as one rulebook so they can never drift apart: a per-trade size cap, a rolling daily spend budget, a price-impact circuit breaker, a fee-and-rent cushion so a buy never bricks the wallet, and a kill switch to pause all trading instantly. Set those limits per agent under Limits & Safety. If a trade would cross a limit you get a clear, specific reason back instead of a failure — and a retried request can never double-spend. Graduated coins route through the AMM automatically, and every trade lands in one unified history alongside your sniper's. (`/agents`) `[feature, security]`
- **Your AR agent now hides behind real-world objects** — Place an agent in your room with the AR button and it now lives in the space instead of floating on top of the camera feed. Walk a chair, a doorway, or your own hand between your phone and the agent and the agent is correctly hidden behind it — the single biggest "is this really in my room?" upgrade. It uses your phone's depth sensor on devices that have one (recent Android Chrome); on every other device AR works exactly as before, with no change and nothing to turn on. (`/features/ar`) `[feature]`
## 2026-06-17
diff --git a/api/_lib/cosmetics.js b/api/_lib/cosmetics.js
index 3a544a00b..4cca11ad3 100644
--- a/api/_lib/cosmetics.js
+++ b/api/_lib/cosmetics.js
@@ -61,9 +61,9 @@ const CATALOG = [
{ id: 'hat-cowboy', name: 'Cowboy Hat', slot: 'hat', kind: 'hat', rarity: 'rare',
glbUrl: '/accessories/hat-cowboy.glb', attachBone: 'Head', previewImage: '/accessories/thumbs/hat-cowboy.png' },
{ id: 'glasses-round', name: 'Round Glasses', slot: 'glasses', kind: 'glasses', rarity: 'common',
- glbUrl: '/accessories/glasses-round.glb', attachBone: 'Head', previewImage: '/accessories/thumbs/glasses-round.png' },
+ glbUrl: '/accessories/glasses-round.glb', attachBone: 'Head', anchor: 'face', previewImage: '/accessories/thumbs/glasses-round.png' },
{ id: 'glasses-shades', name: 'Shades', slot: 'glasses', kind: 'glasses', rarity: 'rare',
- glbUrl: '/accessories/glasses-shades.glb', attachBone: 'Head', previewImage: '/accessories/thumbs/glasses-shades.png' },
+ glbUrl: '/accessories/glasses-shades.glb', attachBone: 'Head', anchor: 'face', previewImage: '/accessories/thumbs/glasses-shades.png' },
{ id: 'earrings-hoops', name: 'Hoop Earrings', slot: 'earrings', kind: 'earrings', rarity: 'common',
glbUrl: '/accessories/earrings-hoops.glb', attachBone: 'Head', previewImage: '/accessories/thumbs/earrings-hoops.png' },
{ id: 'earrings-studs', name: 'Stud Earrings', slot: 'earrings', kind: 'earrings', rarity: 'common',
@@ -144,7 +144,7 @@ export function buildCatalog({ ownedIds = [], rarity = null } = {}) {
locked: !isOwned,
previewImage: c.previewImage || null,
// Rig payload the live preview needs — only the relevant keys per kind.
- ...(c.glbUrl ? { glbUrl: c.glbUrl, attachBone: c.attachBone } : {}),
+ ...(c.glbUrl ? { glbUrl: c.glbUrl, attachBone: c.attachBone, ...(c.anchor ? { anchor: c.anchor } : {}) } : {}),
...(c.morphBinding ? { morphBinding: c.morphBinding } : {}),
...(c.colors ? { colors: c.colors } : {}),
...(c.emote ? { emote: c.emote } : {}),
diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.js
index 42984279c..5fab8de31 100644
--- a/api/agents/agent-trade.js
+++ b/api/agents/agent-trade.js
@@ -24,7 +24,7 @@ import { sql } from '../_lib/db.js';
import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { ensureAgentWallet, recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
-import { getConnection, getPumpTradeClient } from '../_lib/pump.js';
+import { getPumpTradeClient } from '../_lib/pump.js';
import { buildAmmSellInstructions, quoteAmmSell } from '../../workers/agent-sniper/amm-exit.js';
import { logAudit } from '../_lib/audit.js';
import { explorerTxUrl } from '../_lib/avatar-wallet.js';
@@ -36,11 +36,11 @@ import {
import { randomUUID } from 'node:crypto';
import {
validateSolanaAddress, enforceSpendLimit, SpendLimitError, lamportsToUsd,
- getSpendLimits, getTradeLimits, setTradeLimits, getDailySpendLamports,
- recordCustodyEvent, updateCustodyEvent,
+ getTradeLimits, setTradeLimits, getDailySpendLamports,
+ updateCustodyEvent,
checkKillSwitch, checkConcurrency, checkPerTradeCap, checkDailyBudgetLamports,
checkSolHeadroom, checkPriceImpact, tradeGuardResponse,
- SOL_FEE_HEADROOM_LAMPORTS, LAMPORTS_PER_SOL, TRADE_LIMIT_DEFAULTS,
+ SOL_FEE_HEADROOM_LAMPORTS, TRADE_LIMIT_DEFAULTS,
} from '../_lib/agent-trade-guards.js';
const WSOL_MINT = 'So11111111111111111111111111111111111111112';
diff --git a/api/agents/solana-trade.js b/api/agents/solana-trade.js
index 44914a9e8..6e9ad1942 100644
--- a/api/agents/solana-trade.js
+++ b/api/agents/solana-trade.js
@@ -43,7 +43,6 @@ import { getAmmPoolState } from '../_lib/pump.js';
const LAMPORTS_PER_SOL = 1_000_000_000;
const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
-const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
// The SOL fee/rent headroom, the price-impact breaker, the per-trade cap, the
// daily budget, and the kill switch all live in the shared guardrail module
@@ -411,8 +410,7 @@ export async function handleTrade(req, res, id) {
return error(res, 402, fundsWarning.code, fundsWarning.message, fundsWarning.detail);
}
if (guardWarning) {
- const status = guardWarning.code === 'price_impact_too_high' ? 422 : 403;
- return error(res, status, guardWarning.code, guardWarning.message, guardWarning.detail);
+ return error(res, guardWarning.status || 403, guardWarning.code, guardWarning.message, guardWarning.detail);
}
// Idempotency key — required for execute so a retry can't double-spend.
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index d4cc42618..e6c185af9 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -26,7 +26,7 @@ import { explorerTxUrl } from '../_lib/avatar-wallet.js';
import {
validateSolanaAddress, enforceSpendLimit, SpendLimitError, lamportsToUsd,
getSpendLimits, setSpendLimits, listCustodyEvents, updateCustodyEvent,
- getDailySpendUsd,
+ getDailySpendUsd, getTradeLimits, setTradeLimits, getDailySpendLamports,
} from '../_lib/agent-trade-guards.js';
// USDC mints per cluster — the only SPL token we can price 1:1 for the spend
@@ -975,20 +975,31 @@ async function handleLimits(req, res, id) {
const bad = body.withdraw_allowlist.find((a) => !validateSolanaAddress(a).valid);
if (bad !== undefined) return error(res, 400, 'invalid_address', `withdraw_allowlist contains an invalid Solana address: ${String(bad).slice(0, 60)}`);
}
- let limitsOut;
+ // The USD spend policy and the lamports-denominated trade policy share this
+ // owner surface. A PUT may patch either or both: a `trade_limits` object
+ // updates the discretionary-trade caps (per-trade SOL, daily budget, breaker,
+ // kill switch); the top-level USD/allowlist keys update the spend policy.
+ const wantsSpend = ['daily_usd', 'per_tx_usd', 'withdraw_allowlist'].some((k) => k in body);
+ let limitsOut = getSpendLimits(meta);
+ let tradeLimitsOut = getTradeLimits(meta);
try {
- limitsOut = await setSpendLimits(id, auth.userId, body, { req });
+ if (wantsSpend) limitsOut = await setSpendLimits(id, auth.userId, body, { req });
+ if (body.trade_limits && typeof body.trade_limits === 'object') {
+ tradeLimitsOut = await setTradeLimits(id, auth.userId, body.trade_limits, { req });
+ }
} catch (e) {
if (e?.status) return error(res, e.status, e.code || 'error', e.message);
throw e;
}
const spentUsd = await getDailySpendUsd(id, network).catch(() => 0);
- return json(res, 200, { data: { limits: limitsOut, spent_today_usd: spentUsd } });
+ const spentLamports = await getDailySpendLamports(id, network).catch(() => 0n);
+ return json(res, 200, { data: { limits: limitsOut, trade_limits: tradeLimitsOut, spent_today_usd: spentUsd, spent_today_sol: Number(spentLamports) / 1e9 } });
}
const limitsOut = getSpendLimits(meta);
const spentUsd = await getDailySpendUsd(id, network).catch(() => 0);
- return json(res, 200, { data: { limits: limitsOut, spent_today_usd: spentUsd } });
+ const spentLamports = await getDailySpendLamports(id, network).catch(() => 0n);
+ return json(res, 200, { data: { limits: limitsOut, trade_limits: getTradeLimits(meta), spent_today_usd: spentUsd, spent_today_sol: Number(spentLamports) / 1e9 } });
}
// ── dispatcher ────────────────────────────────────────────────────────────────
diff --git a/data/changelog.json b/data/changelog.json
index 87d894771..cd87180aa 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,35 @@
{
"$comment": "Curated changelog entries for three.ws \u2014 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-18",
+ "title": "Your agent can now pay for paid APIs from its own wallet",
+ "summary": "The wallet's new Pay tab lets your agent buy from the x402 marketplace in USDC straight from its own Solana wallet — never a shared platform account. Search the bazaar for a paid service (or paste an endpoint), see the live price and exactly what you're buying before you commit, then pay; you watch the payment get built, signed by the agent, and settled on-chain, and get the receipt with a transaction link. Every payment is checked against the agent's own spend limits first, and if the wallet is short on USDC it tells you and sends you to fund it instead of failing mid-pay. A running Payment activity list shows what the agent paid for, to whom, and when. Whenever an agent is in context, payments always come from that agent's wallet.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agents"
+ },
+ {
+ "date": "2026-06-18",
+ "title": "The x402 demo we built with IBM now runs under a locked-down security policy",
+ "summary": "The live x402 demo we made with IBM was hardened so it can be hosted on a strict corporate site. It no longer pulls fonts or the 3D model viewer from Google's CDN — both now ship with the page from three.ws — so it loads cleanly under a strict Content-Security-Policy and even inside an iframe, with no blocked requests. Paying with MetaMask on Base needs nothing but three.ws; if a locked-down host blocks the small library the Solana path loads, the page now says so plainly and the Base button keeps working. The 3D viewer also loads only once you actually forge a model, so the page opens lighter. We published the exact policy and hosting steps for IBM's web team.",
+ "tags": [
+ "improvement",
+ "security"
+ ],
+ "link": "/ibm/x402-demo"
+ },
+ {
+ "date": "2026-06-18",
+ "title": "Your agent can now trade from its own wallet — with real guardrails",
+ "summary": "Fund your agent's wallet and let it buy and sell pump.fun coins straight from that wallet, signed for you on the server — no wallet popup per trade. Every trade runs through the same safety checks the auto-sniper uses, now shared as one rulebook so they can never drift apart: a per-trade size cap, a rolling daily spend budget, a price-impact circuit breaker, a fee-and-rent cushion so a buy never bricks the wallet, and a kill switch to pause all trading instantly. Set those limits per agent under Limits & Safety. If a trade would cross a limit you get a clear, specific reason back instead of a failure — and a retried request can never double-spend. Graduated coins route through the AMM automatically, and every trade lands in one unified history alongside your sniper's.",
+ "tags": [
+ "feature",
+ "security"
+ ],
+ "link": "/agents"
+ },
{
"date": "2026-06-18",
"title": "The Pole Club walk-in is full of people now",
diff --git a/pages/ibm/HOSTING.md b/pages/ibm/HOSTING.md
index d025a73b8..29e364aa8 100644
--- a/pages/ibm/HOSTING.md
+++ b/pages/ibm/HOSTING.md
@@ -40,12 +40,12 @@ from `https://three.ws` (still no build step, still no backend):
settlement the moment the visitor's `402` call clears. It lazy-boots only when scrolled into
view, and degrades to a calm skeleton if its script is blocked.
-Because these load the agent runtime, an avatar GLB, the agent's model endpoint, and framed
-three.ws pages, the **Tier 2** CSP below adds `https://three.ws` to `frame-src`/`img-src` and
-`blob:` to `worker-src`. If you only want the x402 payment demo and not the 3D/agent layer,
-delete the `#forge`, `#agent`, `#play`, and `#irl` `<section>`s plus the `agent-3d.js`
-`<script>` tag, and the
-**Tier 1** policy is all you need.
+Because these load the agent runtime, an avatar GLB, a WebGL/WASM context, `blob:` workers, and
+framed three.ws pages, the 3D layer needs the more permissive **Tier 2** CSP below (each added
+directive is explained in the table there). The Forge viewer's `<model-viewer>` is self-hosted
+(see *What to upload*) so it stays a same-origin script. If you only want the x402 payment demo
+and not the 3D/agent layer, delete the `#forge`, `#agent`, `#play`, and `#irl` `<section>`s plus
+the `agent-3d.js` `<script>` tag, and the **Tier 1** policy is all you need.
## What to upload
@@ -61,21 +61,36 @@ fonts/
IBMPlexMono-400.woff2
IBMPlexMono-500.woff2
vendor/
- model-viewer.min.js
+ model-viewer.min.js (~0.9 MB; the 3D viewer, self-hosted so no Google CDN is needed)
```
+Optional, **at the site root** (`live.ibm.com/three.svg`):
+
+```
+three.svg (the three.ws watermark the 3D agent overlays on snapshot exports)
+```
+
+The 3D agent fetches `/three.svg` from the origin root. If it's absent the agent still renders
+perfectly — you'll just see one harmless `Failed to load watermark` console message and snapshot
+exports won't carry the mark. Upload `three.svg` to the site root to remove that message. (On the
+three.ws reference deployment this already resolves, so the message only appears on a foreign host
+that hasn't placed the file.)
+
Everything else (the payment widget, the API, the explorer links) is loaded at runtime from
`https://three.ws` and the public chain explorers. There is **no build step** and **no
backend** to deploy. IBM Plex is self-hosted from `fonts/` so the page needs no third-party
font CDN, and the `<model-viewer>` web component (used by the Forge demo to display the
generated 3D model) is self-hosted from `vendor/` — it loads as a same-origin
-(`script-src 'self'`) ES module, so no third-party script CDN is required either. Keep
-`vendor/` next to the HTML; the file references it as `./vendor/model-viewer.min.js`.
+(`script-src 'self'`) ES module, lazily and only after a model is forged, so no third-party
+script CDN is required and a page view that never forges never pays its weight. Keep `vendor/`
+next to the HTML; the file references it as `./vendor/model-viewer.min.js`.
## Content-Security-Policy
The page runs under **the host's CSP**. Pick one tier. (If `live.ibm.com` sends no CSP, the
-page works as-is; these are for hardened hosts.)
+page works as-is; these are for hardened hosts.) Both tiers below were verified in a real
+Chromium, served from a non-three.ws origin with the CSP enforced as a response header — both
+top-level and inside a cross-origin iframe — with **zero CSP violations** and no page errors.
### Tier 1 — Strict (Base / MetaMask only, recommended default)
@@ -93,29 +108,40 @@ Content-Security-Policy:
base-uri 'self';
```
-Under this policy the Solana button will fail gracefully (its dependencies are blocked) while
-the Base button works fully.
+> `'unsafe-inline'` covers the page's inline `<style>` and the two small inline bootstrap
+> `<script>` blocks. If IBM requires nonces, drop `'unsafe-inline'` and add a per-response
+> nonce to the inline `<style>` and `<script>` tags instead.
-> `'unsafe-inline'` covers the page's inline `<style>` and the small inline bootstrap
-> `<script>`. If IBM requires nonces, add a per-response nonce to the inline `<style>` and
-> `<script>` tags instead of `'unsafe-inline'`.
+Under this policy the Base button works fully; the Solana button fails gracefully — its `esm.sh`
+dependency is blocked — with a clear message that steers the visitor to the Base path. The page
+degrades, it never throws.
> Under Tier 1 the **3D agent layer** (the agent, and the Forge/Play/IRL rooms) is also
-> blocked — it needs `frame-src`, `worker-src blob:`, and `https://three.ws` in `img-src`,
-> which Tier 1 omits. Use Tier 2 to enable it, or remove those sections (see above) to keep
-> Tier 1.
+> blocked — it needs `frame-src`, `worker-src blob:`, `connect-src blob:`,
+> `script-src 'wasm-unsafe-eval'`, and `https://esm.sh`, which Tier 1 omits. Use Tier 2 to
+> enable it, or remove those sections (see above) to keep Tier 1.
### Tier 2 — Full (Base + Solana, plus the 3D agent layer)
-The Solana path dynamic-imports `@solana/web3.js` from `esm.sh`. The agent layer adds the
-`<agent-3d>` runtime + avatar GLB + model endpoint (all `https://three.ws`), a WebGL/worker
-`blob:` context, and framed three.ws surfaces. One policy covers all of it:
+This enables every demo. Each addition over Tier 1 is load-bearing — verified by removing it
+and observing the resulting violation in a real browser:
+
+| Directive | Why it's needed |
+|-----------|-----------------|
+| `script-src … https://esm.sh` | the Solana path dynamic-imports `@solana/web3.js` |
+| `script-src … 'wasm-unsafe-eval'` | the agent/avatar instantiate a WebAssembly module |
+| `connect-src 'self'` | the agent fetches its `/three.svg` watermark from the host origin |
+| `connect-src … blob:` | the agent and model-viewer read geometry/textures via `blob:` URLs |
+| `connect-src … https://esm.sh` | fetching the Solana library bundle |
+| `img-src … blob: https://three.ws` | WebGL textures (`blob:`) and three.ws imagery |
+| `worker-src 'self' blob:` | model-viewer and the agent spawn `blob:` workers |
+| `frame-src https://three.ws` | the Forge / Play / IRL `<iframe>`s |
```
Content-Security-Policy:
default-src 'none';
- script-src 'self' https://three.ws https://esm.sh 'unsafe-inline';
- connect-src https://three.ws https://esm.sh;
+ script-src 'self' https://three.ws https://esm.sh 'unsafe-inline' 'wasm-unsafe-eval';
+ connect-src 'self' blob: https://three.ws https://esm.sh;
style-src 'self' 'unsafe-inline';
font-src 'self';
img-src 'self' data: blob: https://three.ws;
@@ -124,6 +150,14 @@ Content-Security-Policy:
base-uri 'self';
```
+> The framed surfaces (`three.ws/play`, `three.ws/irl`, `three.ws/forge`) are separate
+> documents governed by **three.ws's own** CSP — anything *they* load (chain RPCs, IPFS
+> gateways, market data) is three.ws's concern, not the host page's. The host CSP only needs to
+> permit framing them (`frame-src https://three.ws`). One known cross-origin item: the embedded
+> `three.ws/irl` AR surface currently logs an internal `setMeshoptDecoder…` avatar message from
+> inside its own iframe; it is three.ws app behavior, independent of the host page and unaffected
+> by either CSP tier.
+
## Visitor requirements
- A browser wallet: **MetaMask** (Base) or **Phantom** (Solana).
@@ -136,10 +170,18 @@ Content-Security-Policy:
## Top-level page vs. iframe
Host it as a **top-level page** for best results: browser wallet extensions inject reliably
-into top-level documents, and the payment modal has full screen real estate. It can be
-embedded in an `<iframe>`, but some browsers restrict wallet-extension injection into
-cross-origin iframes — if you must iframe it, test the wallet flow in your target browsers
-first, or link out to the standalone page.
+into top-level documents, and the payment modal has full screen real estate. The page was
+verified to load and run inside a **cross-origin iframe** as well — it sends no
+`X-Frame-Options` and sets no restrictive `frame-ancestors`, so framing is not blocked, and the
+demo (live 402 preview, widget, agent) renders in-frame. The one caveat is the wallet step:
+**some browsers restrict wallet-extension injection into cross-origin iframes**, so the wallet
+prompt may not appear in-frame in every browser. If you must iframe it, test the wallet flow in
+your target browsers first, or link out to the standalone page.
+
+A short console note: while reading the live payment challenge the demo intentionally
+`fetch()`es endpoints that return HTTP `402`/`401`; browsers log every non-2xx fetch, so one or
+two `responded with a status of 402` lines are expected — that is the protocol working, not a
+fault. The page's own logic raises no errors under either CSP tier.
## Cross-origin (already handled)
diff --git a/public/accessories/presets.json b/public/accessories/presets.json
index f332e509a..0e7b95a06 100644
--- a/public/accessories/presets.json
+++ b/public/accessories/presets.json
@@ -50,6 +50,7 @@
"name": "Round Glasses",
"glbUrl": "/accessories/glasses-round.glb",
"attachBone": "Head",
+ "anchor": "face",
"thumbnail": "/accessories/thumbs/glasses-round.png"
},
{
@@ -58,6 +59,7 @@
"name": "Shades",
"glbUrl": "/accessories/glasses-shades.glb",
"attachBone": "Head",
+ "anchor": "face",
"thumbnail": "/accessories/thumbs/glasses-shades.png"
},
{
diff --git a/public/changelog.json b/public/changelog.json
index c43d02ae2..06cd26887 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-18T09:26:45.826Z",
+ "generated_at": "2026-06-18T09:47:48.090Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -380,6 +380,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-18",
+ "type": "update",
+ "title": "The x402 demo we built with IBM now runs under a locked-down security policy",
+ "summary": "The live x402 demo we made with IBM was hardened so it can be hosted on a strict corporate site. It no longer pulls fonts or the 3D model viewer from Google's CDN — both now ship with the page from three.ws — so it loads cleanly under a strict Content-Security-Policy and even inside an iframe, with no blocked requests. Paying with MetaMask on Base needs nothing but three.ws; if a locked-down host blocks the small library the Solana path loads, the page now says so plainly and the Base button keeps working. The 3D viewer also loads only once you actually forge a model, so the page opens lighter. We published the exact policy and hosting steps for IBM's web team.",
+ "link": "/ibm/x402-demo",
+ "tags": [
+ "improvement",
+ "security"
+ ]
+ },
{
"date": "2026-06-18",
"type": "update",
@@ -451,6 +462,27 @@
"improvement"
]
},
+ {
+ "date": "2026-06-18",
+ "type": "update",
+ "title": "Your agent can now pay for paid APIs from its own wallet",
+ "summary": "The wallet's new Pay tab lets your agent buy from the x402 marketplace in USDC straight from its own Solana wallet — never a shared platform account. Search the bazaar for a paid service (or paste an endpoint), see the live price and exactly what you're buying before you commit, then pay; you watch the payment get built, signed by the agent, and settled on-chain, and get the receipt with a transaction link. Every payment is checked against the agent's own spend limits first, and if the wallet is short on USDC it tells you and sends you to fund it instead of failing mid-pay. A running Payment activity list shows what the agent paid for, to whom, and when. Whenever an agent is in context, payments always come from that agent's wallet.",
+ "link": "/agents",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-18",
+ "type": "update",
+ "title": "Your agent can now trade from its own wallet — with real guardrails",
+ "summary": "Fund your agent's wallet and let it buy and sell pump.fun coins straight from that wallet, signed for you on the server — no wallet popup per trade. Every trade runs through the same safety checks the auto-sniper uses, now shared as one rulebook so they can never drift apart: a per-trade size cap, a rolling daily spend budget, a price-impact circuit breaker, a fee-and-rent cushion so a buy never bricks the wallet, and a kill switch to pause all trading instantly. Set those limits per agent under Limits & Safety. If a trade would cross a limit you get a clear, specific reason back instead of a failure — and a retried request can never double-spend. Graduated coins route through the AMM automatically, and every trade lands in one unified history alongside your sniper's.",
+ "link": "/agents",
+ "tags": [
+ "feature",
+ "security"
+ ]
+ },
{
"date": "2026-06-18",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index bbaf69c46..6f823eaa5 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -294,6 +294,14 @@
<category>feature</category>
<description>Walking up to the Pole Club, you used to move through the alley, the gallery, and the clubhouse completely alone. Now every room is full: each one is populated with a live crowd built from our avatars — the bundled looks plus public avatars from the gallery — grounded on the floor and moving for real. Near the entrance they lean, chill, and idle; deeper in, more of them are dancing, so the energy builds as you get closer to the stage. The crowd lines your route instead of blocking it, and the head-count scales to your device so it stays smooth on phones and goes big on desktop.</description>
</item>
+ <item>
+ <title>The x402 demo we built with IBM now runs under a locked-down security policy</title>
+ <link>https://three.ws/ibm/x402-demo</link>
+ <guid isPermaLink="false">2026-06-18:The x402 demo we built with IBM now runs under a locked-down security policy</guid>
+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>The live x402 demo we made with IBM was hardened so it can be hosted on a strict corporate site. It no longer pulls fonts or the 3D model viewer from Google's CDN — both now ship with the page from three.ws — so it loads cleanly under a strict Content-Security-Policy and even inside an iframe, with no blocked requests. Paying with MetaMask on Base needs nothing but three.ws; if a locked-down host blocks the small library the Solana path loads, the page now says so plainly and the Base button keeps working. The 3D viewer also loads only once you actually forge a model, so the page opens lighter. We published the exact policy and hosting steps for IBM's web team.</description>
+ </item>
<item>
<title>Tip a dancer for a Pole Twerk and she works the pole</title>
<link>https://three.ws/club</link>
@@ -350,6 +358,22 @@
<category>improvement</category>
<description>When an agent replied with a 3D avatar — especially while it was thinking or forging several models at once — the avatar used to float off on its own with a big empty gap, while the reasoning note and the tool buttons drifted down beside its feet. The agent now stands next to its own response: the avatar is framed tighter so it fills its space instead of hovering in the void, and its thinking note and tool calls line up with it as one tidy block. It reads as a single reply whether you're in the normal view or have a tool's details open in the side panel.</description>
</item>
+ <item>
+ <title>Your agent can now pay for paid APIs from its own wallet</title>
+ <link>https://three.ws/agents</link>
+ <guid isPermaLink="false">2026-06-18:Your agent can now pay for paid APIs from its own wallet</guid>
+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The wallet's new Pay tab lets your agent buy from the x402 marketplace in USDC straight from its own Solana wallet — never a shared platform account. Search the bazaar for a paid service (or paste an endpoint), see the live price and exactly what you're buying before you commit, then pay; you watch the payment get built, signed by the agent, and settled on-chain, and get the receipt with a transaction link. Every payment is checked against the agent's own spend limits first, and if the wallet is short on USDC it tells you and sends you to fund it instead of failing mid-pay. A running Payment activity list shows what the agent paid for, to whom, and when. Whenever an agent is in context, payments always come from that agent's wallet.</description>
+ </item>
+ <item>
+ <title>Your agent can now trade from its own wallet — with real guardrails</title>
+ <link>https://three.ws/agents</link>
+ <guid isPermaLink="false">2026-06-18:Your agent can now trade from its own wallet — with real guardrails</guid>
+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Fund your agent's wallet and let it buy and sell pump.fun coins straight from that wallet, signed for you on the server — no wallet popup per trade. Every trade runs through the same safety checks the auto-sniper uses, now shared as one rulebook so they can never drift apart: a per-trade size cap, a rolling daily spend budget, a price-impact circuit breaker, a fee-and-rent cushion so a buy never bricks the wallet, and a kill switch to pause all trading instantly. Set those limits per agent under Limits &amp; Safety. If a trade would cross a limit you get a clear, specific reason back instead of a failure — and a retried request can never double-spend. Graduated coins route through the AMM automatically, and every trade lands in one unified history alongside your sniper's.</description>
+ </item>
<item>
<title>Your AR agent now hides behind real-world objects</title>
<link>https://three.ws/features/ar</link>
diff --git a/public/features.json b/public/features.json
index 6119ac8de..d6af9b521 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-18T09:26:45.801Z",
+ "generated_at": "2026-06-18T09:47:48.078Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/agent-accessories.js b/src/agent-accessories.js
index a78499416..d61c08e4e 100644
--- a/src/agent-accessories.js
+++ b/src/agent-accessories.js
@@ -8,6 +8,7 @@
// The Empathy Layer's morph loop only iterates its own _morphTarget dict, so
// outfit morphs set here are never clobbered by emotion blending.
+import { Box3, Group, Quaternion, Vector3 } from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { resolveURI } from './ipfs.js';
import { collectSlotTargets } from './avatar-wardrobe.js';
@@ -179,7 +180,14 @@ export class AccessoryManager {
return;
}
- const obj = gltf.scene;
+ // Anchored props (currently eyewear) get a placement pass that recentres,
+ // auto-fits and offsets the asset to the right facial landmark — source
+ // GLBs vary (some authored at the head-bone origin, some lying flat), so a
+ // raw bone.add() lands them inside the cheeks. Props without an anchor keep
+ // the legacy raw attach (hats/earrings already bake their offset into the GLB).
+ const obj = preset.anchor
+ ? _placeAnchoredProp(gltf.scene, bone, this.viewer?.content, preset.anchor)
+ : gltf.scene;
bone.add(obj);
this._applied.set(preset.id, { preset, object: obj });
this.viewer?.invalidate?.();
@@ -235,6 +243,72 @@ function _findBone(model, boneName) {
return found;
}
+// Placement ratios are expressed against the avatar's overall height so the same
+// numbers work whether the loaded GLB is a ~1.8 m ReadyPlayerMe body or a custom
+// avatar normalised to a different scale. Calibrated for the 'face' (eyewear)
+// anchor: width ≈ a human face, lifted from the head-bone origin to the eye line
+// and pushed forward to the front of the face.
+const FACE_WIDTH_RATIO = 0.083; // ~0.15 m at 1.8 m tall
+const FACE_UP_RATIO = 0.033; // head-bone origin → eye line
+const FACE_FWD_RATIO = 0.044; // head-bone origin → face front
+const DEFAULT_HEIGHT_M = 1.8;
+
+/**
+ * Recentre, auto-fit and offset an accessory GLB so it sits on the correct facial
+ * landmark, then return it wrapped in a holder whose transform is expressed in the
+ * bone's local space (the caller parents the holder to the bone). The holder is
+ * kept world-upright and world-scaled regardless of the bone's own frame, so the
+ * prop tracks head movement without inheriting bone rotation/scale skew.
+ *
+ * @param {import('three').Object3D} scene loaded GLB scene (mutated in place)
+ * @param {import('three').Bone} bone attach bone (already resolved)
+ * @param {import('three').Object3D|null} root avatar root, for height estimation
+ * @param {'face'} anchor
+ * @returns {import('three').Group}
+ */
+function _placeAnchoredProp(scene, bone, root, anchor) {
+ if (root) root.updateMatrixWorld(true);
+ const height = root
+ ? new Box3().setFromObject(root).getSize(new Vector3()).y || DEFAULT_HEIGHT_M
+ : DEFAULT_HEIGHT_M;
+
+ const model = scene;
+
+ // 1. Fit width so any source asset matches this avatar's face.
+ let box = new Box3().setFromObject(model);
+ let size = box.getSize(new Vector3());
+ const span = Math.max(size.x, size.z) || 1;
+ model.scale.setScalar((FACE_WIDTH_RATIO * height) / span);
+
+ // 2. Stand up props authored lying flat (e.g. shades modelled in the XZ plane).
+ box = new Box3().setFromObject(model);
+ size = box.getSize(new Vector3());
+ if (size.y < size.x * 0.3) {
+ model.rotateX(-Math.PI / 2);
+ }
+
+ // 3. Recentre the mesh on its own midpoint so the holder origin is its pivot.
+ box = new Box3().setFromObject(model);
+ const center = box.getCenter(new Vector3());
+ model.position.sub(center);
+
+ const holder = new Group();
+ holder.add(model);
+
+ // 4. Offset from the head-bone origin to the eye line, in world axes, then map
+ // into the bone's local frame and cancel the bone's rotation + scale so the
+ // prop renders upright at true scale.
+ const target = bone
+ .getWorldPosition(new Vector3())
+ .add(new Vector3(0, FACE_UP_RATIO * height, FACE_FWD_RATIO * height));
+ holder.position.copy(bone.worldToLocal(target));
+ holder.quaternion.copy(bone.getWorldQuaternion(new Quaternion()).invert());
+ const boneScale = bone.getWorldScale(new Vector3());
+ holder.scale.set(1 / (boneScale.x || 1), 1 / (boneScale.y || 1), 1 / (boneScale.z || 1));
+
+ return holder;
+}
+
/**
* Set morph target influences from a name→weight map.
* Returns a receipts array that _zeroMorphs() can use to undo.
diff --git a/src/agent-wallet-hub/tabs/pay.js b/src/agent-wallet-hub/tabs/pay.js
index 9ad780939..85d24674c 100644
--- a/src/agent-wallet-hub/tabs/pay.js
+++ b/src/agent-wallet-hub/tabs/pay.js
@@ -1,18 +1,622 @@
/**
- * Agent Wallet hub — Pay tab (placeholder; replaced by epic task 08).
+ * Agent Wallet hub — Pay tab (fully built).
*
- * Owner-only: paying for services spends the agent's own funds.
- * Task 08 ships in-product x402 pay from the per-agent wallet + payment activity.
+ * Owner-only. Discover an x402 service in the bazaar (or paste an endpoint),
+ * fetch its live price, and pay it in USDC straight from the agent's OWN Solana
+ * wallet — never the shared platform wallet. Streams the payment lifecycle,
+ * shows the receipt, and lists the agent's x402 payment history from the custody
+ * ledger so every spend is auditable: what was paid, to whom, for what, when.
+ *
+ * Funding-aware: before paying it checks the agent's USDC balance and, when
+ * short, routes the owner to the Deposit tab instead of attempting a doomed pay.
+ *
+ * All real: bazaar search (/api/bazaar/search), live 402 negotiation + Solana
+ * settlement (/api/x402-pay), holdings + custody reads. No mocks, no fake data.
*/
-import { registerPlaceholderTab } from './_placeholder.js';
+import { registerWalletTab } from '../registry.js';
+import {
+ searchBazaarServices,
+ previewX402,
+ payX402Stream,
+ fetchAgentUsdc,
+ fetchX402Activity,
+} from '../../agent-x402-pay.js';
+import { formatUsd, timeAgo, explorerTxUrl } from '../util.js';
+
+const SEARCH_DEBOUNCE_MS = 350;
+
+const PAY_STYLE_ID = 'awh-pay-style';
+const PAY_STYLE = `
+.awh-pay-search { display: flex; gap: var(--space-2,8px); }
+.awh-pay-input { flex: 1 1 auto; min-width: 0; font: inherit; font-size: var(--text-md,.8125rem); color: var(--ink,#e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); padding: 8px 12px; }
+.awh-pay-input:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: var(--focus-ring-offset,2px); }
+.awh-pay-hint { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); margin: var(--space-3,12px) 0 0; }
+.awh-pay-note { font-size: var(--text-sm,.764rem); color: var(--warn,#fbbf24); margin: 0 0 var(--space-3,12px); }
+
+.awh-svc-list { list-style: none; margin: var(--space-3,12px) 0 0; padding: 0; display: flex; flex-direction: column; gap: var(--space-2,8px); }
+.awh-svc { display: flex; align-items: center; gap: var(--space-3,12px); padding: var(--space-3,12px); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); background: var(--surface-1, rgba(255,255,255,.03)); transition: border-color var(--duration-fast,140ms), background var(--duration-fast,140ms); }
+.awh-svc:hover { border-color: var(--stroke-strong, rgba(255,255,255,.14)); background: var(--surface-2, rgba(255,255,255,.05)); }
+.awh-svc-main { min-width: 0; flex: 1 1 auto; }
+.awh-svc-name { font-size: var(--text-md,.8125rem); font-weight: 600; color: var(--ink-bright,#fff); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.awh-svc-desc { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); margin-top: 2px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
+.awh-svc-host { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); margin-top: 3px; }
+.awh-svc-side { flex: none; display: flex; flex-direction: column; align-items: flex-end; gap: 6px; }
+.awh-svc-price { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); }
+
+.awh-pay-sheet-top { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3,12px); margin-bottom: var(--space-3,12px); }
+.awh-pay-back { appearance: none; font: inherit; font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); background: none; border: none; cursor: pointer; padding: 0; }
+.awh-pay-back:hover { color: var(--ink,#e8e8e8); }
+.awh-pay-rows { display: flex; flex-direction: column; gap: var(--space-2,8px); margin: var(--space-3,12px) 0; }
+.awh-pay-row { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-3,12px); font-size: var(--text-sm,.764rem); }
+.awh-pay-row dt { color: var(--ink-dim,#888); margin: 0; }
+.awh-pay-row dd { margin: 0; color: var(--ink,#e8e8e8); text-align: right; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
+.awh-pay-price { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-lg,1.236rem); font-weight: 700; color: var(--ink-bright,#fff); }
+.awh-pay-body-label { display: block; font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-dim,#888); margin: var(--space-3,12px) 0 6px; }
+.awh-pay-textarea { width: 100%; box-sizing: border-box; font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); padding: 8px 10px; min-height: 88px; resize: vertical; }
+.awh-pay-actions { display: flex; gap: var(--space-2,8px); margin-top: var(--space-4,16px); }
+.awh-pay-fund { border: 1px solid color-mix(in srgb, var(--warn,#fbbf24) 35%, transparent); background: color-mix(in srgb, var(--warn,#fbbf24) 10%, transparent); border-radius: var(--radius-md,10px); padding: var(--space-3,12px); margin-top: var(--space-3,12px); }
+.awh-pay-fund p { margin: 0 0 var(--space-2,8px); font-size: var(--text-sm,.764rem); color: var(--warn,#fbbf24); }
-registerPlaceholderTab({
+.awh-pay-flow { list-style: none; margin: var(--space-3,12px) 0 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
+.awh-pay-step { display: flex; align-items: center; gap: 10px; font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); }
+.awh-pay-step::before { content: '✓'; flex: none; width: 18px; height: 18px; border-radius: 50%; display: grid; place-items: center; font-size: 11px; background: color-mix(in srgb, var(--success,#4ade80) 18%, transparent); color: var(--success,#4ade80); }
+.awh-pay-step.is-active::before { content: ''; background: none; border: 2px solid var(--ink-dim,#888); border-top-color: var(--ink-bright,#fff); animation: awh-spin .7s linear infinite; }
+.awh-pay-step .detail { color: var(--ink-dim,#888); }
+.awh-pay-receipt { border: 1px solid color-mix(in srgb, var(--success,#4ade80) 30%, transparent); background: color-mix(in srgb, var(--success,#4ade80) 8%, transparent); border-radius: var(--radius-md,10px); padding: var(--space-3,12px); margin-top: var(--space-3,12px); }
+.awh-pay-result { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); white-space: pre-wrap; word-break: break-word; max-height: 180px; overflow: auto; margin: var(--space-2,8px) 0 0; padding: var(--space-2,8px); background: var(--surface-2, rgba(255,255,255,.05)); border-radius: var(--radius-sm,6px); }
+.awh-pay-err { color: var(--danger,#f87171); font-size: var(--text-sm,.764rem); margin-top: var(--space-3,12px); }
+
+.awh-act2-list { list-style: none; margin: 0; padding: 0; }
+.awh-act2-row { display: flex; align-items: center; gap: var(--space-3,12px); padding: 9px 0; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.06)); font-size: var(--text-sm,.764rem); }
+.awh-act2-row:last-child { border-bottom: none; }
+.awh-act2-main { flex: 1 1 auto; min-width: 0; }
+.awh-act2-svc { color: var(--ink,#e8e8e8); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.awh-act2-meta { color: var(--ink-dim,#888); font-size: var(--text-2xs,.6875rem); margin-top: 2px; }
+.awh-act2-amt { flex: none; font-family: var(--font-mono, ui-monospace, monospace); color: var(--ink,#e8e8e8); text-align: right; }
+.awh-act2-status { font-size: var(--text-2xs,.6875rem); }
+.awh-act2-status.is-pending { color: var(--warn,#fbbf24); }
+
+.awh-pay-skel span { display: block; height: 16px; border-radius: var(--radius-sm,6px); background: var(--surface-2, rgba(255,255,255,.05)); animation: awh-skel 1.4s ease-in-out infinite; margin-bottom: 10px; }
+.awh-pay-skel span:nth-child(2){ width: 70%; } .awh-pay-skel span:nth-child(3){ width: 85%; }
+@keyframes awh-spin { to { transform: rotate(360deg); } }
+@media (prefers-reduced-motion: reduce){ .awh-pay-step.is-active::before, .awh-pay-skel span { animation: none; } }
+`;
+function injectPayStyle() {
+ if (typeof document === 'undefined' || document.getElementById(PAY_STYLE_ID)) return;
+ const tag = document.createElement('style');
+ tag.id = PAY_STYLE_ID;
+ tag.textContent = PAY_STYLE;
+ document.head.appendChild(tag);
+}
+
+function hostOf(u) {
+ try {
+ return new URL(u).host;
+ } catch {
+ return u;
+ }
+}
+
+// First Solana accept's human price for a bazaar resource card.
+function solanaPriceLabel(resource) {
+ const sol = (resource.accepts || []).find((a) => a.family === 'solana');
+ return sol?.priceLabel || resource.minPriceLabel || '';
+}
+
+registerWalletTab({
id: 'pay',
label: 'Pay',
order: 50,
ownerOnly: true,
- icon: '⌁',
- title: 'Pay for services',
- body: 'Pay x402 paid-API endpoints in USDC straight from the agent’s wallet — no shared platform wallet — with a running ledger of what the agent has paid for. This panel is being wired up now.',
+ mount({ panel, ctx }) {
+ injectPayStyle();
+ const { escapeHtml, shortAddress, copyToClipboard, toast } = ctx;
+ // x402 here settles on Solana mainnet USDC regardless of the hub's network
+ // toggle (the bazaar + facilitator are mainnet). We surface a note when the
+ // selector is on devnet rather than silently paying on a different network.
+ const PAY_NETWORK = 'mainnet';
+
+ let debounceTimer = null;
+ let detachNet = null;
+ let destroyed = false;
+ let payAbort = false; // set on destroy so a late stream result is ignored
+
+ const state = {
+ query: '',
+ searching: false,
+ searched: false,
+ services: [],
+ searchError: null,
+ selected: null, // { url, method, serviceName, description, bodyText, hasBody }
+ previewing: false,
+ preview: null,
+ previewError: null,
+ usdc: null,
+ depositAddress: null,
+ paying: false,
+ progress: [], // [{ key, label, detail, active }]
+ payResult: null,
+ payError: null,
+ activity: null,
+ activityLoaded: false,
+ activityError: null,
+ };
+
+ // ── element hosts (rendered once; sub-regions update in place) ──────────
+ function shell() {
+ const devnetNote =
+ ctx.getNetwork() === 'devnet'
+ ? `<p class="awh-pay-note">x402 services settle on Solana mainnet — this pays from the agent's mainnet USDC.</p>`
+ : '';
+ panel.innerHTML = `
+ <div class="awh-card">
+ <h2 class="awh-card-h">Pay a service</h2>
+ ${devnetNote}
+ <div data-host="main"></div>
+ </div>
+ <div class="awh-card">
+ <h2 class="awh-card-h">Payment activity</h2>
+ <div data-host="activity"></div>
+ </div>
+ `;
+ renderMain();
+ renderActivity();
+ }
+
+ const mainHost = () => panel.querySelector('[data-host="main"]');
+ const resultsHost = () => panel.querySelector('[data-host="results"]');
+ const flowHost = () => panel.querySelector('[data-host="payflow"]');
+ const activityHost = () => panel.querySelector('[data-host="activity"]');
+
+ // ── discover ────────────────────────────────────────────────────────────
+ function renderMain() {
+ const host = mainHost();
+ if (!host) return;
+ if (state.selected) {
+ host.innerHTML = renderPaySheet();
+ wirePaySheet();
+ return;
+ }
+ host.innerHTML = `
+ <form class="awh-pay-search" data-form="search" autocomplete="off">
+ <input class="awh-pay-input" data-input="query" type="search"
+ placeholder="Search the x402 bazaar (e.g. weather, intel, data)…"
+ aria-label="Search x402 services" value="${escapeHtml(state.query)}" />
+ <button class="awh-btn awh-btn--primary" type="submit">Search</button>
+ </form>
+ <p class="awh-pay-hint">Browse Solana-payable services, or
+ <a href="#" data-act="paste">paste an endpoint URL</a>.</p>
+ <div data-host="results">${renderResultsInner()}</div>
+ `;
+ const input = host.querySelector('[data-input="query"]');
+ input?.addEventListener('input', () => {
+ state.query = input.value;
+ clearTimeout(debounceTimer);
+ debounceTimer = setTimeout(() => runSearch(), SEARCH_DEBOUNCE_MS);
+ });
+ }
+
+ function renderResultsInner() {
+ if (state.searching) {
+ return `<div class="awh-pay-skel" aria-busy="true"><span></span><span></span><span></span></div>`;
+ }
+ if (state.searchError) {
+ return `<div class="awh-empty">Could not reach the bazaar. <button class="awh-btn awh-bal-mini" type="button" data-act="retry-search">Retry</button></div>`;
+ }
+ if (!state.searched) {
+ return `<p class="awh-pay-hint">Search above to find a paid API to call from this agent's wallet.</p>`;
+ }
+ if (!state.services.length) {
+ return `<div class="awh-empty">No Solana-payable services found${state.query ? ` for “${escapeHtml(state.query)}”` : ''}. Try another search, or paste an endpoint URL above.</div>`;
+ }
+ return `<ul class="awh-svc-list">${state.services
+ .map((s, i) => {
+ const price = solanaPriceLabel(s);
+ const name = s.serviceName || hostOf(s.resource);
+ return `<li class="awh-svc">
+ <div class="awh-svc-main">
+ <div class="awh-svc-name" title="${escapeHtml(name)}">${escapeHtml(name)}</div>
+ ${s.description ? `<div class="awh-svc-desc">${escapeHtml(s.description)}</div>` : ''}
+ <div class="awh-svc-host">${escapeHtml(hostOf(s.resource))}</div>
+ </div>
+ <div class="awh-svc-side">
+ ${price ? `<span class="awh-svc-price">${escapeHtml(price)}</span>` : ''}
+ <button class="awh-btn awh-btn--primary awh-bal-mini" type="button" data-act="select" data-i="${i}">Pay</button>
+ </div>
+ </li>`;
+ })
+ .join('')}</ul>`;
+ }
+
+ function renderResults() {
+ const host = resultsHost();
+ if (host) host.innerHTML = renderResultsInner();
+ }
+
+ async function runSearch() {
+ if (destroyed) return;
+ const q = state.query.trim();
+ state.searching = true;
+ state.searchError = null;
+ renderResults();
+ try {
+ const { resources } = await searchBazaarServices(q, { limit: 24 });
+ if (destroyed) return;
+ // Only keep entries that actually expose a Solana accept to pay.
+ state.services = resources.filter((r) => (r.accepts || []).some((a) => a.family === 'solana'));
+ state.searched = true;
+ } catch (e) {
+ state.searchError = e?.message || 'search failed';
+ } finally {
+ state.searching = false;
+ renderResults();
+ }
+ }
+
+ // ── pay sheet ─────────────────────────────────────────────────────────
+ function selectFromService(resource) {
+ const sol = (resource.accepts || []).find((a) => a.family === 'solana');
+ const method = (resource.input?.method || resource.method || 'GET').toUpperCase();
+ const hasBody = ['POST', 'PUT', 'PATCH'].includes(method);
+ const bodyExample = resource.input?.body;
+ state.selected = {
+ url: resource.resource,
+ method,
+ hasBody,
+ bodyText: hasBody && bodyExample ? JSON.stringify(bodyExample, null, 2) : '',
+ serviceName: resource.serviceName || hostOf(resource.resource),
+ description: resource.description || '',
+ priceLabel: sol?.priceLabel || '',
+ };
+ resetPayState();
+ renderMain();
+ runPreview();
+ }
+
+ function selectFromUrl(url) {
+ state.selected = {
+ url,
+ method: 'GET',
+ hasBody: false,
+ bodyText: '',
+ serviceName: hostOf(url),
+ description: '',
+ priceLabel: '',
+ };
+ resetPayState();
+ renderMain();
+ runPreview();
+ }
+
+ function resetPayState() {
+ state.previewing = false;
+ state.preview = null;
+ state.previewError = null;
+ state.usdc = null;
+ state.paying = false;
+ state.progress = [];
+ state.payResult = null;
+ state.payError = null;
+ }
+
+ function backToServices() {
+ state.selected = null;
+ resetPayState();
+ renderMain();
+ }
+
+ async function runPreview() {
+ const sel = state.selected;
+ if (!sel) return;
+ state.previewing = true;
+ state.previewError = null;
+ renderMain();
+ const [prev, bal] = await Promise.allSettled([
+ previewX402({ agentId: ctx.agentId, url: sel.url, method: sel.method, body: bodyForRequest() }),
+ fetchAgentUsdc(ctx.agentId, PAY_NETWORK),
+ ]);
+ if (destroyed || state.selected !== sel) return;
+ if (prev.status === 'fulfilled') {
+ state.preview = prev.value;
+ state.previewError = null;
+ } else {
+ state.previewError = prev.reason?.message || 'could not load the price';
+ }
+ state.usdc = bal.status === 'fulfilled' ? bal.value.usdc : null;
+ state.depositAddress = bal.status === 'fulfilled' ? bal.value.address : null;
+ state.previewing = false;
+ renderMain();
+ }
+
+ function bodyForRequest() {
+ const sel = state.selected;
+ if (!sel || !sel.hasBody || !sel.bodyText.trim()) return undefined;
+ try {
+ return JSON.parse(sel.bodyText);
+ } catch {
+ return sel.bodyText; // send as-is; the server forwards it
+ }
+ }
+
+ function renderPaySheet() {
+ const sel = state.selected;
+ const head = `
+ <div class="awh-pay-sheet-top">
+ <button class="awh-pay-back" type="button" data-act="back">← Back to services</button>
+ </div>
+ <div class="awh-svc-name" title="${escapeHtml(sel.serviceName)}">${escapeHtml(sel.serviceName)}</div>
+ <div class="awh-svc-host">${escapeHtml(hostOf(sel.url))}</div>
+ ${sel.description ? `<p class="awh-svc-desc" style="margin-top:6px;-webkit-line-clamp:4">${escapeHtml(sel.description)}</p>` : ''}`;
+
+ if (state.payResult) return head + renderReceipt();
+ if (state.paying) return head + renderFlow();
+
+ if (state.previewing) {
+ return head + `<div class="awh-pay-skel" aria-busy="true" style="margin-top:12px"><span></span><span></span><span></span></div>`;
+ }
+ if (state.previewError) {
+ return head + `<div class="awh-pay-err">${escapeHtml(state.previewError)}</div>
+ <div class="awh-pay-actions"><button class="awh-btn" type="button" data-act="retry-preview">Try again</button></div>`;
+ }
+ const p = state.preview;
+ if (p && p.requires_payment === false) {
+ return head + `<p class="awh-pay-hint">This endpoint responded without asking for payment — there is nothing to pay. You can call it directly.</p>
+ <div class="awh-pay-actions"><button class="awh-btn" type="button" data-act="back">Back</button></div>`;
+ }
+ if (p && p.payable === false) {
+ const nets = Array.isArray(p.networks) && p.networks.length ? p.networks.join(', ') : 'another network';
+ const why = p.code === 'no_solana_accept'
+ ? `This service only accepts ${escapeHtml(nets)}. Agent wallets pay in Solana USDC, so it can't be paid from here.`
+ : `This service didn't advertise a Solana fee payer, so it can't be paid from here.`;
+ return head + `<div class="awh-pay-err">${why}</div>
+ <div class="awh-pay-actions"><button class="awh-btn" type="button" data-act="back">Back to services</button></div>`;
+ }
+
+ // Ready to confirm.
+ const price = p?.price_usdc;
+ const priceStr = price != null ? `${price.toFixed(price < 1 ? 4 : 2)} USDC` : (sel.priceLabel || '—');
+ const usdcStr = state.usdc == null ? 'unavailable' : `${state.usdc.toFixed(state.usdc < 1 ? 4 : 2)} USDC`;
+ const insufficient = price != null && state.usdc != null && state.usdc < price;
+ const bodyEditor = sel.hasBody
+ ? `<label class="awh-pay-body-label" for="awh-pay-body">Request body (JSON)</label>
+ <textarea class="awh-pay-textarea" id="awh-pay-body" data-input="body" spellcheck="false">${escapeHtml(sel.bodyText)}</textarea>`
+ : '';
+
+ const fundBlock = insufficient
+ ? `<div class="awh-pay-fund">
+ <p>This agent has ${escapeHtml(usdcStr)} but the service costs ${escapeHtml(priceStr)}. Fund the wallet first.</p>
+ ${state.depositAddress ? `<div class="awh-bal-addr"><span class="awh-mono" title="${escapeHtml(state.depositAddress)}">${escapeHtml(shortAddress(state.depositAddress, 6, 6))}</span><button class="awh-btn awh-bal-mini" type="button" data-act="copy-addr">Copy</button></div>` : ''}
+ <div class="awh-pay-actions"><button class="awh-btn awh-btn--primary" type="button" data-act="fund">Fund wallet →</button></div>
+ </div>`
+ : '';
+
+ return head + `
+ <dl class="awh-pay-rows">
+ <div class="awh-pay-row"><dt>Price</dt><dd class="awh-pay-price">${escapeHtml(priceStr)}</dd></div>
+ <div class="awh-pay-row"><dt>Pay to</dt><dd class="awh-mono">${escapeHtml(shortAddress(p?.payTo || '', 6, 6))}</dd></div>
+ <div class="awh-pay-row"><dt>Method</dt><dd>${escapeHtml(sel.method)}</dd></div>
+ <div class="awh-pay-row"><dt>Agent balance</dt><dd>${escapeHtml(usdcStr)}</dd></div>
+ </dl>
+ ${bodyEditor}
+ ${fundBlock}
+ <div class="awh-pay-actions">
+ <button class="awh-btn awh-btn--primary" type="button" data-act="pay" ${insufficient || !p?.payable ? 'disabled' : ''}>Pay ${escapeHtml(priceStr)}</button>
+ <button class="awh-btn" type="button" data-act="back">Cancel</button>
+ </div>
+ <div data-host="payflow"></div>`;
+ }
+
+ function renderFlow() {
+ return `<ul class="awh-pay-flow">${state.progress
+ .map(
+ (s) => `<li class="awh-pay-step ${s.active ? 'is-active' : ''}">${escapeHtml(s.label)}${s.detail ? ` <span class="detail">· ${escapeHtml(s.detail)}</span>` : ''}</li>`,
+ )
+ .join('')}</ul>${state.payError ? `<div class="awh-pay-err">${escapeHtml(state.payError)}</div><div class="awh-pay-actions"><button class="awh-btn" type="button" data-act="retry-preview">Try again</button><button class="awh-btn" type="button" data-act="back">Back</button></div>` : ''}`;
+ }
+
+ function renderReceipt() {
+ const r = state.payResult;
+ const pay = r.payment || {};
+ let resultStr = '';
+ try {
+ resultStr = typeof r.result === 'string' ? r.result : JSON.stringify(r.result, null, 2);
+ } catch {
+ resultStr = String(r.result ?? '');
+ }
+ if (resultStr.length > 1500) resultStr = resultStr.slice(0, 1500) + '\n…';
+ const amt = pay.amount != null ? `${(Number(pay.amount) / 1e6).toFixed(Number(pay.amount) / 1e6 < 1 ? 4 : 2)} USDC` : '';
+ return `
+ <div class="awh-pay-receipt">
+ <div class="awh-svc-name" style="color:var(--success,#4ade80)">Paid ✓ ${escapeHtml(amt)}</div>
+ <dl class="awh-pay-rows" style="margin-bottom:0">
+ <div class="awh-pay-row"><dt>Paid to</dt><dd class="awh-mono">${escapeHtml(shortAddress(pay.payTo || '', 6, 6))}</dd></div>
+ ${pay.tx ? `<div class="awh-pay-row"><dt>Transaction</dt><dd><a class="awh-mono awh-act-sig" href="${escapeHtml(pay.explorer || explorerTxUrl(pay.tx, PAY_NETWORK))}" target="_blank" rel="noopener">${escapeHtml(shortAddress(pay.tx, 6, 6))} ↗</a></dd></div>` : ''}
+ </dl>
+ </div>
+ ${resultStr ? `<div class="awh-pay-body-label">Service response</div><pre class="awh-pay-result">${escapeHtml(resultStr)}</pre>` : ''}
+ <div class="awh-pay-actions">
+ <button class="awh-btn awh-btn--primary" type="button" data-act="back">Pay another</button>
+ </div>`;
+ }
+
+ function wirePaySheet() {
+ const sel = state.selected;
+ if (!sel) return;
+ const body = mainHost()?.querySelector('[data-input="body"]');
+ body?.addEventListener('input', () => {
+ sel.bodyText = body.value;
+ });
+ }
+
+ async function runPay() {
+ const sel = state.selected;
+ const p = state.preview;
+ if (!sel || !p || !p.payable) return;
+ state.paying = true;
+ state.payError = null;
+ state.progress = [{ key: 'start', label: 'Submitting payment…', active: true }];
+ renderMain();
+
+ const setStep = (key, label, detail) => {
+ // Mark the previous active step done, append the new one as active.
+ state.progress = state.progress.map((s) => ({ ...s, active: false }));
+ state.progress.push({ key, label, detail, active: true });
+ const host = flowHost();
+ if (host) host.innerHTML = renderFlow();
+ };
+
+ try {
+ const result = await payX402Stream(
+ {
+ agentId: ctx.agentId,
+ url: sel.url,
+ method: sel.method,
+ body: bodyForRequest(),
+ serviceLabel: sel.serviceName,
+ },
+ (event, data) => {
+ if (destroyed || payAbort) return;
+ if (event === 'challenge') {
+ const price = data?.price_usdc;
+ setStep('challenge', 'Price confirmed', price != null ? `${price.toFixed(price < 1 ? 4 : 2)} USDC` : '');
+ } else if (event === 'built') {
+ setStep('built', 'Payment signed by agent wallet');
+ } else if (event === 'settled') {
+ setStep('settled', 'Settled on-chain', data?.tx ? shortAddress(data.tx, 6, 6) : '');
+ }
+ },
+ );
+ if (destroyed || payAbort) return;
+ state.progress = state.progress.map((s) => ({ ...s, active: false }));
+ state.payResult = result;
+ state.paying = false;
+ renderMain();
+ toast('Payment complete');
+ // Reflect the spend immediately.
+ loadActivity();
+ fetchAgentUsdc(ctx.agentId, PAY_NETWORK)
+ .then((b) => { state.usdc = b.usdc; })
+ .catch(() => {});
+ } catch (e) {
+ if (destroyed || payAbort) return;
+ state.progress = state.progress.map((s) => ({ ...s, active: false }));
+ state.payError = e?.message || 'payment failed';
+ state.paying = false;
+ renderMain();
+ }
+ }
+
+ // ── activity ────────────────────────────────────────────────────────────
+ function renderActivityInner() {
+ if (!state.activityLoaded) {
+ return `<div class="awh-pay-skel" aria-busy="true"><span></span><span></span></div>`;
+ }
+ if (state.activityError) {
+ return `<div class="awh-empty">Could not load payment activity. <button class="awh-btn awh-bal-mini" type="button" data-act="retry-activity">Retry</button></div>`;
+ }
+ const rows = state.activity || [];
+ if (!rows.length) {
+ return `<div class="awh-empty">No payments yet. Services you pay for from this wallet appear here.</div>`;
+ }
+ return `<ul class="awh-act2-list">${rows
+ .map((e) => {
+ const svc = e.meta?.service || (e.meta?.url ? hostOf(e.meta.url) : null) || (e.destination ? shortAddress(e.destination, 4, 4) : 'x402 service');
+ const usd = e.usd != null ? formatUsd(e.usd) : null;
+ const when = e.created_at ? timeAgo(Math.floor(new Date(e.created_at).getTime() / 1000)) : '';
+ const statusCls = e.status === 'pending' ? 'is-pending' : '';
+ const statusTxt = e.status && e.status !== 'confirmed' && e.status !== 'ok' ? e.status : '';
+ return `<li class="awh-act2-row">
+ <div class="awh-act2-main">
+ <div class="awh-act2-svc" title="${escapeHtml(e.meta?.url || svc)}">${escapeHtml(svc)}</div>
+ <div class="awh-act2-meta">${e.destination ? `to ${escapeHtml(shortAddress(e.destination, 4, 4))} · ` : ''}${escapeHtml(when)}${statusTxt ? ` · <span class="awh-act2-status ${statusCls}">${escapeHtml(statusTxt)}</span>` : ''}</div>
+ </div>
+ ${e.signature ? `<a class="awh-act2-amt awh-act-sig" href="${escapeHtml(e.explorer || explorerTxUrl(e.signature, e.network || PAY_NETWORK))}" target="_blank" rel="noopener">${usd ? escapeHtml(usd) : escapeHtml(shortAddress(e.signature, 4, 4))} ↗</a>` : `<span class="awh-act2-amt">${usd ? escapeHtml(usd) : '—'}</span>`}
+ </li>`;
+ })
+ .join('')}</ul>`;
+ }
+
+ function renderActivity() {
+ const host = activityHost();
+ if (host) host.innerHTML = renderActivityInner();
+ }
+
+ async function loadActivity() {
+ try {
+ const items = await fetchX402Activity(ctx.agentId, PAY_NETWORK, 25);
+ if (destroyed) return;
+ state.activity = items;
+ state.activityError = null;
+ } catch (e) {
+ state.activityError = e?.message || 'activity_error';
+ } finally {
+ state.activityLoaded = true;
+ renderActivity();
+ }
+ }
+
+ // ── delegated interactions ──────────────────────────────────────────────
+ panel.addEventListener('submit', (e) => {
+ if (e.target?.dataset?.form === 'search') {
+ e.preventDefault();
+ clearTimeout(debounceTimer);
+ runSearch();
+ }
+ });
+
+ panel.addEventListener('click', async (e) => {
+ const act = e.target?.closest?.('[data-act]')?.dataset?.act;
+ if (!act) return;
+ if (act === 'select') {
+ const i = Number(e.target.closest('[data-act]').dataset.i);
+ const svc = state.services[i];
+ if (svc) selectFromService(svc);
+ } else if (act === 'paste') {
+ e.preventDefault();
+ const url = window.prompt('Paste the x402 endpoint URL to pay:');
+ if (url && url.trim()) selectFromUrl(url.trim());
+ } else if (act === 'back') {
+ backToServices();
+ } else if (act === 'retry-preview') {
+ state.payError = null;
+ runPreview();
+ } else if (act === 'pay') {
+ runPay();
+ } else if (act === 'fund') {
+ ctx.openTab?.('deposit');
+ } else if (act === 'copy-addr') {
+ const ok = await copyToClipboard(state.depositAddress);
+ toast(ok ? 'Address copied' : 'Copy failed — select it manually');
+ } else if (act === 'retry-search') {
+ runSearch();
+ } else if (act === 'retry-activity') {
+ state.activityLoaded = false;
+ renderActivity();
+ loadActivity();
+ }
+ });
+
+ // Network toggle only affects the devnet note here (x402 is mainnet).
+ detachNet = ctx.onNetworkChange(() => {
+ if (!state.selected) shell();
+ });
+
+ shell();
+
+ return {
+ onShow() {
+ if (!state.activityLoaded) loadActivity();
+ },
+ onHide() {
+ clearTimeout(debounceTimer);
+ },
+ destroy() {
+ destroyed = true;
+ payAbort = true;
+ clearTimeout(debounceTimer);
+ detachNet?.();
+ },
+ };
+ },
});
diff --git a/tasks/agent-wallet-trading/03-agent-wallet-trade-endpoint.md b/tasks/agent-wallet-trading/03-agent-wallet-trade-endpoint.md
deleted file mode 100644
index 723a7e3ca..000000000
--- a/tasks/agent-wallet-trading/03-agent-wallet-trade-endpoint.md
+++ /dev/null
@@ -1,113 +0,0 @@
-# Task: Authenticated "trade from the agent wallet" endpoint + shared guardrail module
-
-## Context
-
-Pump.fun trading is real, but the product path is **user-signed**: the client
-provides `wallet_address`, the user signs with their own external wallet, and the
-server only verifies the signature after the fact
-(`api/pump/[action].js` buy/sell prep+confirm, verify-after-sign at `:524`). The
-**only** code that signs a pump.fun trade from the agent's own custodial wallet is
-the sniper worker (`workers/agent-sniper/executor.js`), which loads the agent
-keypair (`keys.js:25` → `agent_identities.meta.encrypted_solana_secret`), builds
-buy/sell instructions (`api/_lib/pump.js:130`, `api/_lib/pump-swap-ix.js`), signs a
-v0 tx (`trade-client.js:29`), and enforces serious guardrails first
-(`executor.js:51-85`: idempotency lock, daily budget, per-trade cap, concurrency,
-price-impact breaker, SOL fee headroom).
-
-For the user's flow — fund the agent wallet, then have the agent trade from it —
-we need that same custodial signing exposed as an authenticated, owner-only API,
-with the guardrails shared (not duplicated) between this discretionary path and the
-sniper. This is the security-critical core of the epic.
-
-## Goal
-
-`POST /api/agents/:id/trade` (owner-authenticated) that buys/sells a pump.fun token
-**from the agent's own wallet**, server-signed, reusing the exact instruction
-builders and a **shared guardrail module** extracted from the sniper executor.
-Real on-chain execution, idempotent, fully guarded, audit-logged.
-
-## Files to Read First
-
-- `workers/agent-sniper/executor.js:46-206` — `executeBuy`/`executeSell`, guardrail
- sequence (`:51-85`), idempotency `INSERT…ON CONFLICT`, PnL recording, graduation
- catch (`:161`)
-- `workers/agent-sniper/keys.js:25-45` — agent keypair loading (TTL cache)
-- `workers/agent-sniper/trade-client.js:29-60` — `signAndSend` v0 tx flow
-- `api/_lib/pump.js:130-137`, `api/_lib/pump-swap-ix.js` — buy/sell instruction builders
-- `api/pump/[action].js` — existing buy/sell prep+confirm, slippage handling,
- fee-recipient routing, quote helpers (reuse, don't re-derive)
-- `api/_lib/agent-wallet.js:419` — `recoverSolanaAgentKeypair` (the only decrypt path)
-- `api/_lib/agent-pumpfun.js:26` — RPC failover connection
-- Auth helper used elsewhere (`requireAuth`) and the audit-log helper used by
- `recoverSolanaAgentKeypair`
-
-## What to Build / Do
-
-1. **Extract a shared guardrail module** (e.g. `api/_lib/agent-trade-guards.js`)
- from `workers/agent-sniper/executor.js`: idempotency lock, per-trade lamport cap,
- daily budget, max-concurrent, price-impact circuit breaker, SOL fee headroom,
- kill switch, wallet-balance check. The sniper executor and the new endpoint must
- **both** call this module — one source of truth for "is this trade allowed."
- Refactor the sniper to use it (no behavior change; its tests still pass).
-2. **`POST /api/agents/:id/trade`**: owner-authenticated (`requireAuth` + ownership
- check). Body: `{ side: 'buy'|'sell', mint, amount, denom: 'sol'|'token',
- slippageBps, network }`. Flow: `ensureAgentWallet` (task 01) → recover keypair
- (audit-logged) → quote → run shared guards → build instructions
- (`api/_lib/pump.js` / `pump-swap-ix.js`) → `signAndSend` → record the trade
- (reuse the sniper's position/trade ledger tables or the existing `pump_agent_*`
- tables — pick the one the sniper UI/PnL already reads so history is unified) →
- return signature + filled amounts + new balance.
-3. **Idempotency + safety**: require a client-supplied idempotency key (or derive
- one) so a retried request never double-spends. Enforce the same daily/per-trade
- caps as the sniper (configurable per agent). Never execute if guards reject —
- return a structured, actionable error (reason + limit), never a 500.
-4. **A read endpoint** (or extend an existing one) for the agent's discretionary
- trade quote/preview so the UI (task 04) can show expected out, price impact, and
- fees before the user confirms.
-
-## Constraints
-
-- The agent keypair is decrypted only via `recoverSolanaAgentKeypair`
- (`api/_lib/agent-wallet.js:419`), only server-side, only after auth + ownership,
- always audit-logged. Never return or log the secret.
-- No duplicated guardrail logic — the shared module is the single source of truth;
- the sniper must be refactored to consume it in the same change (or a clearly
- preceding one) and its tests must still pass.
-- Real quotes and real submission only. Honor `SNIPER_MODE`/a `simulate` flag so the
- endpoint can run in paper mode for tests, but production default is live execution
- against real RPC. No fabricated fills.
-- Errors handled at the boundary (auth, input, RPC, guard rejection, graduation) and
- returned as structured JSON with a recovery hint. A guard rejection is a 4xx with
- the reason, not an exception.
-- Respect the graduation case: if the mint has graduated, route the sell through the
- AMM path (coordinate with task 07) rather than throwing.
-
-## Success Criteria
-
-- `POST /api/agents/:id/trade` buys and sells a pump.fun token from the agent's own
- wallet on devnet, returns a confirmed signature, and the new balance reflects the
- trade.
-- The shared guardrail module is used by both the endpoint and the sniper; sniper
- tests still pass; `git grep` shows no second copy of the cap/breaker logic.
-- Retrying the same idempotency key does not double-execute.
-- Guard rejections (over budget, over per-trade cap, price-impact breaker, kill
- switch, insufficient balance) each return a clear 4xx with reason — verified with
- unit tests.
-- Unauthenticated or non-owner callers are rejected; no secret ever appears in a
- response or log.
-- `npm run typecheck` + `npm test` clean. Changelog entry (tag: feature). Run the
- **completionist** subagent on changed files.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/agent-wallet-trading/03-agent-wallet-trade-endpoint.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tests/agent-wallet-pay-tab.test.js b/tests/agent-wallet-pay-tab.test.js
new file mode 100644
index 000000000..0ac6fdd3b
--- /dev/null
+++ b/tests/agent-wallet-pay-tab.test.js
@@ -0,0 +1,225 @@
+// @vitest-environment jsdom
+//
+// Agent Wallet hub — Pay tab UI. Mounts the real tab against a mocked x402 pay
+// client and asserts the designed states: empty activity, bazaar discover,
+// service cards, the preview confirm card, and the funding-aware insufficient
+// state that routes to Deposit instead of attempting a doomed payment.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const searchBazaarServices = vi.fn();
+const previewX402 = vi.fn();
+const payX402Stream = vi.fn();
+const fetchAgentUsdc = vi.fn();
+const fetchX402Activity = vi.fn();
+
+vi.mock('../src/agent-x402-pay.js', () => ({
+ searchBazaarServices: (...a) => searchBazaarServices(...a),
+ previewX402: (...a) => previewX402(...a),
+ payX402Stream: (...a) => payX402Stream(...a),
+ fetchAgentUsdc: (...a) => fetchAgentUsdc(...a),
+ fetchX402Activity: (...a) => fetchX402Activity(...a),
+}));
+
+await import('../src/agent-wallet-hub/tabs/pay.js');
+const { getRegisteredTabs } = await import('../src/agent-wallet-hub/registry.js');
+const payTab = getRegisteredTabs().find((t) => t.id === 'pay');
+
+function makeCtx(overrides = {}) {
+ return {
+ agentId: 'agent-1',
+ agent: { id: 'agent-1', name: 'Tester' },
+ isOwner: true,
+ network: 'mainnet',
+ getNetwork: () => 'mainnet',
+ onNetworkChange: () => () => {},
+ escapeHtml: (s) =>
+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]),
+ shortAddress: (a, h = 4, t = 4) => (!a ? '' : a.length <= h + t + 1 ? a : `${a.slice(0, h)}…${a.slice(-t)}`),
+ copyToClipboard: vi.fn(async () => true),
+ toast: vi.fn(),
+ openTab: vi.fn(),
+ ...overrides,
+ };
+}
+
+const SOLANA_SERVICE = {
+ type: 'http',
+ resource: 'https://api.example.com/intel',
+ serviceName: 'Crypto Intel',
+ description: 'Live market intelligence',
+ method: 'GET',
+ input: { type: 'http', method: 'GET' },
+ accepts: [
+ { family: 'solana', network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', priceLabel: '0.05 USDC', amountAtomic: '50000' },
+ ],
+ minPriceLabel: '0.05 USDC',
+};
+
+const tick = () => new Promise((r) => setTimeout(r, 0));
+
+beforeEach(() => {
+ searchBazaarServices.mockReset();
+ previewX402.mockReset();
+ payX402Stream.mockReset();
+ fetchAgentUsdc.mockReset();
+ fetchX402Activity.mockReset();
+ document.body.innerHTML = '';
+});
+
+function mountTab(ctx = makeCtx()) {
+ const panel = document.createElement('div');
+ document.body.appendChild(panel);
+ const inst = payTab.mount({ panel, ctx });
+ return { panel, inst, ctx };
+}
+
+describe('Pay tab — discovery + activity', () => {
+ it('registers as an owner-only tab', () => {
+ expect(payTab).toBeTruthy();
+ expect(payTab.ownerOnly).toBe(true);
+ });
+
+ it('shows the empty payment-activity state when there is no history', async () => {
+ fetchX402Activity.mockResolvedValue([]);
+ const { panel, inst } = mountTab();
+ inst.onShow();
+ await tick();
+ expect(panel.textContent).toMatch(/No payments yet/i);
+ expect(panel.querySelector('[data-form="search"]')).toBeTruthy();
+ });
+
+ it('renders Solana-payable service cards from a search', async () => {
+ fetchX402Activity.mockResolvedValue([]);
+ searchBazaarServices.mockResolvedValue({ resources: [SOLANA_SERVICE], count: 1, errors: [] });
+ const { panel, inst } = mountTab();
+ inst.onShow();
+ const form = panel.querySelector('[data-form="search"]');
+ const input = panel.querySelector('[data-input="query"]');
+ input.value = 'intel';
+ form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
+ await tick();
+ expect(searchBazaarServices).toHaveBeenCalled();
+ expect(panel.querySelector('.awh-svc-name')?.textContent).toContain('Crypto Intel');
+ expect(panel.textContent).toContain('0.05 USDC');
+ });
+
+ it('renders a payment-activity row from real custody history', async () => {
+ fetchX402Activity.mockResolvedValue([
+ {
+ id: '10',
+ usd: 0.05,
+ destination: 'PayToooooAddress1111111111111111111111111',
+ signature: 'Sig1111111111111111111111111111111111111111',
+ explorer: 'https://solscan.io/tx/Sig111',
+ network: 'mainnet',
+ status: 'confirmed',
+ created_at: new Date().toISOString(),
+ meta: { service: 'Crypto Intel', url: 'https://api.example.com/intel' },
+ },
+ ]);
+ const { panel, inst } = mountTab();
+ inst.onShow();
+ await tick();
+ expect(panel.querySelector('.awh-act2-svc')?.textContent).toContain('Crypto Intel');
+ expect(panel.textContent).toContain('$0.05');
+ });
+});
+
+describe('Pay tab — preview + funding-aware', () => {
+ it('shows the price and a Pay button when the agent can afford it', async () => {
+ fetchX402Activity.mockResolvedValue([]);
+ searchBazaarServices.mockResolvedValue({ resources: [SOLANA_SERVICE], count: 1, errors: [] });
+ previewX402.mockResolvedValue({
+ ok: true,
+ requires_payment: true,
+ payable: true,
+ price_usdc: 0.05,
+ payTo: 'PayToooooAddress1111111111111111111111111',
+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ method: 'GET',
+ resource: { url: 'https://api.example.com/intel', serviceName: 'Crypto Intel' },
+ });
+ fetchAgentUsdc.mockResolvedValue({ address: 'Agent11111111111111111111111111111111111111', usdc: 1.0, sol: 0.1 });
+
+ const { panel, inst } = mountTab();
+ inst.onShow();
+ const form = panel.querySelector('[data-form="search"]');
+ panel.querySelector('[data-input="query"]').value = 'intel';
+ form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
+ await tick();
+ panel.querySelector('[data-act="select"]').dispatchEvent(new Event('click', { bubbles: true }));
+ await tick();
+ await tick();
+
+ expect(previewX402).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agent-1', url: 'https://api.example.com/intel', method: 'GET' }),
+ );
+ const payBtn = panel.querySelector('[data-act="pay"]');
+ expect(payBtn).toBeTruthy();
+ expect(payBtn.disabled).toBe(false);
+ expect(panel.textContent).toMatch(/0\.05/);
+ });
+
+ it('blocks payment and routes to Deposit when USDC is insufficient', async () => {
+ fetchX402Activity.mockResolvedValue([]);
+ searchBazaarServices.mockResolvedValue({ resources: [SOLANA_SERVICE], count: 1, errors: [] });
+ previewX402.mockResolvedValue({
+ ok: true,
+ requires_payment: true,
+ payable: true,
+ price_usdc: 0.05,
+ payTo: 'PayToooooAddress1111111111111111111111111',
+ method: 'GET',
+ resource: { url: 'https://api.example.com/intel', serviceName: 'Crypto Intel' },
+ });
+ fetchAgentUsdc.mockResolvedValue({ address: 'Agent11111111111111111111111111111111111111', usdc: 0.01, sol: 0.1 });
+
+ const ctx = makeCtx();
+ const { panel, inst } = mountTab(ctx);
+ inst.onShow();
+ const form = panel.querySelector('[data-form="search"]');
+ panel.querySelector('[data-input="query"]').value = 'intel';
+ form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
+ await tick();
+ panel.querySelector('[data-act="select"]').dispatchEvent(new Event('click', { bubbles: true }));
+ await tick();
+ await tick();
+
+ expect(panel.textContent).toMatch(/Fund the wallet/i);
+ const payBtn = panel.querySelector('[data-act="pay"]');
+ expect(payBtn.disabled).toBe(true);
+ // The payment must never be attempted when funds are short.
+ expect(payX402Stream).not.toHaveBeenCalled();
+
+ panel.querySelector('[data-act="fund"]').dispatchEvent(new Event('click', { bubbles: true }));
+ expect(ctx.openTab).toHaveBeenCalledWith('deposit');
+ });
+
+ it('surfaces an unpayable (non-Solana) service as a clear, recoverable state', async () => {
+ fetchX402Activity.mockResolvedValue([]);
+ searchBazaarServices.mockResolvedValue({ resources: [SOLANA_SERVICE], count: 1, errors: [] });
+ previewX402.mockResolvedValue({
+ ok: true,
+ requires_payment: true,
+ payable: false,
+ code: 'no_solana_accept',
+ networks: ['eip155:8453'],
+ });
+ fetchAgentUsdc.mockResolvedValue({ address: 'Agent1', usdc: 1, sol: 0.1 });
+
+ const { panel, inst } = mountTab();
+ inst.onShow();
+ const form = panel.querySelector('[data-form="search"]');
+ panel.querySelector('[data-input="query"]').value = 'intel';
+ form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
+ await tick();
+ panel.querySelector('[data-act="select"]').dispatchEvent(new Event('click', { bubbles: true }));
+ await tick();
+ await tick();
+
+ expect(panel.textContent).toMatch(/only accepts/i);
+ expect(panel.querySelector('[data-act="pay"]')).toBeFalsy();
+ });
+});
diff --git a/tests/api/x402-pay-routing.test.js b/tests/api/x402-pay-routing.test.js
new file mode 100644
index 000000000..accc9b120
--- /dev/null
+++ b/tests/api/x402-pay-routing.test.js
@@ -0,0 +1,146 @@
+// /api/x402-pay — payer routing. An agent context (an `agentId` on the request)
+// must ALWAYS pay from that agent's own wallet; the shared platform wallet is an
+// explicit fallback used only when no agent context is present, and that fallback
+// is logged (never silent) so a regression that drops the agentId is visible.
+//
+// Mocks auth + rate-limit + the logger + fs so no funds move and no network I/O
+// happens — we assert the routing decision and the fallback log only.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const getSessionUserMock = vi.fn(async () => null);
+const authenticateBearerMock = vi.fn(async () => null);
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUserMock(...a),
+ authenticateBearer: (...a) => authenticateBearerMock(...a),
+ extractBearer: () => null,
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ x402PayIp: vi.fn(async () => ({ success: true })),
+ x402PayGlobal: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: () => '127.0.0.1',
+}));
+
+// Capture warn() calls so we can assert the platform-fallback is logged.
+const warnMock = vi.fn();
+vi.mock('../../api/_lib/usage.js', () => ({
+ logger: () => ({ info: vi.fn(), warn: warnMock, error: vi.fn() }),
+ recordEvent: vi.fn(),
+}));
+
+vi.mock('../../api/_lib/redis.js', () => ({ getRedis: () => null }));
+vi.mock('../../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));
+
+// No shared platform wallet configured + no dev keypair file → loadAgentKeypair()
+// throws config-missing, which is the deterministic outcome we assert for the
+// fallback path (the warn must already have fired before this throws).
+vi.mock('node:fs', () => ({
+ readFileSync: () => {
+ throw new Error('no dev keypair');
+ },
+}));
+
+delete process.env.X402_AGENT_SOLANA_SECRET_BASE58;
+
+const mod = await import('../../api/x402-pay.js');
+const { default: handler, resolvePayerRouting } = mod;
+
+function makeReq(body, headers = {}) {
+ const req = {
+ url: '/api/x402-pay',
+ method: 'POST',
+ headers: { host: 'x', 'content-type': 'application/json', ...headers },
+ query: {},
+ };
+ const buf = Buffer.from(JSON.stringify(body));
+ let read = false;
+ req.on = (event, cb) => {
+ if (event === 'data' && !read) {
+ cb(buf);
+ read = true;
+ } else if (event === 'end') queueMicrotask(cb);
+ return req;
+ };
+ req.headers['content-length'] = String(buf.length);
+ return req;
+}
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ setHeader(k, v) {
+ this._h[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this._h[k.toLowerCase()];
+ },
+ end(b) {
+ this._body = b;
+ },
+ };
+}
+async function call(body) {
+ const res = makeRes();
+ await handler(makeReq(body), res);
+ let parsed = null;
+ try {
+ parsed = JSON.parse(res._body);
+ } catch {}
+ return { res, body: parsed };
+}
+
+beforeEach(() => {
+ warnMock.mockReset();
+ getSessionUserMock.mockReset().mockResolvedValue(null);
+ authenticateBearerMock.mockReset().mockResolvedValue(null);
+});
+
+describe('resolvePayerRouting', () => {
+ it('routes to the per-agent wallet when an agentId is present', () => {
+ expect(resolvePayerRouting({ agentId: 'a1', tool: 'tools/list' })).toEqual({
+ mode: 'agent',
+ agentId: 'a1',
+ });
+ });
+
+ it('falls back to the platform wallet only when no agent context is present', () => {
+ expect(resolvePayerRouting({ tool: 'tools/list' })).toEqual({ mode: 'platform' });
+ expect(resolvePayerRouting({})).toEqual({ mode: 'platform' });
+ });
+
+ it('coerces a non-string agentId to its string form for the agent path', () => {
+ expect(resolvePayerRouting({ agentId: 123 })).toEqual({ mode: 'agent', agentId: '123' });
+ });
+});
+
+describe('POST /api/x402-pay payer routing', () => {
+ it('an agent context requires auth — never silently spends the shared wallet', async () => {
+ // agentId present but unauthenticated → 401, NOT a fall-through to the
+ // shared platform wallet. The shared wallet can never pay for an agent.
+ const { res, body } = await call({ tool: 'tools/list', agentId: 'a1' });
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toBe('authentication_required');
+ expect(warnMock).not.toHaveBeenCalledWith('platform_wallet_fallback', expect.anything());
+ });
+
+ it('no agent context logs the platform fallback (not silent)', async () => {
+ const { res } = await call({ tool: 'tools/list' });
+ // The shared wallet is unconfigured in tests → 503 config_missing, but the
+ // fallback must have been logged before that.
+ expect(res.statusCode).toBe(503);
+ expect(warnMock).toHaveBeenCalledWith(
+ 'platform_wallet_fallback',
+ expect.objectContaining({ reason: 'no_agent_context' }),
+ );
+ });
+
+ it('an external-pay request with no agent context is refused, not routed to the shared wallet', async () => {
+ const { res, body } = await call({ url: 'https://example.com/paid' });
+ // requireAuth → null first, so 401; the key point is no shared-wallet pay.
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toBe('authentication_required');
+ });
+});
diff --git a/tests/solana-trade-guards.test.js b/tests/solana-trade-guards.test.js
new file mode 100644
index 000000000..04f957580
--- /dev/null
+++ b/tests/solana-trade-guards.test.js
@@ -0,0 +1,191 @@
+// Guard-wiring tests for the kept /api/agents/:id/solana/trade endpoint.
+//
+// After the shared-guardrail refactor this handler enforces the SAME predicates +
+// per-agent meta.trade_limits as the flat /api/agents/:id/trade endpoint and the
+// sniper. These tests drive it in preview mode (no signing) and on execute to
+// prove the kill switch, per-trade cap, daily budget, price-impact breaker, and
+// fee headroom all reject through the shared module — auth + ownership too.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+import { Keypair, PublicKey } from '@solana/web3.js';
+
+const AGENT_ADDR = Keypair.generate().publicKey.toBase58();
+const MINT = Keypair.generate().publicKey.toBase58();
+
+const sqlState = { agent: null, existingCustody: null };
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings) => {
+ const q = (typeof strings === 'string' ? strings : strings.join('?')).toLowerCase();
+ if (/from agent_identities/.test(q) && /select/.test(q)) return sqlState.agent ? [sqlState.agent] : [];
+ if (/from agent_custody_events/.test(q) && /idempotency_key =/.test(q)) return sqlState.existingCustody ? [sqlState.existingCustody] : [];
+ if (/sum\(amount_lamports\)/.test(q)) return [{ lamports: '0' }];
+ if (/sum\(usd\)/.test(q)) return [{ usd: 0 }];
+ return [];
+ }),
+}));
+
+const authState = { session: { id: 'owner-1' } };
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: true })), walletRead: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+vi.mock('../api/_lib/avatar-wallet.js', () => ({
+ solUsdPrice: vi.fn(async () => 200),
+ explorerTxUrl: (sig, net) => `https://explorer.example/tx/${sig}?cluster=${net}`,
+}));
+
+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
+vi.mock('../api/_lib/cache.js', () => ({ cacheSet: vi.fn(async () => {}), cacheGet: vi.fn(async () => null) }));
+
+const connState = { balance: 5_000_000_000 };
+function fakeConn() {
+ return {
+ getBalance: vi.fn(async () => connState.balance),
+ getParsedAccountInfo: vi.fn(async () => ({ value: { data: { parsed: { info: { decimals: 6 } } } } })),
+ };
+}
+vi.mock('../api/_lib/agent-pumpfun.js', () => ({
+ solanaConnection: vi.fn(() => fakeConn()),
+ solanaPublicConnection: vi.fn(() => fakeConn()),
+}));
+
+const quoteState = { buyImpact: 1 };
+vi.mock('../api/_lib/solana/sdk-bridge.js', () => ({
+ getBuyQuote: vi.fn(async () => ({ tokens: '1000000', priceImpact: quoteState.buyImpact })),
+ getSellQuote: vi.fn(async () => ({ sol: '50000000', priceImpact: 1 })),
+}));
+
+vi.mock('../api/_lib/pump.js', () => ({ getAmmPoolState: vi.fn(async () => { throw Object.assign(new Error('no pool'), { code: 'pool_not_found' }); }) }));
+vi.mock('../api/_lib/pump-platform-fee.js', () => ({ effectivePumpFeeBps: vi.fn(async () => 100) }));
+
+const { handleTrade } = await import('../api/agents/solana-trade.js');
+
+const AGENT_ID = '11111111-1111-4111-8111-111111111111';
+
+function mockRes() {
+ return {
+ statusCode: 200, _headers: {}, _body: '',
+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this._headers[k.toLowerCase()]; },
+ end(b) { this._body = b || ''; },
+ get headersSent() { return false; },
+ get writableEnded() { return false; },
+ get json() { try { return JSON.parse(this._body); } catch { return null; } },
+ };
+}
+function mockReq(body) {
+ const r = Readable.from([Buffer.from(JSON.stringify(body))]);
+ r.method = 'POST';
+ r.url = `/api/agents/${AGENT_ID}/solana/trade`;
+ r.headers = { origin: 'http://localhost:3000', 'content-type': 'application/json' };
+ return r;
+}
+function setAgent(meta = {}) {
+ sqlState.agent = { id: AGENT_ID, user_id: 'owner-1', meta: { solana_address: AGENT_ADDR, encrypted_solana_secret: 'ENC::secret', ...meta } };
+}
+async function call(body) {
+ const res = mockRes();
+ await handleTrade(mockReq(body), res, AGENT_ID);
+ return res;
+}
+
+beforeEach(() => {
+ sqlState.agent = null;
+ sqlState.existingCustody = null;
+ authState.session = { id: 'owner-1' };
+ connState.balance = 5_000_000_000;
+ quoteState.buyImpact = 1;
+ setAgent();
+});
+
+describe('solana-trade — auth & ownership', () => {
+ it('401 for an unauthenticated caller', async () => {
+ authState.session = null;
+ const res = await call({ preview: true, side: 'buy', mint: MINT, sol_amount: 0.1 });
+ expect(res.statusCode).toBe(401);
+ });
+ it('403 for a non-owner', async () => {
+ sqlState.agent.user_id = 'someone-else';
+ const res = await call({ preview: true, side: 'buy', mint: MINT, sol_amount: 0.1 });
+ expect(res.statusCode).toBe(403);
+ });
+});
+
+describe('solana-trade — preview surfaces shared-guard breaches', () => {
+ it('kill switch → guard trading_paused', async () => {
+ setAgent({ trade_limits: { kill_switch: true } });
+ const res = await call({ preview: true, side: 'buy', mint: MINT, sol_amount: 0.1 });
+ expect(res.statusCode).toBe(200);
+ expect(res.json.data.guard?.code).toBe('trading_paused');
+ });
+
+ it('over per-trade cap → guard per_trade_cap', async () => {
+ setAgent({ trade_limits: { per_trade_sol: 0.05 } });
+ const res = await call({ preview: true, side: 'buy', mint: MINT, sol_amount: 0.1 });
+ expect(res.json.data.guard?.code).toBe('per_trade_cap');
+ });
+
+ it('price impact over the configurable breaker → guard price_impact_too_high', async () => {
+ quoteState.buyImpact = 40; // default breaker is 15%
+ const res = await call({ preview: true, side: 'buy', mint: MINT, sol_amount: 0.1 });
+ expect(res.json.data.guard?.code).toBe('price_impact_too_high');
+ expect(res.json.data.guard?.detail?.max_price_impact_pct).toBe(15);
+ });
+
+ it('insufficient SOL → funds insufficient_sol', async () => {
+ connState.balance = 0;
+ const res = await call({ preview: true, side: 'buy', mint: MINT, sol_amount: 0.1 });
+ expect(res.json.data.funds?.code).toBe('insufficient_sol');
+ });
+
+ it('a clean buy previews with no guard/funds warning', async () => {
+ const res = await call({ preview: true, side: 'buy', mint: MINT, sol_amount: 0.1 });
+ expect(res.json.data.guard).toBeNull();
+ expect(res.json.data.funds).toBeNull();
+ expect(res.json.data.price_impact_pct).toBe(1);
+ });
+});
+
+describe('solana-trade — execute hard-stops on a guard breach (no signing)', () => {
+ it('kill switch → 403 before the key is touched', async () => {
+ setAgent({ trade_limits: { kill_switch: true } });
+ const res = await call({ side: 'buy', mint: MINT, sol_amount: 0.1, idempotency_key: 'k-1' });
+ expect(res.statusCode).toBe(403);
+ expect(res.json.error).toBe('trading_paused');
+ });
+
+ it('over per-trade cap → 422', async () => {
+ setAgent({ trade_limits: { per_trade_sol: 0.05 } });
+ const res = await call({ side: 'buy', mint: MINT, sol_amount: 0.1, idempotency_key: 'k-2' });
+ expect(res.statusCode).toBe(422);
+ expect(res.json.error).toBe('per_trade_cap');
+ });
+
+ it('price impact over breaker → 422', async () => {
+ quoteState.buyImpact = 40;
+ const res = await call({ side: 'buy', mint: MINT, sol_amount: 0.1, idempotency_key: 'k-3' });
+ expect(res.statusCode).toBe(422);
+ expect(res.json.error).toBe('price_impact_too_high');
+ });
+
+ it('insufficient SOL → 402', async () => {
+ connState.balance = 0;
+ const res = await call({ side: 'buy', mint: MINT, sol_amount: 0.1, idempotency_key: 'k-4' });
+ expect(res.statusCode).toBe(402);
+ expect(res.json.error).toBe('insufficient_sol');
+ });
+
+ it('execute without an idempotency key is rejected', async () => {
+ const res = await call({ side: 'buy', mint: MINT, sol_amount: 0.1 });
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error).toBe('validation_error');
+ });
+});