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.

test(agent-economy): pin the A2A endpoint's delivery-before-payment and own-property service lookup

nirholasf17d1fecff01
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fbb0ca297..4667a7470 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-08-10
+- **Autopilot answers a bad request with a clear error instead of an internal failure**: The autopilot API (the proposal queue, the permission panel, and the signed activity feed) treated a few kinds of bad input as a server crash: an agent or proposal id that was not a real id, a negative page size, or a pagination cursor larger than the feed can hold all came back as an anonymous internal error with a support reference. Each of those now returns a plain 400 that names the offending field, and asking the proposal queue for an action it does not support says which actions exist instead of complaining about a missing proposal. Nothing about what autopilot can do changed: the ownership, permission and confirmation rules are untouched. (`/autopilot-activity`) `[fix]`
- **Revoking an API key with a malformed id now gives a clear error instead of a server fault**: Deleting an API key through the developer API used to hand whatever id it was given straight to the database, so an id that could never match a key came back as a generic "internal error, quote this reference to support" 500. It now answers a plain 400 saying the id must be a key identifier, and the database is never touched for input that cannot match. Real revokes, the ownership check that stops one account revoking another account's key, and the already-revoked case all behave exactly as before. (`/dashboard`) `[fix]`
+- **The agent-to-agent economy demo speaks again, and never pays for a service it could not deliver**: On the live agent economy page, Nova hires Oracle for a paid data service and Oracle answers with a real model response. That answer had gone silent: the endpoint fetched it over an internal HTTP call to an address that does not exist in production, so both agents stayed mute while the page still reported the trade as complete. The delivery now runs directly against the platform model chain, and it runs before the payment: if no model can produce the service, the request stops with a clear "try again in a moment" and not one lamport leaves Nova's wallet. A request naming a service that does not exist is now rejected outright instead of slipping through as an unnamed, unpriced one, and the daily on-chain spending ceiling is only spent when a payment actually fires, so an empty wallet can no longer exhaust the day's budget for everyone. (`/agent-economy`) `[fix]`
- **The aixbt market feeds now say when the key, not you, is the problem**: When aixbt turned down this deployment's API key, the narrative intel, momentum projects, grounding and chat feeds all answered with a plain 'unauthorized' aimed at you. Nothing on those surfaces ever asked you to sign in, so the message read as a dead end nobody could act on. They now report the real cause, that the platform's aixbt key has expired or sits below the plan the read needs, and carry the same setup pointer the missing-key state shows, so the in-world aixbt panel and the intel SDK both render something an operator can fix. The intel and projects feeds also stop advertising a page size of 100 they were never able to return, and a chat turn that comes back empty now says so instead of handing you a blank answer marked successful. (`/docs/api-reference`) `[fix, improvement]`
- **The CA to x402 tool now always hands you a three.ws payment address**: Paste a contract address into the CA to x402 tool and it generates a paid data service for that token, complete with copy-paste commands you run to pay for and call it. Those commands were built from the web address in your browser's request, which anyone could forge: a crafted link could have handed a visitor a set of "pay here" commands pointing at somebody else's server, and because the answer is cached at the edge, that swapped copy could then have been served on to other visitors. The generated endpoint and every snippet are now pinned to three.ws itself, so what you copy is always ours no matter how the page was reached. (`/ca2x402`) `[security, fix]`
- **The chat plugin now tells you when your Agent ID is wrong**: In the SperaxOS and LobeChat plugin, a mistyped or deleted Agent ID used to come back as a cheerful confirmation while the avatar panel stayed empty, so the model told you it had bound an agent that does not exist. The plugin now checks the ID against your real agents before answering: a bad ID returns a clear error pointing you back to the dashboard to recopy it, and a good one comes back with the agent name so you can see at a glance which identity the panel is wearing. Stray spaces around a pasted ID are trimmed instead of breaking the binding. (`/docs/embedding`) `[fix]`
diff --git a/data/changelog.json b/data/changelog.json
index 27bff19e8..939522b94 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -10,6 +10,15 @@
],
"link": "/autopilot-activity"
},
+ {
+ "date": "2026-08-10",
+ "title": "The agent-to-agent economy demo speaks again, and never pays for a service it could not deliver",
+ "summary": "On the live agent economy page, Nova hires Oracle for a paid data service and Oracle answers with a real model response. That answer had gone silent: the endpoint fetched it over an internal HTTP call to an address that does not exist in production, so both agents stayed mute while the page still reported the trade as complete. The delivery now runs directly against the platform model chain, and it runs before the payment: if no model can produce the service, the request stops with a clear \"try again in a moment\" and not one lamport leaves Nova's wallet. A request naming a service that does not exist is now rejected outright instead of slipping through as an unnamed, unpriced one, and the daily on-chain spending ceiling is only spent when a payment actually fires, so an empty wallet can no longer exhaust the day's budget for everyone.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/agent-economy"
+ },
{
"date": "2026-08-10",
"title": "Revoking an API key with a malformed id now gives a clear error instead of a server fault",
diff --git a/prompts/swarm-100/api-agent-economy-01.md b/prompts/swarm-100/api-agent-economy-01.md
deleted file mode 100644
index 96261c866..000000000
--- a/prompts/swarm-100/api-agent-economy-01.md
+++ /dev/null
@@ -1,103 +0,0 @@
-# API audit: api/agent-economy batch 01 (3 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/agent-economy/status.js
-- api/agent-economy/transact.js
-- api/agent-economy/volume.js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-agent-economy-01.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/public/changelog.json b/public/changelog.json
index 2f2e9dd21..5ea141bcf 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-08-10T16:52:30.839Z",
+ "generated_at": "2026-08-10T17:00:29.080Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-08-10",
+ "type": "update",
+ "title": "Autopilot answers a bad request with a clear error instead of an internal failure",
+ "summary": "The autopilot API (the proposal queue, the permission panel, and the signed activity feed) treated a few kinds of bad input as a server crash: an agent or proposal id that was not a real id, a negative page size, or a pagination cursor larger than the feed can hold all came back as an anonymous internal error with a support reference. Each of those now returns a plain 400 that names the offending field, and asking the proposal queue for an action it does not support says which actions exist instead of complaining about a missing proposal. Nothing about what autopilot can do changed: the ownership, permission and confirmation rules are untouched.",
+ "link": "/autopilot-activity",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-08-10",
"type": "update",
@@ -16,6 +26,16 @@
"fix"
]
},
+ {
+ "date": "2026-08-10",
+ "type": "update",
+ "title": "The agent-to-agent economy demo speaks again, and never pays for a service it could not deliver",
+ "summary": "On the live agent economy page, Nova hires Oracle for a paid data service and Oracle answers with a real model response. That answer had gone silent: the endpoint fetched it over an internal HTTP call to an address that does not exist in production, so both agents stayed mute while the page still reported the trade as complete. The delivery now runs directly against the platform model chain, and it runs before the payment: if no model can produce the service, the request stops with a clear \"try again in a moment\" and not one lamport leaves Nova's wallet. A request naming a service that does not exist is now rejected outright instead of slipping through as an unnamed, unpriced one, and the daily on-chain spending ceiling is only spent when a payment actually fires, so an empty wallet can no longer exhaust the day's budget for everyone.",
+ "link": "/agent-economy",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-08-10",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 07fa96cfb..b820bc7c6 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws: features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Autopilot answers a bad request with a clear error instead of an internal failure</title>
+ <link>https://three.ws/autopilot-activity</link>
+ <guid isPermaLink="false">2026-08-10:Autopilot answers a bad request with a clear error instead of an internal failure</guid>
+ <pubDate>Mon, 10 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The autopilot API (the proposal queue, the permission panel, and the signed activity feed) treated a few kinds of bad input as a server crash: an agent or proposal id that was not a real id, a negative page size, or a pagination cursor larger than the feed can hold all came back as an anonymous internal error with a support reference. Each of those now returns a plain 400 that names the offending field, and asking the proposal queue for an action it does not support says which actions exist instead of complaining about a missing proposal. Nothing about what autopilot can do changed: the ownership, permission and confirmation rules are untouched.</description>
+ </item>
<item>
<title>Revoking an API key with a malformed id now gives a clear error instead of a server fault</title>
<link>https://three.ws/dashboard</link>
@@ -14,6 +22,14 @@
<category>fix</category>
<description>Deleting an API key through the developer API used to hand whatever id it was given straight to the database, so an id that could never match a key came back as a generic &quot;internal error, quote this reference to support&quot; 500. It now answers a plain 400 saying the id must be a key identifier, and the database is never touched for input that cannot match. Real revokes, the ownership check that stops one account revoking another account's key, and the already-revoked case all behave exactly as before.</description>
</item>
+ <item>
+ <title>The agent-to-agent economy demo speaks again, and never pays for a service it could not deliver</title>
+ <link>https://three.ws/agent-economy</link>
+ <guid isPermaLink="false">2026-08-10:The agent-to-agent economy demo speaks again, and never pays for a service it could not deliver</guid>
+ <pubDate>Mon, 10 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>On the live agent economy page, Nova hires Oracle for a paid data service and Oracle answers with a real model response. That answer had gone silent: the endpoint fetched it over an internal HTTP call to an address that does not exist in production, so both agents stayed mute while the page still reported the trade as complete. The delivery now runs directly against the platform model chain, and it runs before the payment: if no model can produce the service, the request stops with a clear &quot;try again in a moment&quot; and not one lamport leaves Nova's wallet. A request naming a service that does not exist is now rejected outright instead of slipping through as an unnamed, unpriced one, and the daily on-chain spending ceiling is only spent when a payment actually fires, so an empty wallet can no longer exhaust the day's budget for everyone.</description>
+ </item>
<item>
<title>The aixbt market feeds now say when the key, not you, is the problem</title>
<link>https://three.ws/docs/api-reference</link>
diff --git a/tests/agent-economy-status.test.js b/tests/agent-economy-status.test.js
new file mode 100644
index 000000000..ea2390add
--- /dev/null
+++ b/tests/agent-economy-status.test.js
@@ -0,0 +1,95 @@
+// GET /api/agent-economy/status, the live wallet read behind the A2A demo page.
+//
+// The invariant worth a test: `configured` reports CONFIGURATION, not RPC
+// health. An agent whose env var is set stays configured:true with a null
+// balance when Solana is unreachable, so the page can say "balance unavailable"
+// instead of "wallet not set". Those two used to collapse into the same
+// configured:false, because the address was only assigned after a successful
+// balance read and Promise.allSettled swallowed the RPC error.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const BUYER = 'BUYERaddr1111111111111111111111111111111111';
+const SELLER = 'SELLERaddr222222222222222222222222222222222';
+
+const walletConfigMock = vi.fn();
+const getSolBalanceMock = vi.fn();
+const solUsdPriceMock = vi.fn();
+vi.mock('../api/_lib/avatar-wallet.js', () => ({
+ avatarWalletConfig: () => walletConfigMock(),
+ loadAvatarKeypair: () => ({ publicKey: { toBase58: () => BUYER } }),
+ getConnection: () => ({}),
+ getSolBalance: (...a) => getSolBalanceMock(...a),
+ solUsdPrice: () => solUsdPriceMock(),
+ isValidPubkey: (a) => typeof a === 'string' && a.length > 30,
+ explorerAccountUrl: (addr) => `https://solscan.io/account/${addr}`,
+}));
+
+const { default: status } = await import('../api/agent-economy/status.js');
+
+const mkReq = () => ({ method: 'GET', url: '/api/agent-economy/status', headers: {} });
+function mkRes() {
+ return {
+ statusCode: 200, headers: {}, body: undefined, writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ writeHead(code, hdrs) { this.statusCode = code; Object.assign(this.headers, hdrs || {}); return this; },
+ end(b) { this.body = b; this.writableEnded = true; },
+ };
+}
+const payload = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+beforeEach(() => {
+ process.env.AVATAR_WALLET_SECRET = 'test-secret';
+ process.env.AGENT_B_ADDRESS = SELLER;
+ walletConfigMock.mockReset().mockReturnValue({ configured: true, network: 'mainnet' });
+ solUsdPriceMock.mockReset().mockResolvedValue(200);
+ getSolBalanceMock.mockReset().mockImplementation(async (_conn, addr) =>
+ (addr === BUYER ? { sol: 0.5, lamports: 500_000_000 } : { sol: 2, lamports: 2_000_000_000 }));
+});
+
+describe('GET /api/agent-economy/status', () => {
+ it('returns both live balances priced in USD', async () => {
+ const res = mkRes();
+ await status(mkReq(), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.headers['cache-control']).toBe('no-store');
+ const out = payload(res);
+ expect(out.agentA).toEqual({
+ configured: true, address: BUYER, sol: 0.5, lamports: 500_000_000,
+ usd: 100, solPriceUsd: 200, network: 'mainnet',
+ explorer: `https://solscan.io/account/${BUYER}`,
+ });
+ expect(out.agentB).toMatchObject({ configured: true, address: SELLER, sol: 2, usd: 400 });
+ });
+
+ it('stays configured with a null balance when the RPC read fails', async () => {
+ getSolBalanceMock.mockRejectedValue(new Error('429 rate limited'));
+ const res = mkRes();
+ await status(mkReq(), res);
+
+ const out = payload(res);
+ expect(out.agentA).toMatchObject({ configured: true, address: BUYER, sol: null, usd: null });
+ expect(out.agentB).toMatchObject({ configured: true, address: SELLER, sol: null });
+ });
+
+ it('reports configured:false only when the env var is absent', async () => {
+ walletConfigMock.mockReturnValue({ configured: false, network: 'mainnet' });
+ delete process.env.AGENT_B_ADDRESS;
+ const res = mkRes();
+ await status(mkReq(), res);
+
+ expect(payload(res)).toEqual({ agentA: { configured: false }, agentB: { configured: false } });
+ expect(getSolBalanceMock).not.toHaveBeenCalled();
+ });
+
+ it('ignores a malformed AGENT_B_ADDRESS instead of reporting a bad wallet', async () => {
+ process.env.AGENT_B_ADDRESS = 'not-a-pubkey';
+ const res = mkRes();
+ await status(mkReq(), res);
+
+ const out = payload(res);
+ expect(out.agentB).toEqual({ configured: false });
+ expect(out.agentA.configured).toBe(true);
+ });
+});
diff --git a/tests/agent-economy-transact.test.js b/tests/agent-economy-transact.test.js
new file mode 100644
index 000000000..81d9f2282
--- /dev/null
+++ b/tests/agent-economy-transact.test.js
@@ -0,0 +1,217 @@
+// POST /api/agent-economy/transact, the agent-to-agent economy endpoint.
+//
+// The contract this locks down is about MONEY, so it is exercised against the
+// real handler with only the two outside edges stubbed: the LLM provider chain
+// and the Solana wallet. Four invariants:
+//
+// 1. A real completion is what gets sold: the seller's text is the model's,
+// never a canned line.
+// 2. Delivery happens BEFORE payment. A dead model chain returns 503 and
+// sendSol() is never called, so Agent A cannot pay for nothing.
+// 3. Service lookup is own-property only: `service: "constructor"` is a 400,
+// not a pseudo-service with an undefined price walking into the send path.
+// 4. The global daily spend ceiling is consumed only when a send actually
+// fires. An unfunded wallet must not be able to drain the demo budget.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const llmCompleteMock = vi.fn();
+vi.mock('../api/_lib/llm.js', () => ({
+ llmComplete: (...a) => llmCompleteMock(...a),
+ LlmUnavailableError: class LlmUnavailableError extends Error {},
+}));
+
+const sendSolMock = vi.fn();
+const getSolBalanceMock = vi.fn();
+const walletConfigMock = vi.fn();
+vi.mock('../api/_lib/avatar-wallet.js', () => ({
+ avatarWalletConfig: () => walletConfigMock(),
+ loadAvatarKeypair: () => ({ publicKey: { toBase58: () => 'BUYERaddr1111111111111111111111111111111111' } }),
+ getConnection: () => ({}),
+ getSolBalance: (...a) => getSolBalanceMock(...a),
+ solUsdPrice: async () => 100,
+ sendSol: (...a) => sendSolMock(...a),
+ isValidPubkey: (a) => typeof a === 'string' && a.length > 30,
+ explorerTxUrl: (sig) => `https://solscan.io/tx/${sig}`,
+ explorerAccountUrl: (addr) => `https://solscan.io/account/${addr}`,
+ LAMPORTS_PER_SOL: 1_000_000_000,
+}));
+
+const ipLimitMock = vi.fn();
+const globalLimitMock = vi.fn();
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ clientIp: () => '10.0.0.1',
+ limits: {
+ agentEconomyIp: (...a) => ipLimitMock(...a),
+ agentEconomyGlobal: (...a) => globalLimitMock(...a),
+ },
+}));
+
+const { default: transact } = await import('../api/agent-economy/transact.js');
+
+function mkReq(body) {
+ return {
+ method: 'POST',
+ url: '/api/agent-economy/transact',
+ headers: { 'content-type': 'application/json' },
+ on(event, cb) {
+ if (event === 'data' && body != null) {
+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));
+ queueMicrotask(() => { cb(buf); this._endCb?.(); });
+ } else if (event === 'end') {
+ this._endCb = cb;
+ if (body == null) queueMicrotask(() => cb());
+ }
+ },
+ destroy() {},
+ };
+}
+function mkRes() {
+ return {
+ statusCode: 200, headers: {}, body: undefined, writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ writeHead(code, hdrs) { this.statusCode = code; Object.assign(this.headers, hdrs || {}); return this; },
+ end(b) { this.body = b; this.writableEnded = true; },
+ };
+}
+const payload = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+const FUNDED = { configured: true, network: 'mainnet', rpcUrl: 'https://rpc.test', defaultRecipient: null };
+
+beforeEach(() => {
+ process.env.AVATAR_WALLET_SECRET = 'test-secret';
+ process.env.AGENT_B_ADDRESS = 'SELLERaddr222222222222222222222222222222222';
+ llmCompleteMock.mockReset().mockImplementation(async ({ system }) => ({
+ text: system ? 'Risk sits at 6. Liquidity is thinning and holder concentration is climbing.' : 'Oracle, price me a market read.',
+ }));
+ sendSolMock.mockReset().mockResolvedValue('SIGNATURE111');
+ getSolBalanceMock.mockReset().mockResolvedValue(5_000_000);
+ walletConfigMock.mockReset().mockReturnValue(FUNDED);
+ ipLimitMock.mockReset().mockResolvedValue({ success: true });
+ globalLimitMock.mockReset().mockResolvedValue({ success: true });
+});
+
+describe('POST /api/agent-economy/transact', () => {
+ it('sells the model completion and settles the payment on-chain', async () => {
+ const res = mkRes();
+ await transact(mkReq({ service: 'risk-score', topic: 'Solana DeFi' }), res);
+
+ expect(res.statusCode).toBe(200);
+ const out = payload(res);
+ expect(out.service).toMatchObject({ slug: 'risk-score', name: 'Risk Score', priceUsd: 0.003 });
+ expect(out.topic).toBe('Solana DeFi');
+ expect(out.sellerSaid).toContain('Risk sits at 6');
+ expect(out.buyerSaid).toBe('Oracle, price me a market read.');
+ // $0.003 at $100/SOL is 30_000 lamports, above the 10_000-lamport floor.
+ expect(out.transaction).toMatchObject({
+ signature: 'SIGNATURE111',
+ explorerUrl: 'https://solscan.io/tx/SIGNATURE111',
+ sellerAddress: process.env.AGENT_B_ADDRESS,
+ lamports: 30_000,
+ usdAmount: 0.003,
+ network: 'mainnet',
+ });
+ expect(sendSolMock).toHaveBeenCalledTimes(1);
+ expect(globalLimitMock).toHaveBeenCalledTimes(1);
+ // The seller's line is the model's own text, not a canned fallback.
+ expect(out.sellerSaid).not.toMatch(/delivered\. The data is yours/);
+ });
+
+ it('never pays when the model chain is down: 503, no send, no budget consumed', async () => {
+ llmCompleteMock.mockRejectedValue(Object.assign(new Error('chain exhausted'), { status: 502 }));
+ const res = mkRes();
+ await transact(mkReq({ service: 'market-analysis' }), res);
+
+ expect(res.statusCode).toBe(503);
+ expect(payload(res).error).toBe('delivery_unavailable');
+ expect(sendSolMock).not.toHaveBeenCalled();
+ expect(globalLimitMock).not.toHaveBeenCalled();
+ });
+
+ it('treats an empty completion as an undeliverable service', async () => {
+ llmCompleteMock.mockResolvedValue({ text: ' ' });
+ const res = mkRes();
+ await transact(mkReq({ service: 'onchain-insight' }), res);
+
+ expect(res.statusCode).toBe(503);
+ expect(sendSolMock).not.toHaveBeenCalled();
+ });
+
+ it('still delivers when only the buyer line fails', async () => {
+ llmCompleteMock.mockImplementation(async ({ system }) => {
+ if (!system) throw new Error('buyer lane down');
+ return { text: 'Momentum is holding. Watch the 4h close.' };
+ });
+ const res = mkRes();
+ await transact(mkReq({ service: 'market-analysis' }), res);
+
+ expect(res.statusCode).toBe(200);
+ const out = payload(res);
+ expect(out.buyerSaid).toBeNull();
+ expect(out.sellerSaid).toContain('Momentum is holding');
+ expect(sendSolMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects prototype-chain keys as unknown services without touching the wallet', async () => {
+ for (const service of ['constructor', '__proto__', 'toString', 'valueOf']) {
+ const res = mkRes();
+ await transact(mkReq({ service }), res);
+ expect(res.statusCode, service).toBe(400);
+ expect(payload(res).error, service).toBe('unknown_service');
+ }
+ expect(llmCompleteMock).not.toHaveBeenCalled();
+ expect(sendSolMock).not.toHaveBeenCalled();
+ expect(globalLimitMock).not.toHaveBeenCalled();
+ });
+
+ it('reports insufficient balance without consuming the daily spend budget', async () => {
+ getSolBalanceMock.mockResolvedValue(1_000);
+ const res = mkRes();
+ await transact(mkReq({ service: 'risk-score' }), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(payload(res).transaction).toEqual({
+ error: 'insufficient_balance',
+ message: "Fund Agent A's wallet to enable live transactions.",
+ });
+ expect(sendSolMock).not.toHaveBeenCalled();
+ // The ceiling exists to cap real spend; an unfunded wallet must not drain it.
+ expect(globalLimitMock).not.toHaveBeenCalled();
+ });
+
+ it('delivers the service but reports the wallet when it is unconfigured', async () => {
+ walletConfigMock.mockReturnValue({ configured: false, network: 'mainnet', rpcUrl: 'https://rpc.test', defaultRecipient: null });
+ const res = mkRes();
+ await transact(mkReq({ service: 'market-analysis' }), res);
+
+ const out = payload(res);
+ expect(res.statusCode).toBe(200);
+ expect(out.sellerSaid).toBeTruthy();
+ expect(out.transaction.error).toBe('wallet_unconfigured');
+ expect(sendSolMock).not.toHaveBeenCalled();
+ });
+
+ it('holds the send back once the daily ceiling is reached', async () => {
+ globalLimitMock.mockResolvedValue({ success: false, limit: 500, remaining: 0, reset: Date.now() + 1000 });
+ const res = mkRes();
+ await transact(mkReq({ service: 'risk-score' }), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(payload(res).transaction.error).toBe('rate_limited');
+ expect(sendSolMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unknown service and a bad body before any spend', async () => {
+ const unknown = mkRes();
+ await transact(mkReq({ service: 'not-a-service' }), unknown);
+ expect(unknown.statusCode).toBe(400);
+ expect(payload(unknown).error).toBe('unknown_service');
+
+ const tooLong = mkRes();
+ await transact(mkReq({ service: 'risk-score', topic: 'x'.repeat(121) }), tooLong);
+ expect(tooLong.statusCode).toBe(400);
+ expect(payload(tooLong).error).toBe('validation_error');
+
+ expect(sendSolMock).not.toHaveBeenCalled();
+ });
+});