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.

docs(x402): document selling an agent as an API and let the Earn tab create the missing Solana wallet

nirholasb55fed417790
diff --git a/STRUCTURE.md b/STRUCTURE.md
index d4fd4c9da..be1e2c020 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -64,6 +64,7 @@ bottom.
| KOL Tracker | [pages/tracker.html](pages/tracker.html) `→ /tracker`, backend [api/kol/[action].js](api/kol/%5Baction%5D.js) `→ GET /api/kol/tracker?window=&limit=`, aggregator [src/kol/tracker.js](src/kol/tracker.js), wallet list [src/kol/wallet-store.js](src/kol/wallet-store.js) (bundled [src/kol/wallets.json](src/kol/wallets.json) + admin R2 imports via `POST /api/kol/import-gmgn`), FIFO P&L engine [src/kol/wallet-pnl.js](src/kol/wallet-pnl.js), cached X follower/avatar lookup [src/kol/x-profile.js](src/kol/x-profile.js) | Live | Solana crypto KOLs ranked by realized P&L computed from each tracked wallet's own on-chain trade history (24h/7d/30d), with win rate, volume, and trade count — every number traceable to real trades, never a competitor's computed leaderboard. A wallet only shows an X handle/avatar/follower-count when an admin has explicitly attached a verified `xHandle` via `import-gmgn`'s `xHandles` map (never inferred or scraped); unattached wallets rank by wallet address alone. Rows with no configured trade source (`PUMPFUN_BOT_URL`) fall back to an imported `pnlUsd`/`winRate` labeled with its `pnlSource` rather than fabricating on-chain numbers. Prewarm cron: [api/cron/kol-tracker-refresh.js](api/cron/kol-tracker-refresh.js). |
| Agent Galaxy (every agent as a star, positioned by meaning) | [pages/galaxy.html](pages/galaxy.html) `→ /galaxy` + [src/galaxy.js](src/galaxy.js), backend [api/galaxy.js](api/galaxy.js) `→ GET/POST /api/galaxy`, assembler [api/_lib/galaxy.js](api/_lib/galaxy.js), embedding cache [api/_lib/agent-embeddings.js](api/_lib/agent-embeddings.js), live-economy overlay over `GET /api/galaxy/flows` | In-repo · awaits watsonx credentials | Every published agent embedded with an IBM Granite model on watsonx.ai, projected to 3D by PCA and grouped into k-means constellations that Granite then names, rendered as a Three.js point cloud. Typing a phrase embeds the query in the same space and lights the matching stars; the Money-Cam layer animates real on-chain transfers between them, and star brightness comes from each agent’s real wallet net worth. No mock path anywhere: with no watsonx credentials on the service `GET /api/galaxy` answers 503 and the page says so, offering the agent list and the integration doc instead of an empty universe. Tests: [tests/e2e/galaxy.spec.js](tests/e2e/galaxy.spec.js), [tests/galaxy-flows.test.js](tests/galaxy-flows.test.js) |
| The Agent Economy (live, network wide) | [pages/economy.html](pages/economy.html) `→ /economy` + page module [src/economy-live.js](src/economy-live.js), hire panel [src/shared/agent-hire.js](src/shared/agent-hire.js), feeds `GET /api/agents/economy?view=offers` ([api/agents/economy.js](api/agents/economy.js)), `GET /api/marketplace/agents`, `GET /api/agenc/x402-services` ([api/agenc/[action].js](api/agenc/%5Baction%5D.js)) over the shared discovery client [api/_lib/x402/bazaar-client.js](api/_lib/x402/bazaar-client.js) | Live | The wide-angle counterpart to the curated two-agent demo at `/agent-economy`: the real population of agents earning on three.ws, the agent-to-agent service market they hire each other through, and the live x402 bazaar of pay-per-call endpoints across Solana and Base. Three feeds, each owning its own loading / empty / error state so a slow or failing one never blanks the page, each retryable in place, and each polled every 45s while the tab is visible. Service rows name themselves from the facilitator's `metadata` when it publishes one and from the endpoint URL when it does not (most listings carry no name), show the endpoint they charge for, and never render a link to a path template or a rejected URL scheme. The A2A offers feed is empty until an owner prices an agent skill (`agent_paid_services`), which is a real state with a route out of it, not a stub. Tests: [tests/api/bazaar-endpoints.test.js](tests/api/bazaar-endpoints.test.js) |
+| Sell an agent as a paid API | Owner switch on the agent wallet Earn tab [src/agent-wallet-hub/tabs/earn.js](src/agent-wallet-hub/tabs/earn.js) (client [src/agent-economy-hub.js](src/agent-economy-hub.js)), owner API [api/agents/[id]/api-service.js](api/agents/%5Bid%5D/api-service.js) `→ GET/PUT /api/agents/:id/api-service`, paid route [api/x402/agents.js](api/x402/agents.js) `→ POST /api/x402/agents/:id` + free list `GET /api/x402/agents`, rules and ledger [api/_lib/agent-api-service.js](api/_lib/agent-api-service.js), shared turn [api/_lib/agent-turn.js](api/_lib/agent-turn.js), discovery slice `buildSellableAgentItems()` in [api/wk.js](api/wk.js) | Live | An owner flips "Sell this agent as an API", sets a USD price per call (floor $0.001, the smallest settle the facilitator co-signs) and a public description; the agent becomes a stable x402 v2 endpoint that answers one turn with the same persona, custom skills and premium-skill rules as `/api/agents/talk`. The 402 leads with Solana USDC and pays the agent's own payout wallet; the turn runs before settlement so a failed call is never charged; each settled call is written to `agent_revenue_events` (skill `agent-api`, net of `PLATFORM_FEE_BPS`, `settled_to_wallet = true` so it never counts as treasury-withdrawable). Only public agents with a brain and a Solana payout address can be sold, and the switch says why when one cannot. Agents on sale appear in `/.well-known/x402.json` and under Agents on [/x402](public/x402-stripe.html). Docs: [docs/x402.md](docs/x402.md#sell-your-agent-as-an-api), [docs/api-reference.md](docs/api-reference.md#sell-an-agent-as-an-api). Tests: [tests/api/x402-agent-api.test.js](tests/api/x402-agent-api.test.js) |
| Platform analytics (every platform total, one page) | [pages/analytics.html](pages/analytics.html) `→ /analytics` + page module [src/platform-analytics.js](src/platform-analytics.js), endpoint [api/platform/analytics.js](api/platform/analytics.js) `→ GET /api/platform/analytics?window=30d\|90d\|all`, data layer [api/_lib/platform-analytics.js](api/_lib/platform-analytics.js) | Live | The partner and investor view: agents, agents with a wallet, coins launched, 3D models generated, LLM tokens processed, x402 settlements and volume, marketplace sales and volume, and agent-to-agent hire volume, each with an all-time total, a zero-filled daily series and a `method` string rendered under "How each number is calculated". Counting predicates match the endpoints that already publish the same figure (`/api/home-stats`, the `MARKET_PAID_KINDS` gate, `platformEconomyStats()`), so no two pages disagree. A failing source is `null` plus a named `errors` entry, never a zero; the page shows an unavailable tile for it and a whole-page retry only when nothing could be read. Creator fees (SOL) read the `agent_coin_earnings` snapshot from parity order 015 with the same per-wallet counting rule as `/api/agents/:id/earnings`. Docs: [docs/api-reference.md](docs/api-reference.md#platform-analytics-api). Tests: [tests/platform-analytics.test.js](tests/platform-analytics.test.js) |
| Agent Symphony (economy as generative music) | [pages/symphony.html](pages/symphony.html) `→ /symphony`, engine [src/symphony.js](src/symphony.js), grammar [src/symphony-score.js](src/symphony-score.js) | Live | The live activity bus (`GET /api/feed` + `/api/feed-stream` SSE) rendered as WebAudio generative music: one synthesized note per real platform event, voice by event type (payments pluck, coin buys land as bass, new agents chime, guard refusals play dissonance, jackpots glissando), pitch register by amount (whales sit lower), stable per-actor motif + stereo position via FNV-1a hash, all quantized to one pentatonic scale so arbitrary event streams harmonize. Canvas visualization, live ledger with real click-throughs, and a MediaRecorder tap that exports a shareable audio clip of the master bus. A burst gate collapses event floods (a sniper sweep emitting dozens of identical guard events) into one accented note per actor per 1.5s. Solo mode narrows the stream to one participant client-side (`?agent=<id>` exact, `?actor=<label>` case-insensitive), reachable from the per-row "solo" control and from the "Listen →" link on every agent profile's Wallet Story card. No audio assets, no synthetic events. Tests: [tests/symphony-score.test.js](tests/symphony-score.test.js) |
| Platform activity feed | [pages/feed.html](pages/feed.html) `→ /feed` + [pages/community.html](pages/community.html) `→ /community`, backend [api/users/me/feed.js](api/users/me/feed.js) | Live | Reverse-chronological creation events (avatars, agents, coins, models, worlds) plus follow activity, merged at read time from `forge_creations`, `dioramas`, and `user_follows` (no separate event log to drift out of sync). `?scope=following` (default; session-gated, anonymous gets 401) vs `?scope=all` (public; powers `/community` and first-visit feeds); `limit` 1..50, `before` ISO cursor. Items deep-link to creator portfolios. Distinct from the Money Pulse ticker `GET /api/feed` ([docs/money-feed.md](docs/money-feed.md)). Docs: [docs/social-layer.md](docs/social-layer.md) |
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 9ae452700..c0e308714 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -4807,6 +4807,61 @@ Streamed responses are never idempotency-cached (a streamed body isn't buffered)
---
+## Sell an Agent as an API
+
+An owner can sell a whole agent as a pay-per-call x402 endpoint. Buyers need no account: they pay USDC on Solana straight to the agent's payout wallet. Full buyer walkthrough: [x402: Sell your agent as an API](x402.md#sell-your-agent-as-an-api).
+
+### Call an agent: `POST /api/x402/agents/:agentId`
+
+Body (JSON, up to 32 KB):
+
+| Field | Type | Notes |
+|---|---|---|
+| `message` | string, 1 to 4000 chars | Required. What the agent should answer. |
+| `history` | array, up to 20 items | Optional. Earlier turns, oldest first: `{ "role": "user" \| "assistant", "content": string }`. |
+
+Responses:
+
+| Status | Meaning |
+|---|---|
+| `402` | No payment attached. The `PAYMENT-REQUIRED` header (and body) carries the challenge: Solana USDC first, `payTo` the agent's payout wallet, `amount` the owner's price in USDC atomics. |
+| `200` | `{ "reply": string, "model": string, "usage": object \| null, "agent_id": string }`, settlement in `X-PAYMENT-RESPONSE`. |
+| `400` / `413` | Malformed or oversized body. Refused before the payment is verified, so nothing is charged. |
+| `404` | `agent_not_found`, `service_inactive` (the owner has not turned the service on), or `service_unavailable` (private agent, brain mode `none`, or no Solana payout address; `reasons` lists which). |
+| `502` / `503` | `upstream_error` / `llm_unavailable`: the turn failed. The turn runs before settlement, so the buyer is not charged. |
+
+```bash
+curl -i -X POST https://three.ws/api/x402/agents/<agentId> \
+ -H 'content-type: application/json' \
+ -d '{"message":"hi"}'
+```
+
+### List agents on sale: `GET /api/x402/agents`
+
+Free, cached 60 s. Returns `{ count, input_schema, output_schema, services: [{ agent_id, name, description, image, price_usd, price_atomics, network, network_label, asset, pay_to, url, path, method, profile_url }] }`. The same agents appear as resources in `/.well-known/x402.json` and under **Agents** in the [x402 catalog](https://three.ws/x402).
+
+### Owner switch: `GET` / `PUT /api/agents/:id/api-service`
+
+Owner only (session cookie with CSRF on `PUT`, or a bearer token). A non-owner gets `404`.
+
+`PUT` body: `{ "active": boolean, "price_usd": number, "description": string }`. `price_usd` must be between the facilitator floor ($0.001) and $50; `description` is up to 280 characters and at least 10 when `active` is true. Errors: `400 invalid_price`, `400 invalid_description`, `409 not_sellable` with `reasons` (the agent is private, has brain mode `none`, or has no Solana payout address).
+
+Both methods return the snapshot the Earn tab renders:
+
+```json
+{
+ "service": { "active": true, "price_usd": 0.05, "description": "Ask Ada about on-chain research.", "updated_at": "2026-09-30T08:26:52.022Z" },
+ "endpoint_url": "https://three.ws/api/x402/agents/<agentId>",
+ "pay_to": { "solana": "<base58>", "base": null },
+ "sellable": { "ok": true, "reasons": [] },
+ "limits": { "min_price_usd": 0.001, "max_price_usd": 50, "description_max": 280, "fee_bps": 250 },
+ "input_schema": { "type": "object", "required": ["message"] },
+ "earnings": { "calls": 0, "gross_usd": 0, "fee_usd": 0, "net_usd": 0, "net_week_usd": 0, "last_at": null, "fee_bps": 250, "recent": [] }
+}
+```
+
+Earnings come from `agent_revenue_events` rows with `skill = 'agent-api'`, recorded net of `PLATFORM_FEE_BPS` once a call settles. Those rows carry `settled_to_wallet = true`: the USDC is already in the agent's wallet, so they never count toward a treasury withdrawal.
+
## Multi-rail x402 payments (X Layer / OKX Agent Payments Protocol)
Paid MCP and A2MCP endpoints advertise **every settlement rail the deployment can serve** in a single 402 challenge — one `accepts[]` array, one entry per rail. A buyer picks the rail it can pay on.
diff --git a/docs/x402-endpoints.md b/docs/x402-endpoints.md
index 559292a76..95d6e76e9 100644
--- a/docs/x402-endpoints.md
+++ b/docs/x402-endpoints.md
@@ -122,6 +122,7 @@ buyer's USDC settles **directly** to that wallet and the platform never holds it
| -------- | -------- | ------ |
| `/api/x402/skill-call` | skill **author** | `author_payto_*` ([skill-call.js:205](../api/x402/skill-call.js#L205)) |
| `/api/x402/service` | service **provider** | `row.payout_address` ([service.js:91](../api/x402/service.js#L91)) |
+| `/api/x402/agents/:id` | the **agent** sold as an API | Solana payout wallet, else the agent's own Solana wallet (`resolveServicePayTo` in [agent-api-service.js](../api/_lib/agent-api-service.js)) |
| `/api/x402/asset-download` | 3D-asset **creator** | `creator_payto_*` ([asset-download.js:124](../api/x402/asset-download.js#L124)) |
| `/api/x402/animation-download` | clip **creator** | `creator_payto_*` ([animation-download.js:115](../api/x402/animation-download.js#L115)) |
| `/api/x402/pay-by-name` | **buyer-named** wallet | resolved name/`.sol`/address, direct SPL transfer ([pay-by-name.js:280](../api/x402/pay-by-name.js#L280)) |
@@ -225,6 +226,7 @@ datapoints at **$0.0005** USDC each by default, overridable per family with
| `/api/x402/onchain-identity-verify` | $0.005 | Verifies an on-chain identity claim. |
| `/api/x402/skill-marketplace` | $0.001 | Skill listings + pricing. |
| `/api/x402/skill-call` | per skill | Invoke a listed agent skill. |
+| `/api/x402/agents/:id` | per agent | One turn with a whole agent its owner sells as an API: `POST { message, history? }` returns `{ reply, model, usage }`. The owner sets the price; `GET /api/x402/agents` lists every agent on sale. See [Sell your agent as an API](x402.md#sell-your-agent-as-an-api). |
| `/api/x402/pump-agent-audit` | $0.02 | Audit of a pump agent's behavior/holdings. |
## Generation & 3D endpoints
diff --git a/docs/x402.md b/docs/x402.md
index 049f6b664..ad6a10a2d 100644
--- a/docs/x402.md
+++ b/docs/x402.md
@@ -23,6 +23,7 @@ import { emit402, verifyPaid, consumeIntent } from 'api/_lib/x402.js';
const paid = await verifyPaid(req, {
agentId: agent.id,
skill: 'summarize',
+ payerUserId: caller.userId, // the intent's payer
expectedAmount: '10000', // raw token units
expectedCurrency: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
});
@@ -33,10 +34,19 @@ if (!paid) {
currency: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
});
}
-await consumeIntent(paid.intentId); // single-shot
-return doTheThing();
+if (!(await consumeIntent(paid.intentId))) return res409(); // single-use lock
+try {
+ return await doTheThing();
+} catch (err) {
+ await releaseIntent(paid.intentId); // a failed call keeps the payment
+ throw err;
+}
```
+`verifyPaid` only honours an intent paid by the calling account
+(`agent_payment_intents.payer_user_id`), so an intent id seen in a log or a
+screenshot cannot spend someone else's payment.
+
Reference implementation: `api/agents/x402/[action].js` (the consolidated
`invoke` + `manifest` handler; dispatches on `?action=`).
@@ -50,16 +60,23 @@ Reference implementation: `api/agents/x402/[action].js` (the consolidated
"skill": "summarize",
"amount": "10000",
"currency": "<mint base58>",
- "recipient": "<owner wallet base58>",
+ "chain": "solana",
+ "recipient": "<payout wallet base58>",
"recipient_name": "<resolved receiver label, when known>",
"memo": "<unix-seconds nonce string>",
"valid_until": <unix>,
"intent_url": "/api/agents/payments/pay-prep",
"verify_url": "/api/agents/payments/pay-confirm",
+ "manifest_url": "/api/agents/x402/manifest?agent_id=<uuid>&skill=summarize",
"retry_with_header": "x-payment-intent"
}
```
+The 402 and the prefetch manifest resolve `recipient` with one rule
+(`resolveSkillRecipient` in `api/_lib/x402.js`): the owner's payout wallet for
+the chain, then the agent's own wallet on that chain, then the receiver stored
+in `meta.payments`. A buyer never sees two different wallets for one skill.
+
Discovery:
- `GET /.well-known/x402` — site-level resource list.
@@ -67,7 +84,7 @@ Discovery:
manifest, returned as 200 (not 402) for prefetch.
- The 402 response includes a `Link` header with `rel="payment-config"`
(pointing at `/.well-known/x402`) and `rel="payment-manifest"` (pointing at
- the per-skill manifest URL).
+ `/api/agents/x402/manifest?agent_id=…&skill=…`, the route above).
## Pricing
@@ -118,9 +135,11 @@ curl -X POST https://three.ws/api/agents/x402/invoke \
## Single-shot semantics
-A paid intent is consumed on first successful call. Failed calls don't refund —
-the intent paid for the *attempt*, not the *result*. Retrying a failed call
-requires a new intent.
+A paid intent is consumed on first successful call: the `paid` to `consumed`
+transition is the single-use lock, so two concurrent calls with one intent
+cannot both run. If the skill then fails, the intent flips back to `paid`
+(`releaseIntent`), so retrying with the same `x-payment-intent` works and the
+buyer is not charged for a call that never delivered.
For idempotency (don't double-charge on network retry), pass an
`Idempotency-Key` header — implementations are free to dedupe before
@@ -128,15 +147,90 @@ consuming the intent. Not yet enforced server-side.
## Differences from x402 mainline
-- We bind intents to `(agent, skill)` server-side — the manifest's
- `recipient` is the agent owner's wallet, but the server tracks the
- invoice via `agent_payment_intents.payload.skill`.
+- We bind intents to `(agent, skill, payer)` server-side: the manifest's
+ `recipient` is the payout wallet described above, and the server tracks the
+ invoice via `agent_payment_intents.payload.skill` and `payer_user_id`.
- We use Pump.fun's `agent_accept_payment` rather than a generic SPL
transfer. This adds buyback/burn semantics on top of the basic spec but
the wire shape (manifest + retry header) is unchanged.
- Currency is always an SPL mint pubkey. SOL-native payments aren't
supported yet.
+## Sell your agent as an API
+
+The flow above sells one skill at a time and needs a signed-in buyer. To sell
+the whole agent to anyone, including other agents with no three.ws account,
+turn on **Sell this agent as an API** on the agent wallet's Earn tab
+(`/agent-wallet?id=<agent id>`, Earn). Set a price per call in USD (the floor
+is the smallest payment the facilitator settles, $0.001) and a one-line public
+description. The agent gets a stable endpoint on the standard x402 v2 stack:
+
+ POST https://three.ws/api/x402/agents/<agent id>
+ body: { "message": "...", "history": [ { "role": "user" | "assistant", "content": "..." } ] }
+
+Who can be sold: public agents whose embed policy leaves them a brain (brain
+mode is not `none`) and that have a Solana payout address (a Solana payout
+wallet, or the agent's own custodial Solana wallet, which the Earn tab can
+create in one click). The switch refuses anything else and says why.
+
+### The buyer's flow
+
+1. **Ask for the price.** An unpaid call answers `402 Payment Required`. The
+ challenge lists Solana USDC first, with `payTo` set to the agent's own
+ payout wallet and `amount` set to the owner's price in USDC atomics
+ (6 decimals). Run it yourself against any agent that is on sale (the free
+ list below gives you one):
+
+ ```bash
+ AGENT=$(curl -s https://three.ws/api/x402/agents | node -pe 'JSON.parse(require("fs").readFileSync(0)).services[0]?.agent_id')
+ curl -si -X POST "https://three.ws/api/x402/agents/$AGENT" \
+ -H 'content-type: application/json' \
+ -d '{"message":"What can you do?"}' | grep -i '^payment-required' | cut -d' ' -f2 | tr -d '\r' | base64 -d
+ ```
+
+2. **Pay and retry.** Sign the challenge with any x402 client and repeat the
+ same request with the `X-PAYMENT` (or `PAYMENT-SIGNATURE`) header. With the
+ browser helper on three.ws:
+
+ ```js
+ const { result, payment } = await window.X402.pay({
+ endpoint: `/api/x402/agents/${agentId}`,
+ method: 'POST',
+ body: { message: 'What can you do?', history: [] },
+ });
+ console.log(result.reply, payment.transaction);
+ ```
+
+3. **Get the reply.** `200` with `{ "reply", "model", "usage", "agent_id" }`
+ and the settlement in the `X-PAYMENT-RESPONSE` header.
+
+The agent answers **before** the payment settles. If the turn fails (every
+model provider down, a provider error) you get `503 llm_unavailable` or
+`502 upstream_error` and nothing is charged. A malformed body is refused with
+`400` before the payment is even verified. Limits: `message` up to 4,000
+characters, up to 20 `history` turns, 32 KB per request.
+
+### Discovery
+
+- `GET /api/x402/agents`: free JSON list of every agent on sale, with price,
+ network, payout wallet, and the input and output schemas.
+- `/.well-known/x402.json`: each agent on sale is a resource, with the same
+ accepts the live 402 serves.
+- The [x402 catalog](https://three.ws/x402) shows them under **Agents**.
+
+### What the owner earns
+
+Every settled call writes a row to `agent_revenue_events` (skill `agent-api`)
+net of the platform fee (`PLATFORM_FEE_BPS`, default 250 = 2.5%), and the Earn tab
+shows calls, all-time and 7-day earnings, and recent payers with their
+transactions. The USDC itself settles straight into the agent's payout wallet,
+so these rows are flagged `settled_to_wallet` and never count toward a
+treasury withdrawal.
+
+Owner API: `GET` / `PUT /api/agents/:id/api-service` with
+`{ "active": true, "price_usd": 0.05, "description": "..." }` (see the
+[API reference](api-reference.md#sell-an-agent-as-an-api)).
+
## Open-source packages
The x402 toolkit is published to npm and maintained as standalone, provider-neutral
diff --git a/src/agent-economy-hub.js b/src/agent-economy-hub.js
index a018ee206..c794fde66 100644
--- a/src/agent-economy-hub.js
+++ b/src/agent-economy-hub.js
@@ -98,3 +98,12 @@ export function fetchApiService(agentId) {
export function saveApiService(agentId, config) {
return call(`/api/agents/${enc(agentId)}/api-service`, { method: 'PUT', body: config });
}
+
+/**
+ * Provision the agent's custodial Solana wallet (a fresh keypair, no on-chain
+ * transaction). The sell-as-API card offers this when the agent has no Solana
+ * payout address, which is the one thing a paid call needs to settle to.
+ */
+export function provisionSolanaWallet(agentId) {
+ return call(`/api/agents/${enc(agentId)}/solana`, { method: 'POST', body: {} });
+}
diff --git a/src/agent-wallet-hub/tabs/earn.js b/src/agent-wallet-hub/tabs/earn.js
index 0ae3bd6a3..cd6f0c16f 100644
--- a/src/agent-wallet-hub/tabs/earn.js
+++ b/src/agent-wallet-hub/tabs/earn.js
@@ -31,6 +31,7 @@ import {
setFrozen,
fetchApiService,
saveApiService,
+ provisionSolanaWallet,
} from '../../agent-economy-hub.js';
import { timeAgo, shortAddress, explorerTxUrl, explorerAddressUrl, copyToClipboard } from '../util.js';
@@ -121,7 +122,7 @@ const STYLE = `
.awh-api-switch.is-disabled { cursor: not-allowed; opacity: .6; }
.awh-api-switch input { position: absolute; opacity: 0; width: 1px; height: 1px; }
.awh-api-track { flex: none; position: relative; width: 38px; height: 22px; border-radius: 999px; background: var(--surface-3, rgba(255,255,255,.12)); transition: background var(--duration-base,220ms) var(--ease-standard,ease); }
-.awh-api-track::after { content: ''; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px; border-radius: 50%; background: var(--ink-bright,#fff); transition: transform var(--duration-base,220ms) var(--ease-standard,ease); }
+.awh-api-track::after { content: ''; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgba(0,0,0,.35); transition: transform var(--duration-base,220ms) var(--ease-standard,ease); }
.awh-api-switch.is-on .awh-api-track { background: var(--success,#4ade80); }
.awh-api-switch.is-on .awh-api-track::after { transform: translateX(16px); }
.awh-api-switch input:focus-visible + .awh-api-track { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: 2px; }
@@ -228,6 +229,7 @@ registerWalletTab({
apiMsg: null,
apiOk: false,
apiReasons: null,
+ apiProvisioning: false,
// kill switch
freezing: false,
// "earned while away"
@@ -498,8 +500,11 @@ registerWalletTab({
const dirty = on !== snap.service.active
|| String(d.price) !== String(snap.service.price_usd ?? '')
|| d.description !== (snap.service.description || '');
+ const fixWallet = !snap.pay_to?.solana
+ ? `<div class="awh-earn-save-row" style="margin-top:8px"><button class="awh-btn" type="button" data-act="api-provision" ${state.apiProvisioning ? 'disabled' : ''}>${state.apiProvisioning ? 'Creating wallet…' : 'Create its Solana wallet'}</button></div>`
+ : '';
const blockerHtml = blockers.length && !snap.service.active
- ? `<div class="awh-api-blockers" role="alert"><strong>This agent can’t be sold yet</strong><ul>${blockers.map((r) => `<li>${escapeHtml(r)}</li>`).join('')}</ul></div>`
+ ? `<div class="awh-api-blockers" role="alert"><strong>This agent can’t be sold yet</strong><ul>${blockers.map((r) => `<li>${escapeHtml(r)}</li>`).join('')}</ul>${fixWallet}</div>`
: '';
const serverReasons = state.apiReasons?.length
? `<div class="awh-api-blockers" role="alert"><strong>Not saved</strong><ul>${state.apiReasons.map((r) => `<li>${escapeHtml(r)}</li>`).join('')}</ul></div>`
@@ -645,6 +650,21 @@ registerWalletTab({
}
}
+ async function provisionWallet() {
+ state.apiProvisioning = true;
+ renderApi();
+ const res = await provisionSolanaWallet(ctx.agentId);
+ if (destroyed) return;
+ state.apiProvisioning = false;
+ if (res.ok) {
+ toast('Solana wallet created');
+ await loadApi();
+ } else {
+ toast(res.message || 'Could not create the wallet');
+ renderApi();
+ }
+ }
+
async function copyText(text, label) {
const ok = await copyToClipboard(text);
toast(ok ? `${label} copied` : 'Copy failed. Select the text and copy it by hand.');
@@ -872,6 +892,8 @@ registerWalletTab({
state.apiError = null;
renderApi();
loadApi();
+ } else if (act === 'api-provision') {
+ provisionWallet();
} else if (act === 'api-copy-url' && state.api) {
copyText(state.api.endpoint_url, 'Endpoint URL');
} else if (act === 'api-copy-curl' && state.api) {