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.

Refactor Solana Memo Media MCP: Enhance media extraction, add WebP support, and improve memo handling

nirholasb91463154fc8
diff --git a/docs/ops/livepeer-federation.md b/docs/ops/livepeer-federation.md
index 64800c591..87b5ee089 100644
--- a/docs/ops/livepeer-federation.md
+++ b/docs/ops/livepeer-federation.md
@@ -24,14 +24,19 @@ routes exactly that class:
before persistence: gateway `safety_check` screening honored, artifact bytes
must carry a real PNG/JPEG signature and clear a 1 KB floor. Dark unless
`LIVEPEER_FEDERATION_ENABLED` is truthy.
-- Chain position in `api/_mcp3d/text-to-image.js`: after the first-party free
- lanes (Vertex/NIM cost the platform nothing), before the paid Replicate
- backstop ($0.003/image). A successful federated call is strictly cheaper
- than every remaining option at that point in the ladder.
+- Chain position in `api/_mcp3d/text-to-image.js`: after the first-party
+ lanes (Vertex/NIM) and the HF-routed FLUX rungs (fal-ai, then nscale, when
+ `HF_TOKEN` is set), before the keyless Pollinations rung and the paid
+ Replicate backstop ($0.003/image). Like every rung, it runs under the
+ ladder's one shared budget (`TEXT_TO_IMAGE_BUDGET_MS`, default 60s), so its
+ own 90s ceiling is capped by whatever is left and a stalled gateway hands
+ off instead of hanging the submit.
- `api/_lib/image-persist.js`: the persist-to-R2 rule was copy-pasted between
`text-to-image.js` and `forge-reference-image.js`; the adapter needed a
third copy, so the rule now lives in one module and both call sites import
- it. No behavior change.
+ it. When the bucket refuses the write (a storage-infrastructure fault such
+ as a rejected credential), it now returns an inline `data:image/` URI under
+ 4 MB instead of throwing, which the platform's own GPU workers read directly.
- `scripts/livepeer-federation-bench.mjs`: the comparison harness. Runs N
real jobs per lane, reports latency/success/cost per lane with failure
classes, and writes a JSON report.
diff --git a/docs/pay-skills-listing.md b/docs/pay-skills-listing.md
index a6910c33d..040562b4d 100644
--- a/docs/pay-skills-listing.md
+++ b/docs/pay-skills-listing.md
@@ -12,7 +12,7 @@
three.ws is an agent-first 3D model platform. Paid REST endpoints cover glTF/GLB model
validation, Solana token visualization, Pump.fun agent analytics, on-chain identity
verification, and a Claude-backed growth-analysis power. All endpoints settle in USDC
-on Solana mainnet, with Base (and Arbitrum for model-check) as the alternative EVM
+(or $THREE) on Solana mainnet, with Base (and Arbitrum for model-check) as the alternative EVM
rails; Solana is the first accept in every 402 challenge, so a client that takes
the first accept settles there. The MCP server exposes the same surface as
JSON-RPC tools.
@@ -35,7 +35,7 @@ are the source of truth and match what the 402 challenges advertise; verify with
| `/api/x402/agent-reputation` | GET | $0.01 | Reputation snapshot for a three.ws agent: USDC paid in, distinct payers, deployed mints, distribution success rate, attestation count |
| `/api/x402/fact-check` | POST | $0.10 | Sourced fact-check verdict (supported/contradicted/mixed/insufficient) with cited sources, authority weights, and a SHA-256 attestation |
| `/api/x402/mint-to-mesh-batch` | POST | $0.05 | Resolve 1–10 Solana SPL mints to themed GLB cubes in one call; per-mint failures report individually |
-| `/api/x402/pump-launch` | POST | $5.00 | Deploy a brand-new pump.fun token in one paid call. Supply name + symbol + (metadataUri or imageUrl); the server fronts the SOL deploy cost and signs the create-coin tx. Creator rewards accrue to any Solana wallet you nominate; optional vanity mint address. Returns mint + tx signature + pump.fun URL |
+| `/api/x402/pump-launch` | POST | $5.00 | Deploy a brand-new pump.fun token in one paid call. Supply name + symbol + (metadataUri or imageUrl); the server fronts the SOL deploy cost and signs the create-coin tx. Creator rewards accrue to any Solana wallet you nominate, or pass `holderReward: true` to route creator fees to holders through the pump.fun holder-rewards PDA; optional vanity mint address. Returns mint + tx signature + pump.fun URL |
All prices are in USDC with 6 decimals. `$0.001` = 1000 atomics.
@@ -90,7 +90,12 @@ are supported.
- Every 402 challenge echoes the resource URL both at top-level `resource.url` AND in
each `accepts[].resource`, so wallet/facilitator spend logs reconcile cleanly without
relying on the buyer to remember which endpoint they hit.
-- Solana routes require a `feePayer` field in the accept block (included automatically
- in the 402 challenge) for PayAI's `/verify` to accept the SPL transfer.
+- Solana accepts normally carry `extra.feePayer` (the platform sponsor, included
+ automatically in the 402 challenge), and an external facilitator such as PayAI
+ requires it at `/verify`. When three.ws settles in-house and the sponsor wallet
+ cannot co-sign, the accept is advertised without `feePayer`: the buyer signs as
+ their own fee payer (self-pay) and needs a little SOL for the network fee.
+- On Solana, `$THREE` is offered as a second accept alongside USDC on the same
+ challenge.
- No public key-generation endpoints. three.ws does not run any server-side vanity-key
or keypair-generation paid endpoint — wallet keys never leave the buyer's environment.
diff --git a/docs/shipfeed.md b/docs/shipfeed.md
index 08506ac55..85ba44cfb 100644
--- a/docs/shipfeed.md
+++ b/docs/shipfeed.md
@@ -2,7 +2,7 @@
Every project keeps two records of the same work.
-The **commit log** is complete and unreadable. The **changelog** is readable and incomplete. On three.ws both are published, both are pushed to the holder Telegram channel, and until now neither knew the other existed. The same afternoon's work reached the same channel twice, in two voices, with nothing saying it was the same work.
+The **commit log** is complete and unreadable. The **changelog** is readable and incomplete. On three.ws both are published, both are pushed to the community Telegram channel, and until now neither knew the other existed. The same afternoon's work reached the same channel twice, in two voices, with nothing saying it was the same work.
The ship log is the join. Live at **[three.ws/ship](https://three.ws/ship)**, served as data at **[/api/ship/feed](https://three.ws/api/ship/feed)**, and computed by an open-source package, **[@three-ws/shipfeed](../packages/shipfeed/README.md)**, that works on any repository.
@@ -27,7 +27,7 @@ GitHub /repos/nirholas/three.ws/commits public/changelog.json
│
┌──────────────┼───────────────────────┐
▼ ▼ ▼
- /api/ship/feed /ship page the holder Telegram lanes
+ /api/ship/feed /ship page the community Telegram lanes
(JSON, MD, RSS) (provenance footer + noise filter)
```
@@ -140,7 +140,7 @@ curl -s 'https://three.ws/api/ship/feed?format=rss' # a feed reader, with c
## What changed in the Telegram channel
-Two lanes post to the holders' channel, and they now share this one join.
+Two lanes post to the community channel, and they now share this one join.
**Release announcements** (`/api/cron/changelog-push`, every 20 minutes) carry a provenance footer:
@@ -154,7 +154,7 @@ shipped in 4 commits ← links to the GitHub compare view for the range
three.ws/changelog/2026-08-27-text-to-3d-... · 2026-08-27 · #fix #infra
```
-The footer is best-effort by design: if GitHub cannot be read at that moment, the announcement goes out without it rather than not going out.
+The footer is best-effort by design: if GitHub cannot be read at that moment, the announcement goes out without it rather than not going out. Entries are keyed by date and title, and repeats of one key within a batch are collapsed before sending, so a duplicated line in `data/changelog.json` never reaches the channel twice.
**The raw commit feed** (`/api/cron/commit-feed-push`, every 5 minutes) reads its headline from the same parser, so a scoped commit now says "Feature · resilience" rather than "feat(resilience)", and it skips commits the classifier calls noise: merges, `chore(deps):` bumps, and lockfile-only changes. A skipped commit still advances the lane's state, so nothing is ever re-read, and the tick reports `{ posted, skipped }` so the drop is visible in the logs rather than silent.
diff --git a/docs/ux-flows/09-x402-agent-commerce.md b/docs/ux-flows/09-x402-agent-commerce.md
index 23cb9aa8f..9ab1388cc 100644
--- a/docs/ux-flows/09-x402-agent-commerce.md
+++ b/docs/ux-flows/09-x402-agent-commerce.md
@@ -142,10 +142,10 @@ choreographed two-agent narrative driven by Server-Sent Events.
3. Click **Run Task** → button "Running…", skeleton cards shown.
4. `POST /api/agents/endpoint-shopper-run` with `{ task, maxCostUsd }` → agent emits a step trace: **discover** 🔍 → **plan** 🗺 → **call** ⚡ (per endpoint, with URL + USDC cost + snippet) → **synthesize** 🧠.
5. Timeline renders all steps; **Total spent** row ("$0.00…" or "Free"); **Final Answer** card with synthesized text. Button re-enabled.
-- **Decision points / branches:** empty task / budget < $0.01 → button disabled + hint; `402` → paywall card "Pay with Wallet" → `/paywall.html?req=…&return=/shopper`; `400`/`5xx`/network → error card + retry.
+- **Decision points / branches:** empty task / budget < $0.01 → button disabled + hint; `402` → paywall card "Pay with Wallet" → `/paywall.html?req=…&return=/shopper`; `400`/`5xx`/network → error card + retry. The error card never repeats the run route's machine output (a snake_case code such as `no_payto_configured`, or a diagnostic with a module prefix such as `paidEndpoint:`): a `5xx` reads "The agent service is temporarily unavailable", a lost connection says the service could not be reached, and a `4xx` uses the server's text only when it reads as a sentence for a person (`readableServerMessage`), else designed copy.
- **External calls / dependencies:** `/api/agents/endpoint-shopper-run`, downstream x402 endpoints discovered via the Bazaar, `/paywall.html`.
- **Success state:** full step timeline + final answer + total cost; ready for a new task.
-- **Empty / error states:** initial skeleton/empty hint ("Enter a task…"); `402` warning card with CTA; red error card with retry; "Free (no paid calls executed)" if only free steps ran.
+- **Empty / error states:** initial skeleton/empty hint ("Enter a task…"); a run that returns no plan and no answer → "No endpoints matched" card quoting the task, with rewrite / raise budget / browse the Bazaar suggestions and a run-again button; `402` warning card with CTA; red error card with retry; "Free (no paid calls executed)" if only free steps ran.
- **Step count:** 5 required (+3 optional).
### Fact Checker — `/fact-checker`
@@ -296,20 +296,20 @@ choreographed two-agent narrative driven by Server-Sent Events.
---
### Sniper Arena — `/play/arena`
-- **Source:** `pages/play/arena.html` + `src/play/arena.js`; backend `api/sniper/leaderboard`, `api/sniper/stream` (SSE), `api/sniper/trader`, `api/oracle/agent-stats`.
+- **Source:** `pages/play/arena.html` + `src/play/arena.js` + `src/play/rivalries.js`; backend `api/sniper/leaderboard`, `api/sniper/rivalries` (see `docs/rivalries.md`), `api/sniper/stream` (SSE), `api/sniper/trader`, `api/oracle/agent-stats`.
- **Entry point:** A 3D world where **autonomous** AI agents trade real pump.fun tokens on Solana mainnet, live. Left = live leaderboard; right = live trade tape; bottom = movement hints. **No x402 micropayments here** — agents have pre-funded wallets and trade autonomously.
- **Prerequisites / gates:** None to watch. Picking an avatar is local (`localStorage arena:avatar:v1`), no payment. Agents trade with their own funded Solana wallets.
- **Steps (4 required + 3 optional):**
- 1. **[auto]** Page boots `ArenaWorld` (Three.js 60fps), loads animation manifest + default avatar GLB, fetches `/api/sniper/leaderboard?network=mainnet`, opens SSE `/api/sniper/stream`.
- 2. **[auto]** Agents spawn (deterministic avatar by `agent_id` hash, arc formation, floating DOM labels with rank/name/P&L).
+ 1. **[auto]** Page boots `ArenaWorld` (Three.js 60fps) and, without waiting on the 3D load, fetches `/api/sniper/leaderboard?network=mainnet` and mounts the grudge-match strip (`GET /api/sniper/rivalries?window=7d&lookback=24h&limit=2`, refreshed every 90s: each row pairs a trader with the one above them, labelled Passed / Debut / Chasing, with links to the leader's record and Ghost-copy). The board and tape paint while the animation manifest + avatar GLB download; the loading curtain sits below the side panels, so it only hides the empty canvas. Once the world is walkable, SSE `/api/sniper/stream` opens after the first board read.
+ 2. **[auto]** Agents spawn once the world is ready (deterministic avatar by `agent_id` hash, arc formation, floating DOM labels with rank/name/P&L).
3. **[auto/live]** SSE `buy`/`sell`/`update` events → agent emotes + particle burst, trade tape prepends (BUY/SELL ▲▼, symbol, Solscan link), big-win banner, board refresh.
4. **[user, optional]** **Choose your avatar** → modal → select → spawn player (saved to localStorage).
5. **[user, optional]** Move with WASD / drag look / scroll zoom / touch joystick.
6. **[user, optional]** Click an agent label → camera focus + right drawer profile (equity sparkline, stats grid, recent closed trades with on-chain proof, Oracle conviction section) → **Full proof & copy ↗** → `/trader/<agent_id>` new tab.
- **Decision points / branches:** fully autonomous trading — user only watches/moves/inspects; SSE vs periodic board refresh; avatar selection local; focus/unfocus; big-win banner threshold (≥0.4◎ or ≥100%).
-- **External calls / dependencies:** `/api/sniper/leaderboard`, `/api/sniper/stream` (SSE), `/api/sniper/trader`, `/api/oracle/agent-stats`, `/animations/manifest.json`, avatar GLBs, Solscan, `/trader/<id>`. Solana mainnet (real pump.fun trades).
+- **External calls / dependencies:** `/api/sniper/leaderboard`, `/api/sniper/rivalries`, `/api/sniper/stream` (SSE), `/api/sniper/trader`, `/api/oracle/agent-stats`, `/animations/manifest.json`, avatar GLBs, Solscan, `/trader/<id>`. Solana mainnet (real pump.fun trades).
- **Success state:** agents render + leaderboard + live tape; user can move + inspect; real trades animate in real time.
-- **Empty / error states:** no live agents → "No agents are live yet… arm a trader and enter"; SSE drop → "Reconnecting…" (retry 2.5s); board fetch fail → keep last good; drawer fail → "Couldn't load this trader"; avatar load fail → mono-initial tile.
+- **Empty / error states:** no live agents → "No agents are live yet… arm a trader and enter"; SSE drop → "Reconnecting…" (retry 2.5s); board never read → "Can't reach the leaderboard." + **Retry now** (KPI strip hidden); refresh fail after a good read → "Standings are stale." keeping the last good board and its KPI strip; rivalries → skeleton, an empty note when fewer than two traders have 3+ closed round-trips, or "Can't reach the rivalry feed." + Retry; drawer fail → "Couldn't load this trader"; avatar load fail → mono-initial tile.
- **Step count:** 4 required (auto boot) + 3 optional (avatar, move, inspect).
### Agent Exchange (feature page) — `/features/agent-exchange`
@@ -331,6 +331,7 @@ choreographed two-agent narrative driven by Server-Sent Events.
- **Routing:** all clean URLs resolve through the `vercel.json` route table — read directly by the Cloud Run server (`server/index.mjs`) in production and mirrored by the `vite.config.js` `historyApiFallback` map in dev. `/pay`, `/bazaar`, `/arbitrage`, `/providers`, `/forever`, `/tutor` live under `public/`; the rest under `pages/`.
- **Shared payment modal:** `/x402.js` (`public/x402.js`, ~2.4k LOC) is the drop-in `window.X402.pay()` modal used by `/pay/c`, `/bazaar`, `/arbitrage`, `/ibm/x402-demo`, `/shopper` (paywall), `/fact-checker`, `/unstoppable`, `/tutor`. It handles wallet connect (Phantom/Solana, MetaMask/Base via EIP-3009), the 402→sign→retry loop, and SIWX re-entry. Its Solana web3.js and SIWX hashing imports go through `/load-module.js` (the pinned version on esm.sh, then jsdelivr, then unpkg, each under a deadline); only when all three fail does the modal steer the buyer to MetaMask on Base, which needs no third-party code. A cross-origin endpoint whose response carries no CORS headers is reported as "<host> does not allow browser requests" with a pointer to a server, an agent, or the x402 CLI, and no Try-again button.
+- **Chain order in the 402:** every `paidEndpoint` route in this cluster (`/api/x402/fact-check`, `/api/x402/tutor`, `/api/x402/symbol-availability`, and the rest) inherits the platform default of Solana first, then Base, so the live challenge lists networks in the same order the discovery catalog advertises and a client that takes the first accept settles on Solana. `tests/x402-solana-first-ordering.test.js` fails the suite if a route pins Base first again.
- **Server-payer vs user-payer:** the "agent economy" narratives (`/agent-exchange`, `/agent-trade`, `/agent-economy`, `/demo`, `/live`) pay from **server-held agent wallets** and stream the choreography over SSE — the user only triggers/selects, then watches. The "showcase" apps (`/shopper`, `/fact-checker`, `/tutor`, `/bazaar`, `/arbitrage`, `/ibm`) make the **user** pay via the `/x402.js` modal.
- **Auto-play demos:** `/agent-exchange`, `/agent-trade`, `/agent-economy`, `/demo` need one user click to start, then auto-play. `/live` adds an auth gate for real settlement. `/play/arena` is fully autonomous (agents trade themselves; user only watches/moves/inspects) and uses **no x402** — real pre-funded Solana trades.
- **Forever** is the only **non-x402** payment in the cluster: native Bitcoin (or Lightning) to an OrdinalsBot charge address, inscribing a real Taproot text inscription on Bitcoin mainnet.
diff --git a/docs/ux-flows/10-chat-brain-labs.md b/docs/ux-flows/10-chat-brain-labs.md
index 27c5bb0da..19dee061d 100644
--- a/docs/ux-flows/10-chat-brain-labs.md
+++ b/docs/ux-flows/10-chat-brain-labs.md
@@ -158,13 +158,13 @@ modules. Routes resolved via `vercel.json` rewrites.
### Club — 3D Pole-Stage Venue (x402) — `/club`
- **Source:** `/workspaces/three.ws/pages/club.html` → scripts: `/x402.js` (wallet/payment modal), `/workspaces/three.ws/src/club-entrance.js` (walk-in alley scene), `/workspaces/three.ws/src/club-gate.js` (cover-charge bouncer), `/workspaces/three.ws/src/club.js` (main pole stage). Supporting modules in `src/`: `club-venue.js`, `club-audio.js`, `club-camera.js`, `club-crowd.js`, `club-perf.js`, `club-sequence.js`, `animation-manager.js`.
- **Entry point:** `/club` → `club.html`; entrance scene + door gate + pole stage boot in parallel behind a loading screen.
-- **Prerequisites / gates:** **x402 wallet payment** — a cover charge settled on-chain (USDC, via `/api/x402/club-cover`); wallet (Phantom / EVM) connected through `x402.js`. No $THREE gate (USDC-denominated x402). WebGL required.
+- **Prerequisites / gates:** **x402 wallet payment** — a cover charge settled on-chain via `/api/x402/club-cover`; wallet (Phantom / EVM) connected through `x402.js`. The one door's 402 quotes both USDC and $THREE on Solana (while `X402_ACCEPT_THREE_SOLANA` is on, the default), so the checkout shows a token chooser with each token's real price and either token issues the same pass. Paying in $THREE is optional, not a gate. WebGL required.
- **Steps (7):**
1. Open `/club`; loading screen with real GLB byte-count progress; avatar picker populates (bundled + gallery avatars via `/api/avatars/` and `/api/explore`).
2. (optional) Select an avatar.
3. Spawn in the entrance scene; move with WASD / touch joystick, look via drag.
4. Walk to the neon door → "Enter the club" prompt; activate it.
- 5. Door reveals the x402 cover screen; connect wallet and pay the cover → a paid `GET /api/x402/club-cover` (x402, `club-gate.js`) settles on-chain and checks the gate.
+ 5. Door reveals the x402 cover screen; connect wallet, pick USDC or $THREE in the token chooser, and pay the cover → a paid `GET /api/x402/club-cover` (x402, `club-gate.js`) settles on-chain and checks the gate.
6. On approval the rope drops; walk through to the pole stage — entrance fades, main `club.js` stage becomes active (dancers at poles, leaderboard, live tip feed).
7. Select a pole + dance style and tip → `POST /api/x402/dance-tip`; on settlement the dancer performs the routine, leaderboard + live feed update, reactions float up.
- **Decision points / branches:** avatar choice; cover approved vs "not tonight"; wallet not connected / insufficient balance; tip per pole + dance style; back-out to alley while paying; entrance-GLB failure → drop straight to stage.
diff --git a/docs/x402-endpoints.md b/docs/x402-endpoints.md
index 8c73188ce..725a40eab 100644
--- a/docs/x402-endpoints.md
+++ b/docs/x402-endpoints.md
@@ -36,8 +36,13 @@ Endpoints advertise the networks they accept in the 402 challenge. The platform
settles **USDC on Solana** (primary, always-on via the self-hosted facilitator)
and, when configured, **USDC on Base** (EVM) and a **BSC leg** (contract-mediated
`direct` scheme, advertised only when `X402_PAY_TO_BSC` is set). On the Solana
-rail, `X402_ACCEPT_THREE_SOLANA` optionally advertises **$THREE** alongside USDC
-as a second accept entry on the same challenge. The relevant config (see
+rail, `X402_ACCEPT_THREE_SOLANA` (on by default) advertises **$THREE** alongside
+USDC as a second accept entry on the same challenge; the browser checkout renders a
+token chooser whenever a resource quotes more than one asset on a network, so a
+buyer can actually pay in either. `paidEndpoint` lists networks Solana first, then
+Base; a handler passes `networks` only to narrow that set, and
+`tests/x402-solana-first-ordering.test.js` fails any handler that pins a non-Solana
+network first. The relevant config (see
[Configuration](configuration.md)):
| Key | Meaning |
@@ -64,22 +69,35 @@ endpoint logic, and issues a signed receipt.
### When settlement capacity runs dry
-Solana settles in sponsor mode: the platform's fee wallet
+Solana normally settles in sponsor mode: the platform's fee wallet
(`X402_FEE_PAYER_SOLANA`) co-signs and pays the network fee. The
-self-facilitator refuses to settle whenever that wallet drops below
-`X402_SPONSOR_SOL_FLOOR_LAMPORTS` (0.02 SOL), which protects the wallet from
-being drained to zero mid-flight. That refusal is **temporary capacity, not an
-outage**, and the whole path says so:
-
-| Layer | Behaviour while the sponsor is below its floor |
-| ------------------------- | -------------------------------------------------------------------------------------------------------------- |
-| 402 challenge | The Solana accept is **not advertised**. Other configured networks still are, so the endpoint stays payable. |
-| No network left to offer | `503 settlement_unavailable`, retryable, never the `500 no_payto_configured` misconfiguration error. |
-| A payment that still lands | `503 settlement_unavailable`. Only a genuinely unexplained settle failure is `502 settle_failed`. |
+self-facilitator refuses a sponsored settle whenever that wallet would end below
+`X402_SPONSOR_SOL_FLOOR_LAMPORTS` (default 0.02 SOL) **after paying the settle's
+own cost** (including ~0.00204 SOL of ATA rent when the receiver has never held
+the mint), which protects the wallet from being drained to zero mid-flight.
+
+Sponsoring gas is a convenience, not a precondition for being paid. When we
+settle in-house (the self-hosted facilitator) and the sponsor cannot co-sign (no
+key loaded, or known below its floor), both accept builders (`buildRequirements()`
+in `x402-paid-endpoint.js` and `paymentRequirements()` in `x402-spec.js`) keep
+advertising the Solana USDC and $THREE accepts **without `extra.feePayer`**. That
+is the self-pay contract: the buyer signs as their own fee payer and the
+facilitator only broadcasts, spending none of our SOL. Sponsored mode resumes on
+its own once the wallet is refunded. Self-pay is never offered when Solana routes
+to an external facilitator, which pins the sponsor and would reject the challenge
+at `/verify`.
+
+| Situation | Behaviour |
+| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
+| Sponsor below floor, in-house facilitator | Solana accepts are advertised in self-pay mode (no `feePayer`); the endpoint stays payable on Solana. |
+| Sponsor below floor, external facilitator | The Solana accept is not advertised. Other configured networks still are. |
+| No network left to offer | `503 settlement_unavailable`, retryable, never the `500 no_payto_configured` misconfiguration error. |
+| Sponsored payment lands while the wallet is short | `503 settlement_unavailable` (`fee_wallet_below_floor`, `fee_wallet_cannot_cover_settle`). Only a genuinely unexplained settle failure is `502 settle_failed`. |
+| Self-pay buyer cannot cover the network fee | `402 insufficient_fee_balance` (`buyer_cannot_cover_fee`): add a little SOL and pay again. No top-up of ours helps. |
**Buyers should treat `503 settlement_unavailable` as retry-after**, the same as
-any capacity signal. No signed payment is consumed by a doomed settle, and the
-accept reappears automatically within about a minute of the wallet being
+any capacity signal. No signed payment is consumed by a doomed settle, and
+sponsored mode reappears automatically within about a minute of the wallet being
refunded (each instance re-reads the balance at most once per 20s).
Operators: the funding root tops the fee wallet back up automatically
@@ -87,7 +105,9 @@ Operators: the funding root tops the fee wallet back up automatically
wallet in the default deployment, the sweep reserves the settle floor plus
`ECONOMY_MASTER_SPONSOR_HEADROOM_SOL` (0.03) on top of its own reserve, so
funding engines can never starve settlement. Check the effective value in the
-cron's `sweepFloorSol` field.
+cron's `sweepFloorSol` field. When the master is thin, settle-critical fee wallets
+are funded before float wallets regardless of which has the larger deficit, and a
+skip reason distinguishes a dry master from a run cap that genuinely bound.
## Where payments land
@@ -213,12 +233,12 @@ datapoints at **$0.0005** USDC each by default, overridable per family with
| ----------------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------- |
| `/api/x402/forge` | tiered | Text/image → 3D model (price by tier; GPU-bound). Every settled generation also lands in the public community gallery (`forge_creations`) stamped with the payer, settle signature, and price; the gallery shows a Solscan-linked "x402" provenance badge. See [Avatar pipeline](avatar-pipeline.md). |
| `/api/x402/embody` | $1.00 | **Embodiment.** One call, an agent buys itself a body: prompt or image in → rigged, voiced 3D avatar out, plus a durable persona id and a one-tag `<iframe>` embed for any website. Settles on delivery — a failed generation never charges. See [Embodiment](embody.md). |
-| `/api/x402/pipeline` | per stage | **One call, full 3D asset pipeline** — text or GLB in, rigged/optimized game-ready GLB out. Ordered chain of `generate → rig → remesh → gameready → stylize`; the 402 quote is the exact sum of the requested stages. Poll free at `/api/forge?job=<id>` for per-stage progress. See [3D pipeline](3d-pipeline.md). |
+| `/api/x402/pipeline` | per stage | **One call, full 3D asset pipeline** — text or GLB in, rigged/optimized game-ready GLB out. Ordered chain of `generate → rig → remesh → gameready → stylize`; the 402 quote is the exact sum of the requested stages. Poll free at `/api/forge?job=<id>` for per-stage progress. A bare POST with no body (how listing validators probe a paid row) gets the 402 priced at the catalog's example chain; the body validation error is raised only for a caller that pays. See [3D pipeline](3d-pipeline.md). |
| `/api/x402/pipeline-rig` | $0.05 | **Pipeline — Rig.** Static GLB in → animation-ready rigged GLB out (skeleton + skin weights). One paid call, durable URL. See [3D pipeline](3d-pipeline.md). |
| `/api/x402/pipeline-remesh` | $0.03 | **Pipeline — Remesh.** Retopologize a GLB (triangle/quad/lowpoly, repair, decimate to a face budget) with texture re-baked. GLB in → GLB out. See [3D pipeline](3d-pipeline.md). |
| `/api/x402/pipeline-gameready` | $0.03 | **Pipeline — Game-Ready.** Retopologize to a poly budget + PBR re-bake for real-time engines. GLB in → engine-ready GLB out. See [3D pipeline](3d-pipeline.md). |
| `/api/x402/pipeline-stylize` | $0.03 | **Pipeline — Stylize.** Geometric restyle (voxel/brick/voronoi/lowpoly) that rebuilds the mesh. GLB in → GLB out. See [3D pipeline](3d-pipeline.md). |
-| `/api/x402/pipeline-rembg` | $0.01 | **Pipeline — Background Removal.** Image in → transparent PNG out (clean reference view for image→3D). See [3D pipeline](3d-pipeline.md). |
+| `/api/x402/pipeline-rembg` | $0.01 | **Pipeline — Background Removal.** Image in → transparent PNG out (clean reference view for image→3D). `model`: `rmbg2` (default), `birefnet` (cleanest hair and thin edges, ~6 s), `u2net_human_seg`, `isnet`, `u2net`, `silueta`. See [3D pipeline](3d-pipeline.md). |
| `/api/x402/mint-to-mesh`, `/api/x402/mint-to-mesh-batch` | $0.001 | Token/mint → 3D mesh; `mint-to-mesh-batch` runs a set at $0.05. |
| `/api/x402/model-check`, `/api/x402/model-validation-sweep` | $0.001 | Validate a GLB / sweep a batch. (`model-check` is kept as a paid convenience; the same inspection is free at `/api/3d/inspect`.) |
| `/api/x402/avatar-optimize-batch` | $0.001 | Batch optimization pass over the top N avatars. |
@@ -232,7 +252,7 @@ datapoints at **$0.0005** USDC each by default, overridable per family with
| [`/api/x402/vanity`](vanity.md) | $0.01–$0.50 (≤3) · $2.50–$10 (4–5, inventory-only) | **Vanity Grinder** — get a brand-new Solana address that starts with your ticker/prefix and/or ends with a suffix, for a branded token mint or agent/treasury wallet. Checks the pre-ground warehouse first for **instant delivery** (`source: "inventory"`); falls back to a live grind (`source: "ground"`) up to 3 chars. Keypair or importable BIP-39 mnemonic; nothing stored; optional `sealTo` ECIES. Full doc: [vanity.md](vanity.md). |
| [`/api/x402/vanity-verifiable`](vanity.md#tier-2--provably-fair-grinder) | $0.02–$0.40 | **Provably-fair grinder** — same grind with a signed commit–reveal receipt proving the key was ground fresh and never kept. Spec: [PROTOCOL-vanity.md](PROTOCOL-vanity.md). |
| [`/api/x402/vanity-premium`](vanity.md#tier-3--premium-inventory) | $1–$50 by rarity | **Premium inventory** — buy a pre-ground 4–5+ char brandable address from stock. GET lists available patterns + prices (free); `?address=…` buys via x402 and delivers the key **once** (ciphertext destroyed on delivery). Browsable at `/vanity/premium`. |
-| `/api/x402/pay-by-name` | $0.001 | Resolve and pay a `@username` / `.sol` name / raw address (see [Agent wallets](agent-wallets.md)); the paid resolve toll is $0.001, the transfer amount itself is buyer-specified. A name that resolves to nothing returns `404 not_found` and the payment is left unsettled, so an unresolvable name is free. |
+| `/api/x402/pay-by-name` | $0.001 | Resolve and pay a `@username` / `.sol` name / raw address (see [Agent wallets](agent-wallets.md)); the paid resolve toll is $0.001, the transfer amount itself is buyer-specified. A name that resolves to nothing returns `404 not_found` and the payment is left unsettled, so an unresolvable name is free. A body-less POST lands on this paid resolve lane and gets the 402 challenge (the free prep flow must say `mode: "prep"` or carry its wallet/amount fields). |
| `/api/x402/did` | $0.001 | **POST** is the DID verification canary: it resolves three.ws's published W3C DID document over its real public route, structurally validates it, and returns `{ verified, latency_ms, configured, checks }`. `configured: false` means the resolver answered 404 or could not be reached at all. `mode: "sweep"` audits recent agent identities for resolvable key material instead. **GET** is the free publisher for `/.well-known/did.json`; every other verb returns `405`. |
| `/api/x402/three-buy` | $0.001 | Micro-buy service: one settled toll payment triggers one small, real on-chain USDC to $THREE buy funded by the micro-buy wallet (driven by the `three-buy-loop` cron). |
| `/api/x402/knock` | set by recipient | **Knock**: pay a person's own price and get exactly one message through to them, in person. The recipient sets what a moment of their attention costs and the USDC settles straight to their wallet, never the platform's, so a priced door cannot be opened without one. The accepted message becomes a companion event whose importance is derived from the amount paid, and their 3D companion walks on screen wherever they are and delivers it out loud. Body is validated against that door's limits before any 402 is issued, so nobody pays for a message that was going to be refused. |
@@ -269,7 +289,7 @@ directory.
| Endpoint | Default | Returns |
| ---------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `/api/x402/analytics` | $0.005 | Platform reports: club and listing analytics. |
+| `/api/x402/analytics` | $0.005 | Platform reports: club and listing analytics. The volume report's gross totals include the internal ring, so it carries a `revenue_split` block (external / internal ring / synthetic, or `null` when it cannot be computed). |
| `/api/x402/mcp-tool-catalog` | $0.001 | Snapshot of every MCP tool (name, paid/free, price, input shape) and a diff vs the last snapshot (added / removed / re-priced tools). |
| **Free read surfaces** | — | — |
| `/api/x402/my-receipts` | free | A buyer's own settled receipts, gated by a wallet signature (SIWX) rather than a payment. |
diff --git a/packages/solana-memo-media-mcp/README.md b/packages/solana-memo-media-mcp/README.md
index 23724d318..007d3f7b7 100644
--- a/packages/solana-memo-media-mcp/README.md
+++ b/packages/solana-memo-media-mcp/README.md
@@ -27,20 +27,33 @@ For Cursor, Claude Desktop, or another stdio MCP client:
| Tool | Purpose |
| --- | --- |
-| `extract_solana_memo_media` | Fetch one finalized transaction and extract supported image data URIs from top-level and inner Memo instructions. |
+| `extract_solana_memo_media` | Fetch one legacy, v0, or v1 transaction and return every supported image in its top-level and inner Memo instructions, with signer, slot, and version. |
+| `find_solana_memo_media` | Scan up to 1,000 recent signatures for an address (pageable with `before`). Only signatures whose memo summary holds a data URI are fetched, so a scan costs a handful of RPC calls. |
| `decode_solana_memo_data_uri` | Decode one already-copied data URI locally. No network call. |
-| `find_solana_memo_media` | Inspect up to 20 recent finalized transactions for an address and return matching memo media. |
-| `get_solana_memo_media_status` | Show the local policy and RPC failover hosts. No network call. |
+| `get_solana_memo_media_status` | Show the local policy, recognized memo programs, and RPC failover hosts. No network call. |
+
+Recognized memo programs: SPL Memo v1 (`Memo1UhkJRfHyvLMcVLMbLJYfW2tfU8G8H4PqvV6v8`), SPL Memo v2 (`MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr`), and the newer program carried by version 1 transactions (`Memo4c2pN8afCj432Lb7RMVKi9PbQnnW7ewFFaV3oAH`).
## Example
-Ask an MCP client: "Show any image embedded in Solana transaction `<signature>`." It calls:
+Ask an MCP client: "Show any image embedded in Solana transaction `<signature>`." It calls `extract_solana_memo_media` with:
```json
{ "signature": "<base58 Solana transaction signature>" }
```
-The response includes a concise JSON record plus MCP `image` content. JSON metadata contains the source signature, MIME type, byte length, SHA-256, and dimensions when the file format exposes them. The raw data URI is intentionally not echoed into text output.
+The response is a JSON record plus one MCP `image` content block per asset. The record carries the signature, fee payer, slot, transaction version, and for each asset its MIME type, byte length, SHA-256, and dimensions. The raw data URI is intentionally not echoed into text output.
+
+Use it from your own code:
+
+```js
+import { decodeDataUri } from '@three-ws/solana-memo-media-mcp/src/lib/media.js';
+
+const media = decodeDataUri('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/lwV8YQAAAABJRU5ErkJggg==');
+console.log(media.mimeType, media.byteLength, media.dimensions, media.sha256);
+```
+
+Full guide: [docs/mcp-solana-memo-media.md](../../docs/mcp-solana-memo-media.md).
## Safety and provenance
diff --git a/packages/solana-memo-media-mcp/package.json b/packages/solana-memo-media-mcp/package.json
index d227fae35..f46639c75 100644
--- a/packages/solana-memo-media-mcp/package.json
+++ b/packages/solana-memo-media-mcp/package.json
@@ -14,7 +14,7 @@
"files": ["src", "server.json", "smithery.yaml", "README.md", "LICENSE"],
"bin": { "solana-memo-media-mcp": "src/index.js" },
"main": "./src/index.js",
- "exports": { ".": "./src/index.js" },
+ "exports": { ".": "./src/index.js", "./src/lib/media.js": "./src/lib/media.js", "./src/lib/memos.js": "./src/lib/memos.js" },
"engines": { "node": ">=20" },
"scripts": { "start": "node src/index.js", "test": "node --test \"test/**/*.test.mjs\"", "inspect": "npx -y @modelcontextprotocol/inspector node src/index.js" },
"dependencies": { "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^3.23.8" }
diff --git a/packages/solana-memo-media-mcp/src/lib/media.js b/packages/solana-memo-media-mcp/src/lib/media.js
index 888a0a858..a396a5c4e 100644
--- a/packages/solana-memo-media-mcp/src/lib/media.js
+++ b/packages/solana-memo-media-mcp/src/lib/media.js
@@ -26,6 +26,19 @@ function gifDimensions(bytes) {
return { width: bytes.readUInt16LE(6), height: bytes.readUInt16LE(8) };
}
+function webpDimensions(bytes) {
+ const chunk = bytes.subarray(12, 16).toString('ascii');
+ if (chunk === 'VP8X' && bytes.length >= 30) return { width: bytes.readUIntLE(24, 3) + 1, height: bytes.readUIntLE(27, 3) + 1 };
+ if (chunk === 'VP8L' && bytes.length >= 25 && bytes[20] === 0x2f) {
+ const bits = bytes.readUInt32LE(21);
+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
+ }
+ if (chunk === 'VP8 ' && bytes.length >= 30 && bytes[23] === 0x9d && bytes[24] === 0x01 && bytes[25] === 0x2a) {
+ return { width: bytes.readUInt16LE(26) & 0x3fff, height: bytes.readUInt16LE(28) & 0x3fff };
+ }
+ return null;
+}
+
function jpegDimensions(bytes) {
let offset = 2;
while (offset + 9 < bytes.length) {
@@ -58,7 +71,7 @@ function inspectMagic(type, bytes) {
}
if (type === 'image/webp') {
if (bytes.subarray(0, 4).toString('ascii') !== 'RIFF' || bytes.subarray(8, 12).toString('ascii') !== 'WEBP') throw bad('Bytes do not have a WebP signature.', 'media_signature_mismatch');
- return null;
+ return webpDimensions(bytes);
}
return null;
}
diff --git a/packages/solana-memo-media-mcp/src/lib/memos.js b/packages/solana-memo-media-mcp/src/lib/memos.js
index c2c5cec2c..9c2f08f92 100644
--- a/packages/solana-memo-media-mcp/src/lib/memos.js
+++ b/packages/solana-memo-media-mcp/src/lib/memos.js
@@ -1,24 +1,28 @@
-const MEMO_PROGRAMS = new Set(['MemoSq4gqABAXKb96qnH8TysNcV4F6n7jKx9jABZx1s', 'Memo1UhkJRfHyvLMcVLMbLJYfW2tfU8G8H4PqvV6v8']);
+// SPL Memo v1, SPL Memo v2, and the newer memo program that version-1 transactions carry.
+export const MEMO_PROGRAM_IDS = new Set([
+ 'Memo1UhkJRfHyvLMcVLMbLJYfW2tfU8G8H4PqvV6v8',
+ 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr',
+ 'Memo4c2pN8afCj432Lb7RMVKi9PbQnnW7ewFFaV3oAH',
+]);
function isMemo(instruction) {
- return MEMO_PROGRAMS.has(instruction?.programId) || /memo/i.test(String(instruction?.program || '')) || /memo/i.test(String(instruction?.programId || ''));
-}
-
-function textFrom(instruction) {
- if (typeof instruction?.parsed === 'string') return instruction.parsed;
- if (typeof instruction?.data === 'string' && instruction.data.startsWith('data:')) return instruction.data;
- return null;
+ return MEMO_PROGRAM_IDS.has(instruction?.programId) || instruction?.program === 'spl-memo';
}
+// jsonParsed RPC responses carry a memo's UTF-8 text as a string in `parsed`.
export function memoPayloads(transaction) {
const groups = [transaction?.transaction?.message?.instructions || [], ...(transaction?.meta?.innerInstructions || []).map((item) => item.instructions || [])];
const output = [];
for (const instructions of groups) {
for (const instruction of instructions) {
- if (!isMemo(instruction)) continue;
- const payload = textFrom(instruction);
- if (payload) output.push(payload);
+ if (isMemo(instruction) && typeof instruction.parsed === 'string') output.push(instruction.parsed);
}
}
return [...new Set(output)];
}
+
+// getSignaturesForAddress reports memos as "[length] text; [length] text". A signature whose
+// memo summary holds no data URI cannot carry memo media, so it needs no getTransaction call.
+export function signatureMayCarryMedia(memoSummary) {
+ return typeof memoSummary === 'string' && memoSummary.includes('data:');
+}
diff --git a/packages/solana-memo-media-mcp/src/tools/extract-transaction.js b/packages/solana-memo-media-mcp/src/tools/extract-transaction.js
index 724506c19..d69462315 100644
--- a/packages/solana-memo-media-mcp/src/tools/extract-transaction.js
+++ b/packages/solana-memo-media-mcp/src/tools/extract-transaction.js
@@ -1,30 +1,11 @@
import { z } from 'zod';
-import { decodeDataUri, mediaMetadata } from '../lib/media.js';
-import { memoPayloads } from '../lib/memos.js';
-import { assertBase58, getParsedTransaction } from '../lib/rpc.js';
+import { extractFromSignature } from './shared.js';
export const def = {
name: 'extract_solana_memo_media',
title: 'Extract media from a Solana transaction memo',
- annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },
- description: 'Fetch a finalized Solana transaction, inspect top-level and inner SPL Memo instructions, and render every supported embedded image data URI inline. The response always identifies the source signature and reports rejected media without returning unsafe bytes. This is chain data, not a claim of authorship or safety.',
- inputSchema: { signature: z.string().trim().min(32).max(128).describe('Finalized Solana transaction signature in base58.') },
- async handler(args) {
- const signature = assertBase58(args.signature, 'signature');
- const transaction = await getParsedTransaction(signature);
- if (!transaction) {
- const error = new Error('Transaction was not found or is not available from the configured RPC endpoints.');
- error.code = 'transaction_not_found';
- throw error;
- }
- const payloads = memoPayloads(transaction);
- const assets = [];
- const rejected = [];
- for (const payload of payloads) {
- if (!payload.startsWith('data:')) continue;
- try { const media = decodeDataUri(payload); assets.push({ media, metadata: mediaMetadata(media, { source: 'spl_memo' }) }); }
- catch (error) { rejected.push({ code: error.code || 'invalid_data_uri', message: error.message }); }
- }
- return { signature, slot: transaction.slot ?? null, block_time: transaction.blockTime ?? null, memo_count: payloads.length, assets, rejected };
- },
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
+ description: 'Fetch a confirmed Solana transaction (legacy, v0, or v1), inspect top-level and inner SPL Memo instructions, and render every supported embedded image data URI inline. The response identifies the source signature, fee payer, slot, and transaction version, and reports rejected media without returning unsafe bytes. This is chain data, not a claim of authorship or safety.',
+ inputSchema: { signature: z.string().trim().min(32).max(128).describe('Solana transaction signature in base58.') },
+ handler: (args) => extractFromSignature(args.signature),
};
diff --git a/packages/solana-memo-media-mcp/src/tools/find-address-media.js b/packages/solana-memo-media-mcp/src/tools/find-address-media.js
index ebe6bc9fa..a31ba8b51 100644
--- a/packages/solana-memo-media-mcp/src/tools/find-address-media.js
+++ b/packages/solana-memo-media-mcp/src/tools/find-address-media.js
@@ -1,26 +1,45 @@
import { z } from 'zod';
import { extractFromSignature } from './shared.js';
+import { signatureMayCarryMedia } from '../lib/memos.js';
import { assertBase58, rpc } from '../lib/rpc.js';
+const FETCH_CONCURRENCY = 4;
+
export const def = {
name: 'find_solana_memo_media',
title: 'Find recent memo media for a Solana address',
annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },
- description: 'Search a public Solana address’s recent finalized transactions and return only validated image data URIs carried by SPL Memo instructions. It is intentionally bounded to limit RPC load. Use the returned signatures to verify provenance in an explorer.',
- inputSchema: { address: z.string().trim().min(32).max(64).describe('Solana wallet, token account, or program address in base58.'), limit: z.number().int().min(1).max(20).default(10).describe('Recent finalized signatures to inspect, from 1 to 20 (default 10).') },
+ description: 'Scan a Solana address\'s recent confirmed transactions and return only validated image data URIs carried by SPL Memo instructions. Signatures whose memo summary holds no data URI are skipped without fetching the transaction, so a scan costs one RPC call plus one per candidate. Pass a memo program id as the address to watch every memo written to it. Use the returned signatures to verify provenance in an explorer.',
+ inputSchema: {
+ address: z.string().trim().min(32).max(64).describe('Solana wallet, token account, or program address in base58.'),
+ limit: z.number().int().min(1).max(1000).default(100).describe('Recent signatures to scan, from 1 to 1000 (default 100).'),
+ before: z.string().trim().min(32).max(128).optional().describe('Continue the scan from signatures older than this one (the previous response\'s next_before).'),
+ },
async handler(args) {
const address = assertBase58(args.address, 'address');
- const limit = args.limit ?? 10;
- const signatures = await rpc('getSignaturesForAddress', [address, { limit, commitment: 'finalized' }]);
+ const limit = args.limit ?? 100;
+ const options = { limit, commitment: 'confirmed' };
+ if (args.before) options.before = assertBase58(args.before, 'before');
+ const signatures = (await rpc('getSignaturesForAddress', [address, options])) || [];
+ const candidates = signatures.filter((item) => item?.signature && !item.err && signatureMayCarryMedia(item.memo));
const matches = [];
const failures = [];
- for (const item of signatures || []) {
- if (!item?.signature || item.err) continue;
- try {
- const result = await extractFromSignature(item.signature);
- if (result.assets.length) matches.push(result);
- } catch (error) { failures.push({ signature: item.signature, code: error.code || 'rpc_error', message: error.message }); }
+ for (let index = 0; index < candidates.length; index += FETCH_CONCURRENCY) {
+ const batch = candidates.slice(index, index + FETCH_CONCURRENCY);
+ const results = await Promise.allSettled(batch.map((item) => extractFromSignature(item.signature)));
+ results.forEach((result, offset) => {
+ if (result.status === 'rejected') failures.push({ signature: batch[offset].signature, code: result.reason?.code || 'rpc_error', message: result.reason?.message || String(result.reason) });
+ else if (result.value.assets.length || result.value.rejected.length) matches.push(result.value);
+ });
}
- return { address, inspected: (signatures || []).length, match_count: matches.length, matches, failures };
+ return {
+ address,
+ scanned: signatures.length,
+ candidates: candidates.length,
+ match_count: matches.length,
+ matches,
+ failures,
+ next_before: signatures.length === limit ? signatures.at(-1).signature : null,
+ };
},
};
diff --git a/packages/solana-memo-media-mcp/src/tools/shared.js b/packages/solana-memo-media-mcp/src/tools/shared.js
index 8e25a294c..bc4892145 100644
--- a/packages/solana-memo-media-mcp/src/tools/shared.js
+++ b/packages/solana-memo-media-mcp/src/tools/shared.js
@@ -5,13 +5,31 @@ import { assertBase58, getParsedTransaction } from '../lib/rpc.js';
export async function extractFromSignature(value) {
const signature = assertBase58(value, 'signature');
const transaction = await getParsedTransaction(signature);
- if (!transaction) { const error = new Error('Transaction was not found.'); error.code = 'transaction_not_found'; throw error; }
+ if (!transaction) {
+ const error = new Error('Transaction was not found or is not available from the configured RPC endpoints.');
+ error.code = 'transaction_not_found';
+ throw error;
+ }
+ const payloads = memoPayloads(transaction);
const assets = [];
const rejected = [];
- for (const payload of memoPayloads(transaction)) {
+ for (const payload of payloads) {
if (!payload.startsWith('data:')) continue;
- try { const media = decodeDataUri(payload); assets.push({ media, metadata: mediaMetadata(media, { source: 'spl_memo' }) }); }
- catch (error) { rejected.push({ code: error.code || 'invalid_data_uri', message: error.message }); }
+ try {
+ const media = decodeDataUri(payload);
+ assets.push({ media, metadata: mediaMetadata(media, { source: 'spl_memo' }) });
+ } catch (error) {
+ rejected.push({ code: error.code || 'invalid_data_uri', message: error.message });
+ }
}
- return { signature, slot: transaction.slot ?? null, block_time: transaction.blockTime ?? null, assets, rejected };
+ return {
+ signature,
+ slot: transaction.slot ?? null,
+ block_time: transaction.blockTime ?? null,
+ transaction_version: transaction.version ?? null,
+ signer: transaction.transaction?.message?.accountKeys?.find((key) => key.signer)?.pubkey ?? null,
+ memo_count: payloads.length,
+ assets,
+ rejected,
+ };
}
diff --git a/packages/solana-memo-media-mcp/src/tools/status.js b/packages/solana-memo-media-mcp/src/tools/status.js
index 06cc9b117..31be0c5dc 100644
--- a/packages/solana-memo-media-mcp/src/tools/status.js
+++ b/packages/solana-memo-media-mcp/src/tools/status.js
@@ -1,10 +1,20 @@
+import { ALLOWED_MEDIA_TYPES, MAX_MEDIA_BYTES } from '../lib/media.js';
+import { MEMO_PROGRAM_IDS } from '../lib/memos.js';
import { getRpcUrls } from '../lib/rpc.js';
export const def = {
name: 'get_solana_memo_media_status',
title: 'Solana memo media capability',
annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
- description: 'Report the local decoding policy and ordered Solana RPC failover hosts. No network call is made and no data is stored.',
+ description: 'Report the local decoding policy, recognized memo programs, and ordered Solana RPC failover hosts. No network call is made and no data is stored.',
inputSchema: {},
- async handler() { return { ok: true, accepted_mime_types: ['image/png', 'image/jpeg', 'image/webp', 'image/gif'], max_decoded_bytes: 262144, rpc_hosts: getRpcUrls().map((url) => new URL(url).host), local_decoding: true, writes: false }; },
+ handler: async () => ({
+ accepted_mime_types: [...ALLOWED_MEDIA_TYPES],
+ max_decoded_bytes: MAX_MEDIA_BYTES,
+ memo_program_ids: [...MEMO_PROGRAM_IDS],
+ rpc_hosts: getRpcUrls().map((url) => new URL(url).host),
+ max_supported_transaction_version: 1,
+ local_decoding: true,
+ writes: false,
+ }),
};
diff --git a/packages/solana-memo-media-mcp/test/media.test.mjs b/packages/solana-memo-media-mcp/test/media.test.mjs
index f5ee95b86..3e4303e61 100644
--- a/packages/solana-memo-media-mcp/test/media.test.mjs
+++ b/packages/solana-memo-media-mcp/test/media.test.mjs
@@ -29,3 +29,29 @@ test('the complete read-only surface is registered without a signer', () => {
const server = buildServer();
for (const tool of TOOLS) assert.ok(server._registeredTools[tool.name]);
});
+
+function dataUri(mimeType, bytes) {
+ return `data:${mimeType};base64,${Buffer.from(bytes).toString('base64')}`;
+}
+
+test('reports dimensions for GIF, JPEG, and every WebP bitstream', () => {
+ assert.deepEqual(decodeDataUri('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==').dimensions, { width: 1, height: 1 });
+
+ const jpeg = [0xff, 0xd8, 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x30, 0x00, 0x2a, 0x03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xd9];
+ assert.deepEqual(decodeDataUri(dataUri('image/jpeg', jpeg)).dimensions, { width: 42, height: 48 });
+
+ const riff = (chunk, body) => Buffer.concat([Buffer.from('RIFF'), Buffer.alloc(4), Buffer.from('WEBP'), Buffer.from(chunk), Buffer.alloc(4), Buffer.from(body)]);
+ const vp8x = riff('VP8X', [0, 0, 0, 0, 41, 0, 0, 47, 0, 0]);
+ assert.deepEqual(decodeDataUri(dataUri('image/webp', vp8x)).dimensions, { width: 42, height: 48 });
+ const bits = Buffer.alloc(4); bits.writeUInt32LE(41 | (47 << 14));
+ const vp8l = riff('VP8L', [0x2f, ...bits]);
+ assert.deepEqual(decodeDataUri(dataUri('image/webp', vp8l)).dimensions, { width: 42, height: 48 });
+ const vp8 = riff('VP8 ', [0, 0, 0, 0x9d, 0x01, 0x2a, 42, 0, 48, 0]);
+ assert.deepEqual(decodeDataUri(dataUri('image/webp', vp8)).dimensions, { width: 42, height: 48 });
+});
+
+test('refuses oversized and non-canonical payloads before decoding them', () => {
+ assert.throws(() => decodeDataUri(PNG, { maxBytes: 10 }), (error) => error.code === 'media_too_large');
+ assert.throws(() => decodeDataUri('data:image/png;base64,iVBORw0KGgo'), (error) => error.code === 'invalid_data_uri');
+ assert.throws(() => decodeDataUri('not a data uri'), (error) => error.code === 'invalid_data_uri');
+});
diff --git a/packages/solana-memo-media-mcp/test/memos.test.mjs b/packages/solana-memo-media-mcp/test/memos.test.mjs
new file mode 100644
index 000000000..d637100de
--- /dev/null
+++ b/packages/solana-memo-media-mcp/test/memos.test.mjs
@@ -0,0 +1,40 @@
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { MEMO_PROGRAM_IDS, memoPayloads, signatureMayCarryMedia } from '../src/lib/memos.js';
+
+const PNG = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/lwV8YQAAAABJRU5ErkJggg==';
+
+// Shape of a jsonParsed getTransaction result for a version-1 transaction on mainnet.
+function transaction(instructions, inner = []) {
+ return { version: 1, slot: 1, blockTime: 1, transaction: { message: { accountKeys: [], instructions } }, meta: { innerInstructions: inner } };
+}
+
+test('reads memos from every SPL Memo program, top level and inner', () => {
+ const [v1, v2, next] = [...MEMO_PROGRAM_IDS];
+ const tx = transaction(
+ [{ program: 'spl-memo', programId: next, parsed: PNG, stackHeight: 1 }, { programId: v1, parsed: 'hello' }],
+ [{ index: 0, instructions: [{ programId: v2, parsed: 'inner note' }] }],
+ );
+ assert.deepEqual(memoPayloads(tx), [PNG, 'hello', 'inner note']);
+});
+
+test('ignores programs that merely look like a memo program', () => {
+ const tx = transaction([
+ { programId: 'MemoSq4gqABAXKb96qnH8TysNcV4F6n7jKx9jABZx1s', parsed: PNG },
+ { program: 'system', programId: '11111111111111111111111111111111', parsed: { type: 'transfer' } },
+ { programId: 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr', data: '3Bxs4h24hBtQy9rw' },
+ ]);
+ assert.deepEqual(memoPayloads(tx), []);
+});
+
+test('deduplicates a payload repeated across instructions', () => {
+ const id = [...MEMO_PROGRAM_IDS][1];
+ assert.deepEqual(memoPayloads(transaction([{ programId: id, parsed: PNG }, { programId: id, parsed: PNG }])), [PNG]);
+});
+
+test('address scans only fetch signatures whose memo summary holds a data URI', () => {
+ assert.equal(signatureMayCarryMedia('[3826] data:image/png;base64,iVBOR'), true);
+ assert.equal(signatureMayCarryMedia('[11] JPP #379584'), false);
+ assert.equal(signatureMayCarryMedia(null), false);
+ assert.equal(signatureMayCarryMedia(undefined), false);
+});
diff --git a/public/onchain/index.html b/public/onchain/index.html
index 5510c1aa1..6b67f0dce 100644
--- a/public/onchain/index.html
+++ b/public/onchain/index.html
@@ -60,7 +60,8 @@
</main>
<script>
const RPC = 'https://api.mainnet-beta.solana.com';
- const memoProgram = 'Memo4c2pN8afCj432Lb7RMVKi9PbQnnW7ewFFaV3oAH';
+ // SPL Memo v1, v2, and the newer program that version-1 transactions use.
+ const memoPrograms = new Set(['Memo1UhkJRfHyvLMcVLMbLJYfW2tfU8G8H4PqvV6v8', 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr', 'Memo4c2pN8afCj432Lb7RMVKi9PbQnnW7ewFFaV3oAH']);
const $ = (id) => document.getElementById(id);
const signatureFrom = (value) => {
const trimmed = value.trim();
@@ -102,7 +103,9 @@
try {
const response = await fetch(RPC, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getTransaction', params: [signature, { encoding: 'jsonParsed', maxSupportedTransactionVersion: 1 }] }) });
const payload = await response.json(); if (payload.error) throw new Error(payload.error.message); if (!payload.result) throw new Error('Transaction was not found on the Solana mainnet.');
- const instruction = payload.result.transaction.message.instructions.find((item) => item.programId === memoProgram && typeof item.parsed === 'string');
+ const instructions = [...payload.result.transaction.message.instructions, ...(payload.result.meta?.innerInstructions || []).flatMap((group) => group.instructions || [])];
+ const memos = instructions.filter((item) => memoPrograms.has(item.programId) && typeof item.parsed === 'string');
+ const instruction = memos.find((item) => item.parsed.startsWith('data:')) || memos[0];
if (!instruction) throw new Error('No readable Memo was found in this transaction.');
render(signature, payload.result, instruction.parsed);
} catch (error) { setStatus(error.message || 'Could not read that transaction.', true); }