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.

feat(onchain-agent-wallets): give an agent a spending allowance instead of a key

nirholasfaaa782f717c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 06d6a23ce..7d0027f73 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Deploy On-chain** (`/deploy-onchain`): Mint your agent into the Metaplex Agent Registry on Solana, in the exact shape the Genesis 333 shipped: a Metaplex Core asset with its own wallet, EIP-8004 identity, verified creator, royalties, and immutable metadata. Phantom, Solflare, or any Solana wallet signs; keys never leave the browser, and devnet rehearsal is free.
- **A page that fails to load now tells you which thing went wrong**: When an avatar or agent page could not load, it always said the same thing: not found, followed by whatever internal message the browser happened to throw. A stale link and a temporary server hiccup looked identical, and the explanation was often developer jargon rather than English. The two cases are now told apart. A link to something that no longer exists says exactly that and points you at the marketplace or the agent directory. A genuine failure on our side says so, offers a Try again button, and keeps the technical detail as a small footnote instead of presenting it as the reason. `[improvement, fix]`
- **Agent pages show what an agent can actually do, and what it charges**: The studio page every agent link opens now carries the agent's real substance. Its Capabilities tab lists the skills it genuinely exposes with the real per-call price of each, and a summary line telling you the cheapest paid call up front (or that everything is free). Skill names read as words instead of raw slugs, with the exact slug shown underneath for anyone wiring an integration. Under the title there is now a row of real counters: skills, conversations, wallet, whether the identity is on-chain, and how long the agent has been around. Below the fold, an agent recommends similar agents rather than unrelated avatars, each rendered as a live 3D card. The page also loads better: a skeleton in the real layout instead of a line of text, cards that show a picture while their 3D model downloads, and full keyboard support on the section tabs with a shareable link per tab. (`/agents`) `[improvement, feature]`
+- **Agents can now hold a spending allowance instead of your private key**: Handing an AI agent a wallet has always meant handing it a private key, which means handing it everything in that wallet. The new onchain-agent-wallets MCP server replaces that with an allowance. Your money stays in an account you own, and the agent gets permission to spend a slice of it that the Solana token program enforces on-chain: it cannot spend past the ceiling however it is prompted, every spend decrements what is left, and you can cancel the whole thing in one instruction or take the balance back without the agent's cooperation. On top of that you set the rules it runs under: a maximum per transaction, a maximum per day, which addresses it may pay, which APIs it may buy from, an expiry, and a pause switch that stops it instantly for free. It can pay x402 APIs out of the allowance, and the price is always read before any money moves. Every decision, including every refusal and the reason for it, is written to an audit log you can read. You never have to put a secret key on the machine: owner actions come back as an unsigned transaction for Phantom, Solflare, or a Ledger to sign. `[feature, sdk, security]`
- **Every three.ws package on npm is current again**: Our npm packages had drifted a long way behind the code: 73 of them, including the main SDK, the React components, the avatar and walk SDKs and most of the MCP servers, were sitting on npm at an older version than what we had actually built. Anyone installing from npm got stale code. All 73 are now published at their current version, and four packages that had never been released at all (the agent runtime, the sign language pack, the spatial MCP server and the VS Code extension) are on npm for the first time. The cause was our release script working from a hand written list, so any package added after that list was written was silently never published; it now discovers packages itself, so a new one cannot be forgotten again. `[sdk, fix]`
- **Phone fixes: helper widgets no longer sit on top of the controls**: On a phone the floating language control and the Getting started pill landed directly on the page's own bottom controls: the language picker rendered inside the "Ask the agent" box and the pill covered the save row. Helper widgets now measure a page's bottom bar and float above it, and the language control shows a compact code (EN) instead of a full-width bar. Gallery cards show all three actions in full, so Animate is no longer clipped mid-word. In the AR Studio, the Add models sheet keeps its tabs at full height on short screens, and each model is labelled with a readable name instead of the whole generation prompt. On the viewer page a long email no longer pushes the account button off the edge of the screen. (`/gallery`) `[fix, improvement]`
- **Put any agent on-chain from your AI assistant: the Metaplex Agent Registry MCP server**: A new npm package, @three-ws/metaplex-agent-mcp, lets any AI assistant deploy an agent on-chain on Solana the exact way the three.ws Genesis 333 shipped: it mints a Metaplex Core asset and registers its EIP-8004 agent identity, so the agent appears on metaplex.com/agents with its own built-in wallet. Agents can sign with their own key, and people can sign with Phantom, Solflare, or any Solana wallet, with a preview-first confirm step before anything is spent. Every royalty, creator, plugin, and metadata field is customizable, and devnet rehearsal is free. (`/deployments`) `[sdk, feature]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 6154d354e..86fd65182 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -153,6 +153,7 @@ bottom.
| Production server (Google Cloud Run) | [server/](server) + [Dockerfile](Dockerfile) | Live | Single Express container serving the static frontend, the vercel.json route table, and all `api/**` handlers with Vercel-parity routing; deploy via `npm run deploy:gcp` ([server/cloudbuild.yaml](server/cloudbuild.yaml)), crons via [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs) · see [server/README.md](server/README.md) |
| Multiplayer 3D world (world.three.ws) | [deploy/world/](deploy/world) — [Dockerfile](deploy/world/Dockerfile), [cloudrun.yaml](deploy/world/cloudrun.yaml), [apply-hardening.sh](deploy/world/apply-hardening.sh), patches in [deploy/world/patches/](deploy/world/patches); health monitor [api/cron/world-health.js](api/cron/world-health.js) | Live · `hyperfy-world` on Cloud Run | [Hyperfy](https://github.com/hyperfy-xyz/hyperfy) pinned to an exact upstream commit and rebuilt with three local patches (server-side upload cap, `/status` blueprint-asset enumeration, fail-closed-without-`ADMIN_CODE`). World state (SQLite + uploaded assets) lives in the GCS bucket `world-three-ws-data` mounted at `/app/world`, so the container is stateless. **The world is gated:** without `ADMIN_CODE` Hyperfy's `effectiveRank` falls back to `Ranks.ADMIN` and every anonymous visitor gets server-side build rights — the fail-open default that emptied the world on 2026-06-12. Deploy + verify with `bash deploy/world/apply-hardening.sh`; builders unlock in-world with `/admin <code>`. See [deploy/world/README.md](deploy/world/README.md) |
| Metaplex Agent Registry deploy (Genesis-333 mint for everyone) | [pages/deploy-onchain.html](pages/deploy-onchain.html) + [src/deploy-onchain.js](src/deploy-onchain.js) `→ /deploy-onchain`, shared builders [packages/metaplex-agent-mcp/src/lib/](packages/metaplex-agent-mcp/src/lib) (published as `@three-ws/metaplex-agent-mcp`, also in the official MCP registry as `io.github.nirholas/metaplex-agent`) | Live | Mint any agent into the Metaplex Agent Registry in the exact Genesis 333 shape: data: URI metadata, verified creator, 5% royalties, immutable metadata, EIP-8004 identity with `model.uri` + `x402Support`. The page signs with the user's own wallet (Phantom/Solflare/Backpack, `signAllTransactions`) through the same-origin RPC proxy; the MCP server gives agents the identical mint with their own key (preview-first, `confirm:true` gated) plus a prepare/send lane for external wallets. Both consume one isomorphic builder library, and [tests](packages/metaplex-agent-mcp/test/genesis-shape.test.mjs) pin the output byte-for-byte to the live Genesis #332 URIs. Devnet is a free rehearsal lane end-to-end. |
+| Onchain agent wallets (spending allowances, not private keys) | [packages/onchain-agent-wallets/](packages/onchain-agent-wallets) (published as `@three-ws/onchain-agent-wallets`, MCP registry `io.github.nirholas/onchain-agent-wallets`) | Live | Give an agent a Solana wallet without giving it the money. Funds sit in a vault token account the OWNER owns, derived deterministically from the owner address plus the agent id (`createWithSeed(owner, "oaw1:<agent>")`); the agent holds only a capped SPL Token delegation over it, so the token program itself refuses any spend past the ceiling and decrements it on every transfer. Guardrails on top (per-tx, rolling daily, recipient and host allowlists, expiry, pause, confirm-above threshold) are enforced before signing, and every decision including refusals lands in a local ledger. `pay_x402` probes the price unpaid, checks it against the guardrails, tops the agent up for exactly that amount, pays, and leaves it empty. Owner actions need no key on the machine: they come back as unsigned transactions for Phantom/Solflare/Ledger. [Delegation tests](packages/onchain-agent-wallets/test/token-delegation.test.mjs) run the real SPL Token program in process and assert that 61 against a remaining allowance of 60 fails on-chain. |
| On-chain contracts (Solidity + Solana) | [contracts/](contracts) · [contracts/README.md](contracts/README.md) | Mixed: `ThreeWSPayments` + `ThreeWSFactory` live on BSC/Base/Arbitrum, the rest in-repo | Every contract and program three.ws owns, in one Foundry project plus two Anchor programs. ERC-8004 identity/reputation/validation registries (reference implementations of the canonical deployments the platform actually reads), the live x402 USDC receiver and its CREATE2 vanity factory, `AgentPayments`, `GreenfieldVault`, `WorldMoves`, and the Solana `skill_license` / `agent_invocation` programs. `forge test` covers the Solidity set with 242 tests across 8 suites; the Solana side is covered by the LiteSVM row below. Deploy status per contract and the address provenance per chain: [contracts/DEPLOYMENTS.md](contracts/DEPLOYMENTS.md) |
| Contract audit pack | [contracts/AUDIT-README.md](contracts/AUDIT-README.md), invariants [specs/ECONOMY_CONTRACT_INVARIANTS.md](specs/ECONOMY_CONTRACT_INVARIANTS.md), threat model [specs/ECONOMY_CONTRACT_THREAT_MODEL.md](specs/ECONOMY_CONTRACT_THREAT_MODEL.md), static analysis [contracts/audit/](contracts/audit) | In-repo | Everything a review firm needs on day one for the reputation, royalty and delegation contracts: scope + deploy status per contract, stable invariant ids with a positive and a negative test each, an assets/actors/failure-modes threat model, and committed Slither + Clippy output with every finding fixed or dispositioned in writing |
| Recurring payments (subscriptions + DCA) | Page [public/recurring.html](public/recurring.html) `→ /recurring`, module [src/recurring.js](src/recurring.js), lifecycle rules [api/_lib/recurring.js](api/_lib/recurring.js), APIs [api/agent-subscriptions.js](api/agent-subscriptions.js) `→ /api/agent-subscriptions` and [api/dca-strategies.js](api/dca-strategies.js) `→ /api/dca-strategies`, hourly crons `run-subscriptions` + `run-dca` in [api/cron/[name].js](api/cron/%5Bname%5D.js), schema [api/_lib/migrations/20260813191500_recurring_payment_lifecycle.sql](api/_lib/migrations/20260813191500_recurring_payment_lifecycle.sql) | Live | One signed ERC-7710 permission, then money moves on a schedule: a subscription transfers a fixed USDC amount to an agent's wallet each period, a DCA strategy swaps the same amount into a token through Uniswap V3. `/recurring` is the whole lifecycle in one place (create, pause, resume, cancel, per-charge history) plus an Incoming tab scoped by agent ownership rather than by payer, so a creator sees what is being paid in. Every attempt is written to `subscription_charges` / `dca_executions`, and one shared classifier decides what a failure means: a revoked or expired permission pauses the schedule with the reason attached, a network blip releases the period claim and retries for three ticks, a timeout is never retried (the only failure that could double-charge), a diverged DCA quote skips the period for free, and a platform-side relayer outage never counts against the owner at all. Settlement needs `AGENT_RELAYER_KEY` + `RPC_URL_<chainId>` on the deployment; DCA creation needs `DCA_ALLOWED_TOKEN_OUT` + `DCA_CHAIN_ID`. Docs: [docs/recurring-payments.md](docs/recurring-payments.md). Tests: [tests/recurring-charge-outcomes.test.js](tests/recurring-charge-outcomes.test.js), [tests/api/recurring-subscription-cron.test.js](tests/api/recurring-subscription-cron.test.js) |
@@ -292,6 +293,7 @@ packages/intel-mcp/ → @three-ws/intel-mcp (MCP server — sm
packages/marketplace-mcp/ → @three-ws/marketplace-mcp (MCP server — agent marketplace + skills catalog browse)
packages/x402-mcp/ → @three-ws/x402-mcp (MCP server — self-custodial x402 buyer: find/inspect/pay any service in USDC)
packages/metaplex-agent-mcp/ → @three-ws/metaplex-agent-mcp (MCP server: mint + register on-chain agents in the Metaplex Agent Registry, self-custody or Phantom/Solflare)
+packages/onchain-agent-wallets/ → @three-ws/onchain-agent-wallets (MCP server: agent wallets with an SPL-Token-enforced spending allowance, guardrails, x402, revocable custody)
packages/autopilot-mcp/ → @three-ws/autopilot-mcp (MCP server — agent execution control: scopes, SOL spend caps, propose/execute/undo)
packages/portfolio-mcp/ → @three-ws/portfolio-mcp (MCP server — portfolio, PnL, balances, trade feed, signed transfers)
packages/provenance-mcp/ → @three-ws/provenance-mcp (MCP server — append-only, signed, on-chain-verifiable agent action log)
diff --git a/data/changelog.json b/data/changelog.json
index 99d866502..5f9789622 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-08-19",
+ "title": "Agents can now hold a spending allowance instead of your private key",
+ "summary": "Handing an AI agent a wallet has always meant handing it a private key, which means handing it everything in that wallet. The new onchain-agent-wallets MCP server replaces that with an allowance. Your money stays in an account you own, and the agent gets permission to spend a slice of it that the Solana token program enforces on-chain: it cannot spend past the ceiling however it is prompted, every spend decrements what is left, and you can cancel the whole thing in one instruction or take the balance back without the agent's cooperation. On top of that you set the rules it runs under: a maximum per transaction, a maximum per day, which addresses it may pay, which APIs it may buy from, an expiry, and a pause switch that stops it instantly for free. It can pay x402 APIs out of the allowance, and the price is always read before any money moves. Every decision, including every refusal and the reason for it, is written to an audit log you can read. You never have to put a secret key on the machine: owner actions come back as an unsigned transaction for Phantom, Solflare, or a Ledger to sign.",
+ "tags": [
+ "feature",
+ "sdk",
+ "security"
+ ]
+ },
{
"date": "2026-08-19",
"title": "Every three.ws package on npm is current again",
diff --git a/packages/onchain-agent-wallets/LICENSE b/packages/onchain-agent-wallets/LICENSE
new file mode 100644
index 000000000..dff21b7f4
--- /dev/null
+++ b/packages/onchain-agent-wallets/LICENSE
@@ -0,0 +1,20 @@
+Copyright 2026 nirholas
+
+All rights reserved.
+
+This software is proprietary and may not be used, copied, modified, distributed,
+translated, or made available to any third party without the express written
+permission of the copyright owner.
+
+No rights are granted by implication, estoppel, or otherwise. Use of this
+software is subject to the terms of a separate license agreement with the
+copyright owner.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
+
+IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY CLAIM, DAMAGES, OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,
+ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/packages/onchain-agent-wallets/README.md b/packages/onchain-agent-wallets/README.md
new file mode 100644
index 000000000..c676bf14a
--- /dev/null
+++ b/packages/onchain-agent-wallets/README.md
@@ -0,0 +1,253 @@
+# onchain-agent-wallets
+
+**Give an AI agent a real Solana wallet without giving it your money.**
+
+An MCP server that hands any agent a spending allowance instead of a private key. The funds stay in an account you own. The agent gets a delegation the SPL Token program caps on-chain, plus guardrails you control, plus the ability to pay x402 APIs out of that allowance. You can revoke it in one instruction, and take the money back without asking the agent.
+
+Nothing here is mocked: real SPL Token delegations, real Solana, real x402 settlement.
+
+## The problem this solves
+
+Every "agent wallet" today works the same way: you generate a keypair, you hand it to the agent, and now the agent has everything in it. There is no ceiling, no allowlist, no expiry, and no way to take it back short of racing the agent to move the funds. People solve this by keeping almost nothing in the wallet, which means the agent cannot do anything useful.
+
+An allowance is the older, better answer. The money never moves to the agent. The agent gets permission to spend a slice of it, and the chain enforces the slice.
+
+## How it works
+
+```
+ YOU (Phantom, Solflare, Ledger)
+ │ owns the vault, holds the money, can revoke or withdraw at any time
+ ▼
+ ┌──────────────────────────────────────────┐
+ │ vault token account │ derived from your address:
+ │ owner = you │ createWithSeed(you, "oaw1:<agent>")
+ │ balance = 500 USDC │
+ │ delegate = the agent ← capped at 100 │ SPL Token enforces this number
+ └──────────────────────────────────────────┘
+ ▲
+ │ may spend up to the cap, and not one unit more
+ AGENT (its own keypair, holds only fee SOL)
+```
+
+Two independent layers protect you:
+
+1. **On-chain.** The SPL Token program checks every agent-signed transfer against `delegated_amount` and decrements it on each spend. Our code cannot raise it. A single `revoke` sets it to zero. This is a stock token program feature, not a new contract to trust.
+2. **Local.** Before this server signs anything it applies your rules: per-transaction cap, rolling 24-hour cap, recipient allowlist, x402 host allowlist, expiry, pause, and a confirm-above-this threshold that forces a human yes.
+
+The agent's own keypair holds nothing but a little SOL for fees. If it leaks, the blast radius is the remaining allowance, and `revoke_agent_wallet` closes it in one transaction.
+
+## Install
+
+```bash
+npm install -g @three-ws/onchain-agent-wallets
+# or run it ad hoc
+npx -y @three-ws/onchain-agent-wallets
+```
+
+## Setup
+
+Claude Code:
+
+```bash
+claude mcp add onchain-agent-wallets -- npx -y @three-ws/onchain-agent-wallets
+```
+
+Cursor, or any MCP client (`mcp.json`):
+
+```json
+{
+ "mcpServers": {
+ "onchain-agent-wallets": {
+ "command": "npx",
+ "args": ["-y", "@three-ws/onchain-agent-wallets"],
+ "env": {
+ "OAW_NETWORK": "mainnet"
+ }
+ }
+ }
+}
+```
+
+No key is required to start. Owner actions come back as an unsigned transaction for your wallet to sign, which `send_signed_transaction` then broadcasts. If you would rather this server sign for you, set `OWNER_SECRET_KEY`.
+
+| Variable | Default | What it does |
+| --- | --- | --- |
+| `OWNER_SECRET_KEY` | unset | Owner key, base58 or a JSON byte array. Optional: without it, you sign in Phantom. |
+| `OAW_NETWORK` | `mainnet` | `mainnet` or `devnet`. State is kept per network. |
+| `SOLANA_RPC_URL` | public endpoint | Your own RPC. The public one rate-limits hard. Must be https. |
+| `OAW_STATE_DIR` | `~/.onchain-agent-wallets` | Where agent keypairs, guardrails, and the spend ledger live (0600 in a 0700 dir). |
+| `REQUIRE_CONFIRM` | `true` | Every value-moving tool refuses to broadcast without `confirm:true`. |
+
+## Quickstart
+
+Give a research agent 100 USDC of spending power, capped at 5 per transaction and 20 per day, and only for one API:
+
+```
+create_agent_wallet
+ id: "researcher"
+ allowance: "100"
+ per_tx: "5"
+ daily: "20"
+ allow_hosts: ["api.example.com"]
+ confirm: true
+
+fund_agent_wallet id: "researcher" amount: "500" sol: "0.02" confirm: true
+```
+
+The agent now spends on its own:
+
+```
+pay_x402 id: "researcher" url: "https://api.example.com/premium" confirm: true
+agent_pay id: "researcher" to: "<address>" amount: "2.50" confirm: true
+```
+
+And you stay in control:
+
+```
+agent_wallet_status id: "researcher" # live balances, remaining allowance, warnings
+spend_log id: "researcher" # every spend AND every refusal, with reasons
+set_guardrails id: "researcher" paused: true # instant, free, no transaction
+revoke_agent_wallet id: "researcher" withdraw: true confirm: true # on-chain kill switch
+```
+
+A refusal tells you exactly which rule fired:
+
+```json
+{
+ "ok": false,
+ "error": "over_daily",
+ "message": "20.5 would exceed the 20 daily cap (18 already spent)",
+ "checks": [
+ { "check": "per_tx", "ok": true, "detail": "2.5 is within the 5 per-transaction cap" },
+ { "check": "daily", "ok": false, "detail": "20.5 would exceed the 20 daily cap (18 already spent)" }
+ ]
+}
+```
+
+## Tools
+
+**Custody (you sign)**
+
+| Tool | What it does |
+| --- | --- |
+| `create_agent_wallet` | Generate the agent's keypair, create the vault, delegate a capped allowance, set guardrails. One call. |
+| `fund_agent_wallet` | Move tokens into the vault, and SOL to the agent for its fees. |
+| `approve_agent_allowance` | Raise, lower, or refill the on-chain ceiling. Replaces the previous allowance. |
+| `withdraw_from_vault` | Take funds back. Works with or without a live delegation. |
+| `revoke_agent_wallet` | The kill switch. Optionally sweeps the balance home in the same transaction. |
+| `send_signed_transaction` | Broadcast a transaction your wallet signed. |
+
+**Guardrails**
+
+| Tool | What it does |
+| --- | --- |
+| `set_guardrails` | per_tx, daily, allow_recipients, allow_hosts, expires_at, confirm_over, paused. Instant, free, no transaction. |
+
+**Spending (the agent signs)**
+
+| Tool | What it does |
+| --- | --- |
+| `agent_pay` | Send tokens to a recipient, inside the limits. |
+| `pay_x402` | Call an x402 API, paying from the allowance. |
+
+**Visibility**
+
+| Tool | What it does |
+| --- | --- |
+| `agent_wallet_status` | Live on-chain state, guardrails, 24h and 7d totals, and warnings. |
+| `list_agent_wallets` | Every agent, with live balances. |
+| `spend_log` | The audit trail, refusals included. |
+
+**Deployment**
+
+| Tool | What it does |
+| --- | --- |
+| `deploy_agent_onchain` | Mint the agent a Metaplex Agent Registry identity with its payment address in the on-chain attributes. |
+| `export_agent_runtime` | The mcp.json and identity card needed to run this agent somewhere else. |
+
+## Guardrails
+
+| Rule | Effect | Enforced by |
+| --- | --- | --- |
+| allowance | Total the agent may ever spend before a new approval | SPL Token program, on-chain |
+| vault balance | The agent cannot spend what is not there | SPL Token program, on-chain |
+| `per_tx` | Maximum single spend | this server |
+| `daily` | Maximum per rolling 24 hours, computed from the local ledger | this server |
+| `allow_recipients` | Only these addresses may receive funds. Empty means unrestricted | this server |
+| `allow_hosts` | Only these hosts may be paid over x402. Subdomains inherit. Empty means unrestricted | this server |
+| `expires_at` | Every spend refused after this timestamp | this server |
+| `confirm_over` | Spends above this need an explicit `confirm:true` | this server |
+| `paused` | Everything refused, instantly and for free | this server |
+
+The distinction matters when it goes wrong. If this machine is compromised, the local rules can be bypassed, and the on-chain allowance still cannot. That is why the allowance should be the smallest number that lets the agent work, topped up as needed, rather than the whole balance.
+
+## x402
+
+`pay_x402` probes the endpoint unpaid first, so the price is known before anything moves and the guardrails see the real number. Then it tops the agent up for exactly that amount out of the vault, pays, and leaves the agent empty again.
+
+It refuses to pay:
+
+- on a chain other than Solana (`no_solana_option`)
+- on the wrong cluster, for instance a mainnet price from a devnet wallet (`wrong_cluster`)
+- in a token the allowance is not denominated in (`asset_mismatch`)
+- above `max_price`, a per-call ceiling independent of the standing guardrails (`over_max_price`)
+
+If the endpoint is not charging, the content comes back and nothing is spent.
+
+## What the agent cannot do
+
+- Spend more than the allowance, however it is prompted. The token program decides that, not the model.
+- Move the vault, close it, or change its owner. It is not the owner.
+- Stop you withdrawing, or stop a revoke.
+- Raise its own allowance. Only an owner-signed `approve` does that.
+- Touch anything else in your wallet. The vault is a separate account holding only what you put in it.
+
+Proven in [`test/token-delegation.test.mjs`](test/token-delegation.test.mjs), which runs the real SPL Token program in process and asserts that a spend of 61 against a remaining allowance of 60 fails on-chain, with 460 sitting in the vault.
+
+## Rehearse for free on devnet
+
+```bash
+OAW_NETWORK=devnet npx -y @three-ws/onchain-agent-wallets
+```
+
+State is kept per network, so a devnet rehearsal never touches your mainnet agents.
+
+## Use it as a library
+
+The custody model is plain `@solana/web3.js` and `@solana/spl-token`, usable without MCP:
+
+```js
+import { createVaultInstructions, readVault, spendableUnits } from '@three-ws/onchain-agent-wallets/lib/vault';
+
+const { vault, instructions } = await createVaultInstructions({
+ connection,
+ owner: ownerPubkey,
+ agentId: 'researcher',
+ mint: usdcMint,
+ delegate: agentPubkey,
+ allowance: 100_000_000n, // 100 USDC
+ decimals: 6,
+});
+// sign `instructions` with the owner, then:
+const state = await readVault({ connection, vault });
+console.log(spendableUnits(state)); // what the agent may spend right now
+```
+
+`@three-ws/onchain-agent-wallets/lib/policy` exports the guardrail engine on its own, if you want the same rules in a different runtime.
+
+## Tests
+
+```bash
+npm test
+```
+
+Runs the guardrail unit tests, the x402 selection tests, and the delegation integration test against the real SPL Token program.
+
+## Related
+
+- [`@three-ws/metaplex-agent-mcp`](https://github.com/nirholas/metaplex-agent-mcp) mints agent identities into the Metaplex Agent Registry. `deploy_agent_onchain` uses it as a library, and its `prepare_agent_mint` is the browser-wallet path for minting.
+- [three.ws](https://three.ws) is where these agents get faces, avatars, and a home.
+
+## License
+
+See [LICENSE](LICENSE).
diff --git a/packages/onchain-agent-wallets/package.json b/packages/onchain-agent-wallets/package.json
new file mode 100644
index 000000000..7c2fd7cf2
--- /dev/null
+++ b/packages/onchain-agent-wallets/package.json
@@ -0,0 +1,75 @@
+{
+ "name": "@three-ws/onchain-agent-wallets",
+ "version": "0.1.0",
+ "mcpName": "io.github.nirholas/onchain-agent-wallets",
+ "description": "Give an AI agent a real Solana wallet without giving it your money. The agent gets a spending allowance the SPL Token program enforces on-chain, plus guardrails (per-tx cap, daily cap, recipient and host allowlists, expiry, kill switch), x402 payments, and a one-call on-chain deploy. Custody never leaves your wallet: you can revoke or withdraw at any moment, and the agent can never spend past the delegated ceiling.",
+ "type": "module",
+ "author": "nirholas <[email protected]>",
+ "license": "SEE LICENSE IN LICENSE",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/onchain-agent-wallets.git"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/onchain-agent-wallets/issues"
+ },
+ "keywords": [
+ "mcp",
+ "model-context-protocol",
+ "solana",
+ "agent-wallet",
+ "onchain-agent",
+ "x402",
+ "usdc",
+ "spl-token",
+ "delegation",
+ "spending-limit",
+ "self-custody",
+ "guardrails",
+ "ai-agent",
+ "agent-payments",
+ "three.ws"
+ ],
+ "publishConfig": {
+ "access": "public"
+ },
+ "files": [
+ "src",
+ "server.json",
+ "README.md",
+ "LICENSE"
+ ],
+ "bin": {
+ "onchain-agent-wallets": "src/index.js"
+ },
+ "main": "./src/index.js",
+ "exports": {
+ ".": "./src/index.js",
+ "./lib": "./src/lib/index.js",
+ "./lib/vault": "./src/lib/vault.js",
+ "./lib/policy": "./src/lib/policy.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",
+ "@solana/spl-token": "^0.4.15",
+ "@solana/web3.js": "^1.98.4",
+ "@three-ws/metaplex-agent-mcp": "^0.1.2",
+ "@x402/core": "^2.14.0",
+ "@x402/fetch": "^2.14.0",
+ "@x402/svm": "^2.14.0",
+ "bs58": "^6.0.0",
+ "zod": "^3.23.8"
+ },
+ "devDependencies": {
+ "solana-bankrun": "^0.4.0"
+ }
+}
diff --git a/packages/onchain-agent-wallets/server.json b/packages/onchain-agent-wallets/server.json
new file mode 100644
index 000000000..e9da99b69
--- /dev/null
+++ b/packages/onchain-agent-wallets/server.json
@@ -0,0 +1,57 @@
+{
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
+ "name": "io.github.nirholas/onchain-agent-wallets",
+ "title": "Onchain Agent Wallets",
+ "description": "Give an AI agent a Solana wallet with an on-chain spending limit it cannot exceed. Guardrails, x402, revocable custody. By three.ws.",
+ "websiteUrl": "https://three.ws",
+ "icons": [{ "src": "https://three.ws/three-ws-mcp-icon.svg", "mimeType": "image/svg+xml", "sizes": ["any"] }],
+ "repository": {
+ "url": "https://github.com/nirholas/onchain-agent-wallets",
+ "source": "github"
+ },
+ "version": "0.1.0",
+ "packages": [
+ {
+ "registryType": "npm",
+ "identifier": "@three-ws/onchain-agent-wallets",
+ "version": "0.1.0",
+ "runtimeHint": "npx",
+ "transport": { "type": "stdio" },
+ "environmentVariables": [
+ {
+ "name": "OWNER_SECRET_KEY",
+ "description": "Owner secret key, base58 or a JSON byte array. Optional: without it every owner action is returned as an unsigned transaction for Phantom, Solflare, Backpack, or a Ledger to sign.",
+ "isRequired": false,
+ "isSecret": true,
+ "format": "string"
+ },
+ {
+ "name": "OAW_NETWORK",
+ "description": "Cluster: mainnet or devnet. Defaults to mainnet. State is kept per network, so a devnet rehearsal never touches mainnet agents.",
+ "isRequired": false,
+ "default": "mainnet",
+ "format": "string"
+ },
+ {
+ "name": "SOLANA_RPC_URL",
+ "description": "HTTPS Solana RPC endpoint. Defaults to the public endpoint for the configured network; bring your own (Helius / Quicknode / Triton) for production.",
+ "isRequired": false,
+ "format": "string"
+ },
+ {
+ "name": "OAW_STATE_DIR",
+ "description": "Where agent keypairs, guardrails, and the spend ledger are stored. Defaults to ~/.onchain-agent-wallets, written 0600 inside a 0700 directory.",
+ "isRequired": false,
+ "format": "string"
+ },
+ {
+ "name": "REQUIRE_CONFIRM",
+ "description": "Refuse to broadcast anything that moves value until the call is re-issued with confirm:true. Default true.",
+ "isRequired": false,
+ "default": "true",
+ "format": "boolean"
+ }
+ ]
+ }
+ ]
+}
diff --git a/packages/onchain-agent-wallets/smithery.yaml b/packages/onchain-agent-wallets/smithery.yaml
new file mode 100644
index 000000000..fb02591fa
--- /dev/null
+++ b/packages/onchain-agent-wallets/smithery.yaml
@@ -0,0 +1,49 @@
+# Smithery deployment config for @three-ws/onchain-agent-wallets
+# https://smithery.ai/docs/config#smitheryyaml
+#
+# Give an AI agent a Solana wallet with an on-chain spending limit. The owner
+# keeps custody; the agent holds a capped SPL Token delegation the token program
+# enforces. Read tools and the whole Phantom/Solflare owner lane work with no
+# key configured at all.
+startCommand:
+ type: stdio
+ configSchema:
+ type: object
+ properties:
+ OWNER_SECRET_KEY:
+ type: string
+ title: Owner secret key
+ description: Base58 secret key (or JSON byte array) for the wallet that funds and controls the agents. Optional. Without it, owner actions come back as unsigned transactions for your own wallet to sign.
+ SOLANA_RPC_URL:
+ type: string
+ title: Solana RPC URL
+ description: HTTPS Solana RPC endpoint. Defaults to the public endpoint for the configured network. Bring your own (Helius / Quicknode / Triton) for production.
+ OAW_NETWORK:
+ type: string
+ title: Default network
+ default: mainnet
+ enum: [mainnet, devnet]
+ description: Solana cluster. State is kept per network, so devnet rehearsals never touch mainnet agents.
+ OAW_STATE_DIR:
+ type: string
+ title: State directory
+ description: Where agent keypairs, guardrails, and the spend ledger live. Defaults to ~/.onchain-agent-wallets.
+ REQUIRE_CONFIRM:
+ type: boolean
+ title: Require explicit confirm
+ default: true
+ description: Refuse to broadcast anything that moves value until the call is re-issued with confirm=true.
+ required: []
+ commandFunction: |
+ (config) => ({
+ command: 'npx',
+ args: ['-y', '@three-ws/onchain-agent-wallets'],
+ env: Object.assign(
+ {},
+ config.OWNER_SECRET_KEY ? { OWNER_SECRET_KEY: config.OWNER_SECRET_KEY } : {},
+ config.SOLANA_RPC_URL ? { SOLANA_RPC_URL: config.SOLANA_RPC_URL } : {},
+ config.OAW_NETWORK ? { OAW_NETWORK: config.OAW_NETWORK } : {},
+ config.OAW_STATE_DIR ? { OAW_STATE_DIR: config.OAW_STATE_DIR } : {},
+ config.REQUIRE_CONFIRM != null ? { REQUIRE_CONFIRM: String(config.REQUIRE_CONFIRM) } : {}
+ )
+ })
diff --git a/packages/onchain-agent-wallets/src/config.js b/packages/onchain-agent-wallets/src/config.js
new file mode 100644
index 000000000..93e79175d
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/config.js
@@ -0,0 +1,91 @@
+// Centralized env for the onchain-agent-wallets MCP.
+//
+// Custody model: the OWNER's wallet holds the money. An agent is a separate
+// keypair that is granted a capped SPL Token delegation over a dedicated vault
+// account the owner owns. The token program enforces the ceiling; this server
+// enforces the finer guardrails (per-tx, daily, allowlists, expiry) before it
+// ever signs. No key is ever baked in, and the owner lane can run entirely
+// through Phantom / Solflare with no secret on this machine at all.
+
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+
+export function env(key, fallback) {
+ const v = typeof process !== 'undefined' && process.env ? process.env[key] : undefined;
+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;
+}
+
+// Default cluster for every tool. Any tool can override per-call with `network`.
+export const NETWORK = (() => {
+ const raw = env('OAW_NETWORK', env('SOLANA_NETWORK', 'mainnet')).toLowerCase();
+ if (raw === 'devnet') return 'devnet';
+ if (raw === 'mainnet' || raw === 'mainnet-beta') return 'mainnet';
+ throw Object.assign(new Error(`OAW_NETWORK must be "mainnet" or "devnet" (got "${raw}")`), {
+ code: 'bad_network_config',
+ });
+})();
+
+export const DEFAULT_RPC = {
+ mainnet: 'https://api.mainnet-beta.solana.com',
+ devnet: 'https://api.devnet.solana.com',
+};
+
+// Transactions are signed and broadcast over this URL, so plaintext http
+// outside localhost is a MITM risk on funds. Refuse it at load.
+function validateRpcUrl(raw) {
+ let u;
+ try {
+ u = new URL(raw);
+ } catch {
+ throw Object.assign(new Error(`SOLANA_RPC_URL is not a valid URL: "${raw}"`), { code: 'bad_rpc_url' });
+ }
+ if (u.protocol === 'https:') return raw;
+ const isLocal = ['localhost', '127.0.0.1', '0.0.0.0', '::1'].includes(u.hostname);
+ if (u.protocol === 'http:' && isLocal) return raw;
+ throw Object.assign(
+ new Error(
+ `SOLANA_RPC_URL must be https (got "${u.protocol}//${u.hostname}"). Only http://localhost is allowed for local dev.`,
+ ),
+ { code: 'insecure_rpc_url' },
+ );
+}
+
+export const SOLANA_RPC_URL = validateRpcUrl(env('SOLANA_RPC_URL', DEFAULT_RPC[NETWORK]));
+
+/** Resolve the RPC endpoint for a per-call network override. */
+export function rpcFor(network) {
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+ return net === NETWORK ? SOLANA_RPC_URL : DEFAULT_RPC[net];
+}
+
+// The owner's key. Optional: every owner action can instead be built unsigned
+// and handed to Phantom / Solflare / Ledger through prepare_owner_transaction.
+export const OWNER_SECRET = env('OWNER_SECRET_KEY', env('SOLANA_SECRET_KEY', ''));
+
+// Where agent keypairs, policies, and the spend ledger live. One JSON file,
+// written 0600. Override to relocate (a mounted volume, a per-project dir).
+export const STATE_DIR = env('OAW_STATE_DIR', join(homedir(), '.onchain-agent-wallets'));
+export const STATE_FILE = join(STATE_DIR, `state-${NETWORK}.json`);
+
+// Anything that moves value requires an explicit confirm:true unless opted out.
+export const REQUIRE_CONFIRM = (() => {
+ const raw = env('REQUIRE_CONFIRM');
+ if (raw === undefined) return true;
+ return !['0', 'false', 'no', 'off'].includes(String(raw).toLowerCase());
+})();
+
+// Per-request timeout (ms) for off-chain fetches (x402 resources, registries).
+export const HTTP_TIMEOUT_MS = (() => {
+ const raw = env('OAW_TIMEOUT_MS');
+ if (raw === undefined) return 30000;
+ const n = Number(raw);
+ if (!Number.isFinite(n) || n <= 0) {
+ throw Object.assign(new Error(`OAW_TIMEOUT_MS must be a positive number (got "${raw}")`), { code: 'bad_config' });
+ }
+ return n;
+})();
+
+// three.ws API host: the cross-chain agent deployment feed.
+export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws').replace(/\/+$/, '');
+
+export const USER_AGENT = '@three-ws/onchain-agent-wallets';
diff --git a/packages/onchain-agent-wallets/src/index.js b/packages/onchain-agent-wallets/src/index.js
new file mode 100644
index 000000000..e84bba7c6
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/index.js
@@ -0,0 +1,160 @@
+#!/usr/bin/env node
+// @three-ws/onchain-agent-wallets: MCP server entry point.
+//
+// Give an AI agent a real Solana wallet without giving it your money.
+//
+// The owner's wallet holds the funds. Each agent gets a vault token account the
+// owner owns, plus a capped SPL Token delegation over it. The token program
+// enforces the ceiling on-chain; this server enforces the owner's finer rules
+// (per-transaction cap, rolling daily cap, recipient and host allowlists,
+// expiry, pause, confirm-above threshold) before it signs anything.
+//
+// Custody create_agent_wallet, fund_agent_wallet, approve_agent_allowance,
+// withdraw_from_vault, revoke_agent_wallet
+// Guardrails set_guardrails
+// Spending agent_pay, pay_x402
+// Visibility agent_wallet_status, list_agent_wallets, spend_log
+// Deployment deploy_agent_onchain, export_agent_runtime
+// Wallet lane send_signed_transaction
+//
+// Nothing is mocked: real SPL Token delegations, real Solana, real x402
+// settlement. Devnet works end to end for free rehearsal (OAW_NETWORK=devnet).
+//
+// Run standalone:
+// OWNER_SECRET_KEY=<base58> node src/index.js
+//
+// Or wire into Claude Code / Cursor: see README.md.
+
+import { realpathSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { pathToFileURL } from 'node:url';
+
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
+
+import { NETWORK } from './config.js';
+
+import { def as createAgentWallet } from './tools/create-agent-wallet.js';
+import { def as fundAgentWallet } from './tools/fund-agent-wallet.js';
+import { def as approveAgentAllowance } from './tools/approve-agent-allowance.js';
+import { def as setGuardrails } from './tools/set-guardrails.js';
+import { def as agentPay } from './tools/agent-pay.js';
+import { def as payX402 } from './tools/pay-x402.js';
+import { def as withdrawFromVault } from './tools/withdraw-from-vault.js';
+import { def as revokeAgentWallet } from './tools/revoke-agent-wallet.js';
+import { def as agentWalletStatus } from './tools/agent-wallet-status.js';
+import { def as listAgentWallets } from './tools/list-agent-wallets.js';
+import { def as spendLog } from './tools/spend-log.js';
+import { def as deployAgentOnchain } from './tools/deploy-agent-onchain.js';
+import { def as exportAgentRuntime } from './tools/export-agent-runtime.js';
+import { def as sendSignedTransaction } from './tools/send-signed-transaction.js';
+
+const require = createRequire(import.meta.url);
+const { version: PKG_VERSION } = require('../package.json');
+
+export const TOOLS = [
+ createAgentWallet,
+ fundAgentWallet,
+ approveAgentAllowance,
+ setGuardrails,
+ agentPay,
+ payX402,
+ withdrawFromVault,
+ revokeAgentWallet,
+ agentWalletStatus,
+ listAgentWallets,
+ spendLog,
+ deployAgentOnchain,
+ exportAgentRuntime,
+ sendSignedTransaction,
+];
+
+/**
+ * Construct a fully-registered McpServer without connecting a transport or
+ * requiring a key. Registration is env-free; only signing needs material.
+ * Safe to import from tests.
+ * @returns {McpServer}
+ */
+export function buildServer() {
+ const server = new McpServer(
+ { name: 'onchain-agent-wallets', title: 'Onchain Agent Wallets', version: PKG_VERSION },
+ {
+ capabilities: { tools: {} },
+ instructions:
+ 'Onchain agent wallets on Solana, by three.ws. The owner keeps custody: funds sit in a vault token ' +
+ 'account the OWNER owns, and the agent holds only a capped SPL Token delegation over it, which the token ' +
+ 'program enforces and the owner can revoke in one instruction. create_agent_wallet sets this up in one ' +
+ 'call; fund_agent_wallet backs it; set_guardrails adds per-transaction, daily, recipient, host, expiry, ' +
+ 'and pause rules on top; agent_pay and pay_x402 are how the agent spends inside them; ' +
+ 'revoke_agent_wallet is the kill switch. Every value-moving tool shows a summary first and refuses to ' +
+ 'broadcast without confirm:true. If no owner key is configured, owner actions come back as an unsigned ' +
+ 'transaction for Phantom, Solflare, Backpack, or a Ledger to sign, then send_signed_transaction ' +
+ 'broadcasts it, so a secret key never has to touch this machine. When a spend is refused, the error ' +
+ 'names the exact rule and what the owner would have to change.',
+ },
+ );
+
+ for (const tool of TOOLS) {
+ server.registerTool(
+ tool.name,
+ {
+ title: tool.title,
+ description: tool.description,
+ inputSchema: tool.inputSchema,
+ annotations: tool.annotations,
+ },
+ async (args, extra) => {
+ try {
+ const result = await tool.handler(args, extra);
+ const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
+ return { content: [{ type: 'text', text }] };
+ } catch (err) {
+ const payload = {
+ ok: false,
+ error: err?.code || 'unhandled',
+ message: err?.message || String(err),
+ // Guardrail refusals carry their full reasoning so the caller
+ // can see which rule stopped it rather than guessing.
+ ...(err?.checks ? { checks: err.checks } : {}),
+ ...(err?.policy ? { guardrails: err.policy } : {}),
+ ...(err?.spendable ? { spendable: err.spendable } : {}),
+ ...(err?.spent_24h ? { spent_24h: err.spent_24h } : {}),
+ ...(err?.signature ? { signature: err.signature } : {}),
+ ...(err?.link ? { link: err.link } : {}),
+ };
+ return {
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
+ isError: true,
+ };
+ }
+ },
+ );
+ }
+
+ return server;
+}
+
+async function main() {
+ const server = buildServer();
+ const transport = new StdioServerTransport();
+ await server.connect(transport);
+ console.error(
+ `[onchain-agent-wallets@${PKG_VERSION}] connected over stdio with ${TOOLS.length} tools on ${NETWORK}`,
+ );
+}
+
+function isProcessEntryPoint() {
+ if (!process.argv[1]) return false;
+ try {
+ return import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
+ } catch {
+ return false;
+ }
+}
+
+if (isProcessEntryPoint()) {
+ main().catch((err) => {
+ console.error('[onchain-agent-wallets] fatal:', err);
+ process.exit(1);
+ });
+}
diff --git a/packages/onchain-agent-wallets/src/lib/agent.js b/packages/onchain-agent-wallets/src/lib/agent.js
new file mode 100644
index 000000000..256188a20
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/lib/agent.js
@@ -0,0 +1,159 @@
+// Everything a spend needs, gathered in one place: the agent record, its
+// keypair, live on-chain vault state, the owner's policy, and the rolling spend
+// window. Tools stay thin because this is where the pipeline lives:
+//
+// context -> authorize -> execute -> record
+//
+// Authorization always runs against numbers read from the chain in the same
+// call, never against cached notes, so a revoke that landed one second ago is
+// respected.
+
+import { NETWORK } from '../config.js';
+import { connectionFor, keypairFrom, mintDecimals, tokenProgramFor, fromBaseUnits, toBaseUnits } from './solana.js';
+import { readVault, spendableUnits, vaultAddress } from './vault.js';
+import { evaluateSpend, spentInWindow, normalizePolicy } from './policy.js';
+import { getAgent, recordSpend, spendHistory } from './store.js';
+
+/** Load an agent and everything currently true about it. */
+export async function agentContext(agentId) {
+ const record = getAgent(agentId);
+ const connection = connectionFor(NETWORK);
+ const programId = await tokenProgramFor(connection, record.mint);
+ const decimals = await mintDecimals(connection, record.mint, programId);
+ const vault = await readVault({ connection, vault: record.vault, programId });
+ const policy = normalizePolicy({}, record.policy);
+ const ledger = spendHistory(record.id);
+ const spentToday = spentInWindow(ledger, { hours: 24 });
+
+ return {
+ record,
+ connection,
+ network: NETWORK,
+ programId,
+ decimals,
+ vault,
+ policy,
+ ledger,
+ spentToday,
+ spendable: spendableUnits(vault),
+ keypair: () => keypairFrom(record.agent_secret, `agent key for "${record.id}"`),
+ human: (units) => fromBaseUnits(units, decimals),
+ units: (amount) => toBaseUnits(amount, decimals),
+ };
+}
+
+/**
+ * Run the guardrails. Returns the decision on approval; on refusal it records
+ * the denial in the ledger and throws an error carrying every check, so the
+ * caller sees exactly which rule stopped it and what to change.
+ */
+export function authorizeSpend(ctx, { amount, recipient, host, confirm = false, kind, resource }) {
+ const decision = evaluateSpend({
+ policy: ctx.policy,
+ amount,
+ decimals: ctx.decimals,
+ spentToday: ctx.spentToday,
+ remainingAllowance: ctx.vault.exists ? ctx.vault.delegatedAmount : 0n,
+ recipient,
+ host,
+ confirm,
+ });
+
+ if (!decision.allowed) {
+ recordSpend({
+ agent: ctx.record.id,
+ kind: kind || 'spend',
+ allowed: false,
+ amount: ctx.human(amount),
+ base_units: String(amount),
+ mint: ctx.record.mint,
+ recipient: recipient || null,
+ resource: resource || null,
+ code: decision.code,
+ reason: decision.reason,
+ });
+ throw Object.assign(new Error(decision.reason), {
+ code: decision.code,
+ checks: decision.checks,
+ policy: ctx.policy,
+ spendable: ctx.human(ctx.spendable),
+ spent_24h: ctx.human(ctx.spentToday),
+ });
+ }
+
+ if (amount > ctx.spendable) {
+ const shortfall = amount - ctx.spendable;
+ throw Object.assign(
+ new Error(
+ `the vault can only cover ${ctx.human(ctx.spendable)} right now (short by ${ctx.human(shortfall)}). ` +
+ `Vault balance ${ctx.human(ctx.vault.balance)}, remaining allowance ${ctx.human(ctx.vault.delegatedAmount)}. ` +
+ 'Ask the owner to run fund_agent_wallet.',
+ ),
+ { code: 'insufficient_vault', checks: decision.checks },
+ );
+ }
+
+ return decision;
+}
+
+/** Write the successful spend to the ledger. The daily cap is computed from these rows. */
+export function logSpend(ctx, entry) {
+ return recordSpend({
+ agent: ctx.record.id,
+ allowed: true,
+ mint: ctx.record.mint,
+ ...entry,
+ });
+}
+
+/** The public view of an agent: no secret material, live on-chain numbers. */
+export function describeAgent(ctx) {
+ return {
+ id: ctx.record.id,
+ label: ctx.record.label || null,
+ network: ctx.network,
+ owner: ctx.record.owner,
+ agent_address: ctx.record.agent_pubkey,
+ vault: ctx.record.vault,
+ mint: ctx.record.mint,
+ asset: ctx.record.asset_symbol || null,
+ created_at: ctx.record.created_at,
+ vault_balance: ctx.human(ctx.vault.balance),
+ allowance_remaining: ctx.human(ctx.vault.exists ? ctx.vault.delegatedAmount : 0n),
+ spendable_now: ctx.human(ctx.spendable),
+ spent_24h: ctx.human(ctx.spentToday),
+ delegate_is_agent: ctx.vault.delegate === ctx.record.agent_pubkey,
+ revoked: ctx.vault.exists && !ctx.vault.delegate,
+ policy: ctx.policy,
+ deployment: ctx.record.deployment || null,
+ };
+}
+
+/** Confirm the on-chain delegation still names this agent. Cheap, and catches a silent revoke. */
+export function assertDelegated(ctx) {
+ if (!ctx.vault.exists) {
+ throw Object.assign(new Error(`the vault for "${ctx.record.id}" does not exist on ${ctx.network} yet`), {
+ code: 'no_vault',
+ });
+ }
+ if (!ctx.vault.delegate) {
+ throw Object.assign(
+ new Error(`the owner has revoked "${ctx.record.id}". Run approve_agent_allowance to grant a new allowance.`),
+ { code: 'revoked' },
+ );
+ }
+ if (ctx.vault.delegate !== ctx.record.agent_pubkey) {
+ throw Object.assign(
+ new Error(
+ `the vault is delegated to ${ctx.vault.delegate}, not to this agent (${ctx.record.agent_pubkey}). ` +
+ 'An approve for a different key replaced this one.',
+ ),
+ { code: 'delegate_mismatch' },
+ );
+ }
+ if (ctx.vault.frozen) {
+ throw Object.assign(new Error('the vault token account is frozen by the mint authority'), { code: 'frozen' });
+ }
+}
+
+export { vaultAddress };
diff --git a/packages/onchain-agent-wallets/src/lib/execute.js b/packages/onchain-agent-wallets/src/lib/execute.js
new file mode 100644
index 000000000..ad95f94c6
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/lib/execute.js
@@ -0,0 +1,101 @@
+// One gate for everything that moves value.
+//
+// Order is deliberate and identical for every tool:
+//
+// 1. Show the deal. Amount, asset, destination, chain, cost. If confirmation
+// is required and the caller did not pass confirm:true, nothing is built
+// and nothing is signed. The caller gets the table and stops.
+// 2. Sign it, if this process is holding the relevant key.
+// 3. Otherwise hand back an unsigned transaction for a real wallet to sign.
+//
+// Step 3 is why an owner never has to paste a secret key anywhere to use this
+// server: the whole custody lane works through Phantom, Solflare, Backpack, or
+// a Ledger.
+
+import { REQUIRE_CONFIRM, OWNER_SECRET, NETWORK } from '../config.js';
+import { keypairFrom, toPublicKey, accountLink } from './solana.js';
+import { sendWithSigners, prepareForWallet } from './tx.js';
+
+/** The owner's keypair if this process was given one, else null. */
+export function ownerKeypair(secret) {
+ const material = secret !== undefined && String(secret).trim() !== '' ? secret : OWNER_SECRET;
+ return material ? keypairFrom(material, 'owner key') : null;
+}
+
+/**
+ * Resolve who the owner is: an explicit address, the configured key, or fail
+ * with an actionable message rather than a null dereference.
+ */
+export function resolveOwner({ owner, secret }) {
+ if (owner) return toPublicKey(owner, 'owner').toBase58();
+ const kp = ownerKeypair(secret);
+ if (kp) return kp.publicKey.toBase58();
+ throw Object.assign(
+ new Error(
+ 'No owner given. Pass `owner` with your wallet address (the non-custodial path: you sign in Phantom), ' +
+ 'or set OWNER_SECRET_KEY to let this server sign for you.',
+ ),
+ { code: 'no_owner' },
+ );
+}
+
+/**
+ * Execute an owner-authorized action, or prepare it for a browser wallet.
+ *
+ * @param {object} input
+ * @param {object} input.summary the confirmation table: what is about to happen
+ */
+export async function ownerAction({
+ connection,
+ owner,
+ instructions,
+ confirm = false,
+ secret,
+ summary,
+ network = NETWORK,
+ note,
+}) {
+ if (REQUIRE_CONFIRM && !confirm) {
+ return {
+ ok: false,
+ action: 'confirm_required',
+ summary,
+ message: 'Nothing has been signed or broadcast. Review the summary above, then re-issue with confirm:true.',
+ };
+ }
+
+ const kp = ownerKeypair(secret);
+ if (kp) {
+ if (kp.publicKey.toBase58() !== String(owner)) {
+ throw Object.assign(
+ new Error(
+ `the configured owner key is ${kp.publicKey.toBase58()} but this call targets ${owner}. ` +
+ 'Pass the matching `secret`, or drop `owner` to use the configured key.',
+ ),
+ { code: 'owner_mismatch' },
+ );
+ }
+ const sent = await sendWithSigners({ connection, payer: kp.publicKey, instructions, signers: [kp], network });
+ return { ok: true, action: 'sent', signed_by: 'owner_key', summary, ...sent };
+ }
+
+ const prepared = await prepareForWallet({ connection, payer: owner, instructions, network, note });
+ return { ok: true, action: 'prepared_for_wallet', signed_by: 'your_wallet', summary, ...prepared };
+}
+
+/** Execute an agent-authorized action. The agent always holds its own key. */
+export async function agentAction({ connection, keypair, instructions, network = NETWORK }) {
+ return sendWithSigners({ connection, payer: keypair.publicKey, instructions, signers: [keypair], network });
+}
+
+/** Uniform confirmation table. Every value-moving tool renders one of these. */
+export function summarize({ action, amount, asset, from, to, network = NETWORK, extra = {} }) {
+ return {
+ action,
+ ...(amount !== undefined ? { amount: `${amount} ${asset || ''}`.trim() } : {}),
+ ...(from ? { from, from_link: accountLink(from, network) } : {}),
+ ...(to ? { to, to_link: accountLink(to, network) } : {}),
+ network: network === 'devnet' ? 'Solana devnet' : 'Solana mainnet',
+ ...extra,
+ };
+}
diff --git a/packages/onchain-agent-wallets/src/lib/index.js b/packages/onchain-agent-wallets/src/lib/index.js
new file mode 100644
index 000000000..c0c6f0a17
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/lib/index.js
@@ -0,0 +1,41 @@
+// Library surface, for embedding the custody model outside MCP: a web app, a
+// script, an agent framework. Everything here is plain web3.js and spl-token.
+
+export {
+ assertAgentId,
+ seedFor,
+ vaultAddress,
+ createVaultInstructions,
+ approveInstruction,
+ revokeInstruction,
+ depositInstructions,
+ withdrawInstructions,
+ delegatedTransferInstructions,
+ readVault,
+ spendableUnits,
+} from './vault.js';
+
+export { DEFAULT_POLICY, normalizePolicy, normalizeHost, evaluateSpend, spentInWindow } from './policy.js';
+
+export {
+ USDC_MINT,
+ MIN_AGENT_FEE_LAMPORTS,
+ connectionFor,
+ keypairFrom,
+ toPublicKey,
+ solBalance,
+ mintDecimals,
+ tokenProgramFor,
+ toBaseUnits,
+ fromBaseUnits,
+ tokenAccount,
+ ataFor,
+ txLink,
+ accountLink,
+} from './solana.js';
+
+export { buildTransaction, sendWithSigners, prepareForWallet, sendSignedBase64 } from './tx.js';
+
+export { probeResource, selectRequirement, requiredUnits, payAndFetch, clusterOf } from './x402.js';
+
+export { agentContext, authorizeSpend, assertDelegated, describeAgent, logSpend } from './agent.js';
diff --git a/packages/onchain-agent-wallets/src/lib/policy.js b/packages/onchain-agent-wallets/src/lib/policy.js
new file mode 100644
index 000000000..be0edddd6
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/lib/policy.js
@@ -0,0 +1,268 @@
+// The guardrail engine.
+//
+// Two layers protect the owner, and they are independent on purpose:
+//
+// 1. On-chain. The SPL Token program caps the agent's delegated amount on the
+// vault account. Nothing this file does can raise that ceiling, and the
+// owner can drop it to zero with a single revoke.
+// 2. Local. This file decides whether a spend that WOULD be allowed on-chain
+// is allowed by the owner's rules: per-transaction cap, rolling daily cap,
+// recipient allowlist, x402 host allowlist, expiry, pause, and a
+// confirm-above threshold that forces a human yes.
+//
+// Every decision, allow or deny, is returned with the full list of checks so
+// the caller can show its work and so the ledger records why.
+
+import { fromBaseUnits, toBaseUnits, toPublicKey } from './solana.js';
+
+export const DEFAULT_POLICY = {
+ per_tx: null,
+ daily: null,
+ allow_recipients: [],
+ allow_hosts: [],
+ expires_at: null,
+ confirm_over: null,
+ paused: false,
+};
+
+/** Normalize and validate a partial policy patch. Throws on anything malformed. */
+export function normalizePolicy(patch = {}, base = DEFAULT_POLICY) {
+ const next = { ...DEFAULT_POLICY, ...base };
+
+ for (const key of ['per_tx', 'daily', 'confirm_over']) {
+ if (!(key in patch)) continue;
+ const raw = patch[key];
+ if (raw === null || raw === '' || raw === undefined) {
+ next[key] = null;
+ continue;
+ }
+ const s = String(raw).trim();
+ if (!/^\d*(\.\d+)?$/.test(s) || s === '') {
+ throw Object.assign(new Error(`${key} must be a positive decimal amount (got "${raw}")`), {
+ code: 'bad_policy',
+ });
+ }
+ next[key] = s;
+ }
+
+ if ('allow_recipients' in patch) {
+ const list = patch.allow_recipients ?? [];
+ if (!Array.isArray(list)) {
+ throw Object.assign(new Error('allow_recipients must be an array of Solana addresses'), { code: 'bad_policy' });
+ }
+ next.allow_recipients = list.map((a) => toPublicKey(a, 'allow_recipients entry').toBase58());
+ }
+
+ if ('allow_hosts' in patch) {
+ const list = patch.allow_hosts ?? [];
+ if (!Array.isArray(list)) {
+ throw Object.assign(new Error('allow_hosts must be an array of hostnames'), { code: 'bad_policy' });
+ }
+ next.allow_hosts = list.map((h) => normalizeHost(h));
+ }
+
+ if ('expires_at' in patch) {
+ const raw = patch.expires_at;
+ if (raw === null || raw === '' || raw === undefined) {
+ next.expires_at = null;
+ } else {
+ const t = new Date(raw);
+ if (Number.isNaN(t.getTime())) {
+ throw Object.assign(new Error(`expires_at must be an ISO timestamp (got "${raw}")`), { code: 'bad_policy' });
+ }
+ next.expires_at = t.toISOString();
+ }
+ }
+
+ if ('paused' in patch) next.paused = Boolean(patch.paused);
+
+ if (next.per_tx && next.daily && Number(next.per_tx) > Number(next.daily)) {
+ throw Object.assign(
+ new Error(`per_tx (${next.per_tx}) cannot exceed daily (${next.daily}): the daily cap would never be reachable`),
+ { code: 'bad_policy' },
+ );
+ }
+
+ return next;
+}
+
+/** Accept a bare hostname or any URL and return the lowercase hostname. */
+export function normalizeHost(value) {
+ const raw = String(value || '').trim().toLowerCase();
+ if (!raw) throw Object.assign(new Error('host cannot be empty'), { code: 'bad_policy' });
+ const withScheme = raw.includes('://') ? raw : `https://${raw}`;
+ let u;
+ try {
+ u = new URL(withScheme);
+ } catch {
+ throw Object.assign(new Error(`not a valid host or URL: "${value}"`), { code: 'bad_policy' });
+ }
+ if (!u.hostname) throw Object.assign(new Error(`not a valid host or URL: "${value}"`), { code: 'bad_policy' });
+ return u.hostname;
+}
+
+/** An allowlisted host covers its subdomains: "example.com" matches "api.example.com". */
+function hostAllowed(list, host) {
+ return list.some((entry) => host === entry || host.endsWith(`.${entry}`));
+}
+
+/**
+ * Decide a single spend.
+ *
+ * @param {object} input
+ * @param {object} input.policy normalized policy
+ * @param {bigint} input.amount spend amount in base units
+ * @param {number} input.decimals mint decimals
+ * @param {bigint} input.spentToday base units already spent in the rolling window
+ * @param {bigint} input.remainingAllowance live on-chain delegated amount left
+ * @param {string} [input.recipient] destination address, for direct transfers
+ * @param {string} [input.host] resource hostname, for x402 calls
+ * @param {boolean} [input.confirm] the caller passed confirm:true
+ * @param {Date} [input.now]
+ * @returns {{allowed: boolean, requires_confirm: boolean, code: string|null, reason: string|null, checks: object[]}}
+ */
+export function evaluateSpend({
+ policy,
+ amount,
+ decimals,
+ spentToday = 0n,
+ remainingAllowance = null,
+ recipient,
+ host,
+ confirm = false,
+ now = new Date(),
+}) {
+ const checks = [];
+ const human = (units) => fromBaseUnits(units, decimals);
+ let denial = null;
+
+ const check = (name, ok, detail, code) => {
+ checks.push({ check: name, ok, detail });
+ if (!ok && !denial) denial = { code, reason: detail };
+ };
+
+ check('paused', !policy.paused, policy.paused ? 'the wallet is paused by the owner' : 'wallet is active', 'paused');
+
+ const expired = policy.expires_at ? new Date(policy.expires_at).getTime() <= now.getTime() : false;
+ check(
+ 'expiry',
+ !expired,
+ policy.expires_at
+ ? expired
+ ? `the delegation expired at ${policy.expires_at}`
+ : `valid until ${policy.expires_at}`
+ : 'no expiry set',
+ 'expired',
+ );
+
+ check('amount', amount > 0n, amount > 0n ? `spending ${human(amount)}` : 'amount must be greater than zero', 'bad_amount');
+
+ if (policy.per_tx) {
+ const cap = toBaseUnits(policy.per_tx, decimals);
+ check(
+ 'per_tx',
+ amount <= cap,
+ amount <= cap
+ ? `${human(amount)} is within the ${policy.per_tx} per-transaction cap`
+ : `${human(amount)} exceeds the ${policy.per_tx} per-transaction cap`,
+ 'over_per_tx',
+ );
+ } else {
+ checks.push({ check: 'per_tx', ok: true, detail: 'no per-transaction cap set' });
+ }
+
+ if (policy.daily) {
+ const cap = toBaseUnits(policy.daily, decimals);
+ const after = spentToday + amount;
+ check(
+ 'daily',
+ after <= cap,
+ after <= cap
+ ? `${human(after)} of ${policy.daily} used in the last 24h after this spend`
+ : `${human(after)} would exceed the ${policy.daily} daily cap (${human(spentToday)} already spent)`,
+ 'over_daily',
+ );
+ } else {
+ checks.push({ check: 'daily', ok: true, detail: 'no daily cap set' });
+ }
+
+ if (remainingAllowance !== null) {
+ check(
+ 'onchain_allowance',
+ amount <= remainingAllowance,
+ amount <= remainingAllowance
+ ? `${human(remainingAllowance)} of on-chain allowance remains`
+ : `${human(amount)} exceeds the ${human(remainingAllowance)} the token program still allows`,
+ 'over_allowance',
+ );
+ }
+
+ if (recipient) {
+ const list = policy.allow_recipients || [];
+ const ok = list.length === 0 || list.includes(recipient);
+ check(
+ 'recipient',
+ ok,
+ list.length === 0
+ ? 'recipients unrestricted'
+ : ok
+ ? `${recipient} is on the recipient allowlist`
+ : `${recipient} is not on the recipient allowlist (${list.length} allowed)`,
+ 'recipient_not_allowed',
+ );
+ }
+
+ if (host) {
+ const list = policy.allow_hosts || [];
+ const ok = list.length === 0 || hostAllowed(list, host);
+ check(
+ 'host',
+ ok,
+ list.length === 0
+ ? 'hosts unrestricted'
+ : ok
+ ? `${host} is on the host allowlist`
+ : `${host} is not on the host allowlist (${list.join(', ')})`,
+ 'host_not_allowed',
+ );
+ }
+
+ let requires_confirm = false;
+ if (policy.confirm_over !== null && policy.confirm_over !== undefined) {
+ const threshold = toBaseUnits(policy.confirm_over, decimals);
+ if (amount > threshold && !confirm) {
+ requires_confirm = true;
+ checks.push({
+ check: 'confirm_over',
+ ok: false,
+ detail: `${human(amount)} is above the ${policy.confirm_over} confirm threshold: re-issue with confirm:true`,
+ });
+ } else {
+ checks.push({
+ check: 'confirm_over',
+ ok: true,
+ detail: amount > threshold ? 'confirmed by the caller' : `at or below the ${policy.confirm_over} threshold`,
+ });
+ }
+ }
+
+ if (denial) return { allowed: false, requires_confirm: false, ...denial, checks };
+ if (requires_confirm) {
+ return {
+ allowed: false,
+ requires_confirm: true,
+ code: 'needs_confirmation',
+ reason: `this spend is above the ${policy.confirm_over} confirm threshold. Re-issue the call with confirm:true.`,
+ checks,
+ };
+ }
+ return { allowed: true, requires_confirm: false, code: null, reason: null, checks };
+}
+
+/** Sum of allowed spends inside the rolling window, in base units. */
+export function spentInWindow(ledger, { hours = 24, now = new Date() } = {}) {
+ const cutoff = now.getTime() - hours * 3600 * 1000;
+ return ledger
+ .filter((row) => row.allowed && row.base_units && new Date(row.at).getTime() >= cutoff)
+ .reduce((sum, row) => sum + BigInt(row.base_units), 0n);
+}
diff --git a/packages/onchain-agent-wallets/src/lib/solana.js b/packages/onchain-agent-wallets/src/lib/solana.js
new file mode 100644
index 000000000..592fc2cfe
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/lib/solana.js
@@ -0,0 +1,179 @@
+// Connection, key handling, balances, token metadata, and explorer links.
+
+import bs58 from 'bs58';
+import { Connection, Keypair, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';
+import {
+ getMint,
+ getAccount,
+ getAssociatedTokenAddressSync,
+ TokenAccountNotFoundError,
+ TokenInvalidAccountOwnerError,
+ TokenInvalidAccountSizeError,
+ TOKEN_PROGRAM_ID,
+ TOKEN_2022_PROGRAM_ID,
+} from '@solana/spl-token';
+
+import { NETWORK, rpcFor } from '../config.js';
+
+export { LAMPORTS_PER_SOL, TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID };
+
+// Circle's canonical USDC mints. The default asset for agent spending because
+// x402 prices in it and it is the deepest stable on Solana.
+export const USDC_MINT = {
+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',
+};
+
+// A signature costs 5000 lamports. An agent pays its own fees, so it needs a
+// little SOL of its own; this is the floor below which it cannot transact.
+export const MIN_AGENT_FEE_LAMPORTS = 5_000 * 20;
+
+const connections = new Map();
+
+/** Cached Connection per network. Confirmed commitment: fast, and final enough to gate a spend. */
+export function connectionFor(network = NETWORK) {
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+ if (!connections.has(net)) {
+ connections.set(net, new Connection(rpcFor(net), { commitment: 'confirmed' }));
+ }
+ return connections.get(net);
+}
+
+/** Parse a base58 secret key or a JSON byte array into a Keypair. */
+export function keypairFrom(secret, label = 'secret') {
+ const raw = String(secret || '').trim();
+ if (!raw) {
+ throw Object.assign(new Error(`No ${label} available. Pass one, or set OWNER_SECRET_KEY.`), { code: 'no_signer' });
+ }
+ let bytes;
+ if (raw.startsWith('[')) {
+ try {
+ bytes = Uint8Array.from(JSON.parse(raw));
+ } catch {
+ throw Object.assign(new Error(`${label} looks like a JSON array but does not parse`), { code: 'bad_secret' });
+ }
+ } else {
+ try {
+ bytes = bs58.decode(raw);
+ } catch {
+ throw Object.assign(new Error(`${label} is not valid base58`), { code: 'bad_secret' });
+ }
+ }
+ if (bytes.length !== 64) {
+ throw Object.assign(new Error(`${label} must be a 64-byte keypair (got ${bytes.length} bytes)`), {
+ code: 'bad_secret',
+ });
+ }
+ return Keypair.fromSecretKey(bytes);
+}
+
+/** Validate and normalize an address, with a field name that survives into the error. */
+export function toPublicKey(value, field = 'address') {
+ try {
+ return new PublicKey(String(value).trim());
+ } catch {
+ throw Object.assign(new Error(`${field} is not a valid Solana address: "${value}"`), { code: 'bad_address' });
+ }
+}
+
+/** SOL balance of an address, in SOL. */
+export async function solBalance(connection, address) {
+ const lamports = await connection.getBalance(toPublicKey(address, 'address'));
+ return lamports / LAMPORTS_PER_SOL;
+}
+
+/**
+ * Which token program owns this mint: classic SPL Token or Token-2022. Every
+ * instruction we build is threaded with it, so a Token-2022 mint works without
+ * a special case anywhere else.
+ */
+const programCache = new Map();
+export async function tokenProgramFor(connection, mint) {
+ const key = `${connection.rpcEndpoint}:${mint}`;
+ if (programCache.has(key)) return programCache.get(key);
+ const info = await connection.getAccountInfo(toPublicKey(mint, 'mint'));
+ if (!info) {
+ throw Object.assign(new Error(`mint ${mint} does not exist on this cluster`), { code: 'unknown_mint' });
+ }
+ const owner = info.owner;
+ if (!owner.equals(TOKEN_PROGRAM_ID) && !owner.equals(TOKEN_2022_PROGRAM_ID)) {
+ throw Object.assign(new Error(`${mint} is not an SPL token mint (owned by ${owner.toBase58()})`), {
+ code: 'unknown_mint',
+ });
+ }
+ programCache.set(key, owner);
+ return owner;
+}
+
+/** Decimals for a mint, read from the chain. Cached: a mint's decimals never change. */
+const decimalsCache = new Map();
+export async function mintDecimals(connection, mint, programId) {
+ const key = `${connection.rpcEndpoint}:${mint}`;
+ if (decimalsCache.has(key)) return decimalsCache.get(key);
+ const program = programId || (await tokenProgramFor(connection, mint));
+ const info = await getMint(connection, toPublicKey(mint, 'mint'), undefined, program);
+ decimalsCache.set(key, info.decimals);
+ return info.decimals;
+}
+
+/** Human amount to base units, without float drift. */
+export function toBaseUnits(amount, decimals) {
+ const s = String(amount).trim();
+ if (!/^\d*(\.\d*)?$/.test(s) || s === '' || s === '.') {
+ throw Object.assign(new Error(`amount must be a positive decimal number (got "${amount}")`), {
+ code: 'bad_amount',
+ });
+ }
+ const [whole, frac = ''] = s.split('.');
+ if (frac.length > decimals) {
+ throw Object.assign(
+ new Error(`amount has ${frac.length} decimal places but the mint only has ${decimals}`),
+ { code: 'bad_amount' },
+ );
+ }
+ return BigInt(whole || '0') * 10n ** BigInt(decimals) + BigInt(frac.padEnd(decimals, '0') || '0');
+}
+
+/** Base units back to a human decimal string, exact. */
+export function fromBaseUnits(units, decimals) {
+ const n = BigInt(units);
+ const d = 10n ** BigInt(decimals);
+ const whole = n / d;
+ const frac = (n % d).toString().padStart(decimals, '0').replace(/0+$/, '');
+ return frac ? `${whole}.${frac}` : String(whole);
+}
+
+/**
+ * Token account state, or null when the account does not exist yet.
+ *
+ * spl-token signals a missing account by throwing a typed error whose message
+ * is empty, so this matches on the error class rather than its text.
+ */
+export async function tokenAccount(connection, address, programId = TOKEN_PROGRAM_ID) {
+ try {
+ return await getAccount(connection, toPublicKey(address, 'token account'), undefined, programId);
+ } catch (err) {
+ const missing =
+ err instanceof TokenAccountNotFoundError ||
+ err instanceof TokenInvalidAccountOwnerError ||
+ err instanceof TokenInvalidAccountSizeError ||
+ /could not find account|TokenAccountNotFound|TokenInvalidAccountOwner/i.test(err?.name || err?.message || '');
+ if (missing) return null;
+ throw err;
+ }
+}
+
+/** The owner's associated token account for a mint. allowOwnerOffCurve: PDAs can hold tokens too. */
+export function ataFor(mint, owner, programId = TOKEN_PROGRAM_ID) {
+ return getAssociatedTokenAddressSync(toPublicKey(mint, 'mint'), toPublicKey(owner, 'owner'), true, programId);
+}
+
+const cluster = (network) => (network === 'devnet' ? '?cluster=devnet' : '');
+
+export function txLink(signature, network = NETWORK) {
+ return `https://solscan.io/tx/${signature}${cluster(network)}`;
+}
+
+export function accountLink(address, network = NETWORK) {
+ return `https://solscan.io/account/${address}${cluster(network)}`;
+}
diff --git a/packages/onchain-agent-wallets/src/lib/store.js b/packages/onchain-agent-wallets/src/lib/store.js
new file mode 100644
index 000000000..b507b61f5
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/lib/store.js
@@ -0,0 +1,91 @@
+// Local state: agent records, guardrail policies, and the append-only spend
+// ledger. One JSON file per network, written 0600 inside a 0700 directory,
+// because it holds agent secret keys.
+//
+// It deliberately holds no owner key and no custody: every record here is
+// reconstructible from the chain (the vault address is derived from the owner
+// pubkey plus the agent id, and the live allowance is read from the token
+// account). Losing this file loses the agent's fee key and its history, never
+// the owner's money.
+
+import { mkdirSync, readFileSync, writeFileSync, renameSync, chmodSync, existsSync } from 'node:fs';
+import { dirname } from 'node:path';
+
+import { STATE_DIR, STATE_FILE, NETWORK } from '../config.js';
+
+const EMPTY = { version: 1, network: NETWORK, agents: {}, ledger: [] };
+
+// Keep the ledger bounded so a long-running agent cannot grow the file without
+// limit. 5000 entries is months of traffic and still a small file.
+const MAX_LEDGER = 5000;
+
+function ensureDir() {
+ mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
+}
+
+export function readState() {
+ if (!existsSync(STATE_FILE)) return structuredClone(EMPTY);
+ let parsed;
+ try {
+ parsed = JSON.parse(readFileSync(STATE_FILE, 'utf8'));
+ } catch (err) {
+ throw Object.assign(
+ new Error(`state file at ${STATE_FILE} is not valid JSON: ${err.message}. Move it aside to start fresh.`),
+ { code: 'bad_state' },
+ );
+ }
+ return { ...structuredClone(EMPTY), ...parsed, agents: parsed.agents || {}, ledger: parsed.ledger || [] };
+}
+
+export function writeState(state) {
+ ensureDir();
+ const tmp = `${STATE_FILE}.${process.pid}.tmp`;
+ const payload = { ...state, ledger: (state.ledger || []).slice(-MAX_LEDGER) };
+ writeFileSync(tmp, `${JSON.stringify(payload, null, 2)}\n`, { mode: 0o600 });
+ chmodSync(tmp, 0o600);
+ renameSync(tmp, STATE_FILE);
+ chmodSync(STATE_FILE, 0o600);
+ return STATE_FILE;
+}
+
+/** Read, mutate, write. The only supported way to change state. */
+export function updateState(mutator) {
+ const state = readState();
+ const result = mutator(state);
+ writeState(state);
+ return result;
+}
+
+export function getAgent(id) {
+ const agent = readState().agents[String(id || '').trim()];
+ if (!agent) {
+ throw Object.assign(
+ new Error(`no agent wallet named "${id}". Run list_agent_wallets, or create_agent_wallet to make one.`),
+ { code: 'unknown_agent' },
+ );
+ }
+ return agent;
+}
+
+export function listAgents() {
+ return Object.values(readState().agents);
+}
+
+/** Append one spend decision to the ledger. Called for allows AND denials. */
+export function recordSpend(entry) {
+ return updateState((state) => {
+ const row = { at: new Date().toISOString(), ...entry };
+ state.ledger.push(row);
+ return row;
+ });
+}
+
+/** Ledger rows for one agent, newest last. */
+export function spendHistory(agentId, { since } = {}) {
+ const cutoff = since ? new Date(since).getTime() : 0;
+ return readState().ledger.filter(
+ (row) => row.agent === agentId && (!cutoff || new Date(row.at).getTime() >= cutoff),
+ );
+}
+
+export const stateLocation = () => ({ dir: STATE_DIR, file: STATE_FILE, parent: dirname(STATE_FILE) });
diff --git a/packages/onchain-agent-wallets/src/lib/tx.js b/packages/onchain-agent-wallets/src/lib/tx.js
new file mode 100644
index 000000000..8a8b4a916
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/lib/tx.js
@@ -0,0 +1,99 @@
+// Transaction assembly, the self-custody signing lane, and the browser-wallet
+// lane. Every value-moving tool goes through exactly one of these two paths:
+//
+// sendWithSigners : this process holds a key (the agent's, or an owner key
+// the operator deliberately configured) and signs locally.
+// prepareForWallet : nothing is signed here. The unsigned transaction is
+// handed back base64-encoded for Phantom, Solflare,
+// Backpack, or a Ledger to sign, then broadcast through
+// send_signed_transaction. No key ever reaches this
+// machine.
+
+import { VersionedTransaction, TransactionMessage, ComputeBudgetProgram } from '@solana/web3.js';
+
+import { toPublicKey, txLink } from './solana.js';
+
+// A small priority fee keeps spends landing when the network is busy. Payments
+// that silently fail to confirm are worse than payments that cost a fraction
+// of a cent more.
+const PRIORITY_MICRO_LAMPORTS = 20_000;
+const COMPUTE_UNIT_LIMIT = 200_000;
+
+function withComputeBudget(instructions) {
+ return [
+ ComputeBudgetProgram.setComputeUnitLimit({ units: COMPUTE_UNIT_LIMIT }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: PRIORITY_MICRO_LAMPORTS }),
+ ...instructions,
+ ];
+}
+
+/** Compile instructions into an unsigned v0 transaction against a fresh blockhash. */
+export async function buildTransaction({ connection, payer, instructions }) {
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
+ const message = new TransactionMessage({
+ payerKey: toPublicKey(payer, 'fee payer'),
+ recentBlockhash: blockhash,
+ instructions: withComputeBudget(instructions),
+ }).compileToV0Message();
+ return { transaction: new VersionedTransaction(message), blockhash, lastValidBlockHeight };
+}
+
+/** Sign locally and broadcast, waiting for confirmation before returning. */
+export async function sendWithSigners({ connection, payer, instructions, signers, network }) {
+ const { transaction, blockhash, lastValidBlockHeight } = await buildTransaction({ connection, payer, instructions });
+ transaction.sign(signers);
+ const signature = await connection.sendTransaction(transaction, { maxRetries: 5 });
+ const result = await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');
+ if (result.value?.err) {
+ throw Object.assign(new Error(`transaction ${signature} failed on-chain: ${JSON.stringify(result.value.err)}`), {
+ code: 'tx_failed',
+ signature,
+ link: txLink(signature, network),
+ });
+ }
+ return { signature, link: txLink(signature, network) };
+}
+
+/** Build the same transaction unsigned, for a browser wallet or a Ledger to sign. */
+export async function prepareForWallet({ connection, payer, instructions, network, note }) {
+ const { transaction, blockhash, lastValidBlockHeight } = await buildTransaction({ connection, payer, instructions });
+ return {
+ transaction_base64: Buffer.from(transaction.serialize()).toString('base64'),
+ fee_payer: String(payer),
+ blockhash,
+ last_valid_block_height: lastValidBlockHeight,
+ network,
+ note,
+ next_step:
+ 'Sign this with your wallet (Phantom, Solflare, Backpack, Ledger), then call send_signed_transaction with the signed base64. Blockhashes expire in about 60 seconds, so sign promptly or re-run this tool.',
+ };
+}
+
+/** Broadcast a transaction a wallet already signed. */
+export async function sendSignedBase64({ connection, signedBase64, network }) {
+ let transaction;
+ try {
+ transaction = VersionedTransaction.deserialize(Buffer.from(String(signedBase64).trim(), 'base64'));
+ } catch (err) {
+ throw Object.assign(new Error(`could not decode the signed transaction: ${err.message}`), { code: 'bad_tx' });
+ }
+ if (!transaction.signatures?.some((sig) => sig.some((byte) => byte !== 0))) {
+ throw Object.assign(new Error('that transaction carries no signature. Sign it in your wallet first.'), {
+ code: 'unsigned_tx',
+ });
+ }
+ const signature = await connection.sendTransaction(transaction, { maxRetries: 5 });
+ const latest = await connection.getLatestBlockhash('confirmed');
+ const result = await connection.confirmTransaction(
+ { signature, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight },
+ 'confirmed',
+ );
+ if (result.value?.err) {
+ throw Object.assign(new Error(`transaction ${signature} failed on-chain: ${JSON.stringify(result.value.err)}`), {
+ code: 'tx_failed',
+ signature,
+ link: txLink(signature, network),
+ });
+ }
+ return { signature, link: txLink(signature, network) };
+}
diff --git a/packages/onchain-agent-wallets/src/lib/vault.js b/packages/onchain-agent-wallets/src/lib/vault.js
new file mode 100644
index 000000000..8a5ff5322
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/lib/vault.js
@@ -0,0 +1,223 @@
+// The custody primitive.
+//
+// Each agent gets a dedicated token account (its "vault") that the OWNER owns,
+// derived deterministically from the owner's pubkey plus the agent id:
+//
+// vault = PublicKey.createWithSeed(owner, "oaw1:<agentId>", tokenProgram)
+//
+// Deterministic derivation matters: the vault is recoverable from the owner
+// wallet and the agent name alone, with no local file and no registry. The
+// owner can always find it, drain it, and revoke it.
+//
+// The agent never owns the vault. It is granted an SPL Token DELEGATION over
+// it, capped at a fixed amount. From then on the token program itself refuses
+// any agent-signed transfer beyond that ceiling, and decrements the remaining
+// allowance on every spend. The owner can revoke in one instruction, or simply
+// withdraw the balance: neither needs the agent's cooperation.
+//
+// Why a seed account and not the agent's own associated token account: an ATA
+// belongs to whoever holds its key. Money in an agent-owned ATA is the agent's
+// money. Money in the vault is still the owner's, and the agent holds nothing
+// but permission.
+
+import { SystemProgram } from '@solana/web3.js';
+import {
+ ACCOUNT_SIZE,
+ createInitializeAccount3Instruction,
+ createApproveCheckedInstruction,
+ createRevokeInstruction,
+ createTransferCheckedInstruction,
+ createAssociatedTokenAccountIdempotentInstruction,
+ getMinimumBalanceForRentExemptAccount,
+} from '@solana/spl-token';
+
+import { toPublicKey, tokenAccount, ataFor, TOKEN_PROGRAM_ID } from './solana.js';
+
+// PublicKey.createWithSeed caps the seed at 32 bytes. "oaw1:" leaves 27.
+export const SEED_PREFIX = 'oaw1:';
+export const MAX_AGENT_ID = 32 - SEED_PREFIX.length;
+
+/** Agent ids are lowercase slugs: they become an on-chain account seed. */
+export function assertAgentId(id) {
+ const value = String(id || '').trim();
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(value)) {
+ throw Object.assign(
+ new Error(`agent id must be lowercase letters, digits, and hyphens, starting alphanumeric (got "${id}")`),
+ { code: 'bad_agent_id' },
+ );
+ }
+ if (value.length > MAX_AGENT_ID) {
+ throw Object.assign(
+ new Error(`agent id must be at most ${MAX_AGENT_ID} characters (it becomes an on-chain account seed)`),
+ { code: 'bad_agent_id' },
+ );
+ }
+ return value;
+}
+
+export const seedFor = (agentId) => `${SEED_PREFIX}${assertAgentId(agentId)}`;
+
+/** The deterministic vault address for an owner + agent id. */
+export async function vaultAddress(owner, agentId, programId = TOKEN_PROGRAM_ID) {
+ const { PublicKey } = await import('@solana/web3.js');
+ return PublicKey.createWithSeed(toPublicKey(owner, 'owner'), seedFor(agentId), programId);
+}
+
+/**
+ * Instructions that create the vault and grant the agent its capped allowance.
+ * Signed by the owner alone: the agent is named, never a signer.
+ */
+export async function createVaultInstructions({
+ connection,
+ owner,
+ agentId,
+ mint,
+ delegate,
+ allowance,
+ decimals,
+ programId = TOKEN_PROGRAM_ID,
+}) {
+ const ownerKey = toPublicKey(owner, 'owner');
+ const vault = await vaultAddress(ownerKey, agentId, programId);
+ const lamports = await getMinimumBalanceForRentExemptAccount(connection);
+ const instructions = [
+ SystemProgram.createAccountWithSeed({
+ fromPubkey: ownerKey,
+ newAccountPubkey: vault,
+ basePubkey: ownerKey,
+ seed: seedFor(agentId),
+ lamports,
+ space: ACCOUNT_SIZE,
+ programId,
+ }),
+ createInitializeAccount3Instruction(vault, toPublicKey(mint, 'mint'), ownerKey, programId),
+ ];
+ if (allowance > 0n) {
+ instructions.push(approveInstruction({ vault, mint, delegate, owner: ownerKey, allowance, decimals, programId }));
+ }
+ return { vault, instructions, rentLamports: lamports };
+}
+
+/** Set the agent's ceiling. Approve overwrites: a second approve replaces the first, it does not add. */
+export function approveInstruction({ vault, mint, delegate, owner, allowance, decimals, programId = TOKEN_PROGRAM_ID }) {
+ return createApproveCheckedInstruction(
+ toPublicKey(vault, 'vault'),
+ toPublicKey(mint, 'mint'),
+ toPublicKey(delegate, 'delegate'),
+ toPublicKey(owner, 'owner'),
+ allowance,
+ decimals,
+ [],
+ programId,
+ );
+}
+
+/** The kill switch. One instruction, owner-signed, drops the allowance to zero. */
+export function revokeInstruction({ vault, owner, programId = TOKEN_PROGRAM_ID }) {
+ return createRevokeInstruction(toPublicKey(vault, 'vault'), toPublicKey(owner, 'owner'), [], programId);
+}
+
+/** Owner tops the vault up from their own associated token account. */
+export function depositInstructions({ owner, vault, mint, amount, decimals, programId = TOKEN_PROGRAM_ID }) {
+ const source = ataFor(mint, owner, programId);
+ return [
+ createTransferCheckedInstruction(
+ source,
+ toPublicKey(mint, 'mint'),
+ toPublicKey(vault, 'vault'),
+ toPublicKey(owner, 'owner'),
+ amount,
+ decimals,
+ [],
+ programId,
+ ),
+ ];
+}
+
+/** Owner pulls funds back out. Works regardless of what the agent is doing. */
+export function withdrawInstructions({ owner, vault, mint, amount, decimals, programId = TOKEN_PROGRAM_ID }) {
+ const destination = ataFor(mint, owner, programId);
+ return [
+ createAssociatedTokenAccountIdempotentInstruction(
+ toPublicKey(owner, 'owner'),
+ destination,
+ toPublicKey(owner, 'owner'),
+ toPublicKey(mint, 'mint'),
+ programId,
+ ),
+ createTransferCheckedInstruction(
+ toPublicKey(vault, 'vault'),
+ toPublicKey(mint, 'mint'),
+ destination,
+ toPublicKey(owner, 'owner'),
+ amount,
+ decimals,
+ [],
+ programId,
+ ),
+ ];
+}
+
+/**
+ * The agent spends. It signs as DELEGATE over the owner's vault, so the token
+ * program checks the amount against delegated_amount and decrements it. The
+ * agent also pays the fee and any rent for a new destination account, which is
+ * the only reason it needs SOL of its own.
+ */
+export function delegatedTransferInstructions({
+ vault,
+ mint,
+ recipientOwner,
+ agent,
+ amount,
+ decimals,
+ programId = TOKEN_PROGRAM_ID,
+}) {
+ const destination = ataFor(mint, recipientOwner, programId);
+ return {
+ destination,
+ instructions: [
+ createAssociatedTokenAccountIdempotentInstruction(
+ toPublicKey(agent, 'agent'),
+ destination,
+ toPublicKey(recipientOwner, 'recipient'),
+ toPublicKey(mint, 'mint'),
+ programId,
+ ),
+ createTransferCheckedInstruction(
+ toPublicKey(vault, 'vault'),
+ toPublicKey(mint, 'mint'),
+ destination,
+ toPublicKey(agent, 'agent'),
+ amount,
+ decimals,
+ [],
+ programId,
+ ),
+ ],
+ };
+}
+
+/** Live vault state straight from the chain. The on-chain numbers, not our notes. */
+export async function readVault({ connection, vault, programId = TOKEN_PROGRAM_ID }) {
+ const account = await tokenAccount(connection, vault, programId);
+ if (!account) {
+ return { exists: false, address: String(vault), balance: 0n, delegate: null, delegatedAmount: 0n };
+ }
+ return {
+ exists: true,
+ address: String(vault),
+ mint: account.mint.toBase58(),
+ owner: account.owner.toBase58(),
+ balance: account.amount,
+ delegate: account.delegate ? account.delegate.toBase58() : null,
+ delegatedAmount: account.delegate ? account.delegatedAmount : 0n,
+ frozen: account.isFrozen,
+ };
+}
+
+/** What the agent can still move: the lower of its remaining allowance and the vault balance. */
+export function spendableUnits(vaultState) {
+ if (!vaultState.exists || !vaultState.delegate) return 0n;
+ return vaultState.delegatedAmount < vaultState.balance ? vaultState.delegatedAmount : vaultState.balance;
+}
diff --git a/packages/onchain-agent-wallets/src/lib/x402.js b/packages/onchain-agent-wallets/src/lib/x402.js
new file mode 100644
index 000000000..a884860b7
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/lib/x402.js
@@ -0,0 +1,171 @@
+// x402 over Solana.
+//
+// The agent pays HTTP 402 responses out of its allowance. Two details make
+// this custody-safe rather than a hole in it:
+//
+// 1. The resource is probed FIRST, unpaid, so the price is known before any
+// money moves and the guardrails see the real number.
+// 2. The agent's own token account is topped up just in time, for exactly the
+// shortfall, by a delegated pull from the owner's vault. The agent never
+// sits on a balance, and every unit it spends came out of the ceiling the
+// token program is enforcing.
+//
+// Step 2 exists because the x402 exact scheme has the payer sign a transfer
+// from an account it owns. A delegation cannot be handed to a third-party
+// facilitator, so the agent's account acts as a till: filled per payment,
+// emptied by the payment.
+
+import { x402Client } from '@x402/core/client';
+import { ExactSvmScheme } from '@x402/svm';
+import { wrapFetchWithPayment, decodePaymentResponseHeader } from '@x402/fetch';
+import { createKeyPairSignerFromBytes } from '@solana/kit';
+
+import { HTTP_TIMEOUT_MS, USER_AGENT, rpcFor } from '../config.js';
+
+/** Send the request without paying, to learn the price. */
+export async function probeResource({ url, method = 'GET', headers = {}, body }) {
+ const response = await fetch(url, {
+ method,
+ headers: { accept: 'application/json', 'user-agent': USER_AGENT, ...headers },
+ body,
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
+ });
+
+ if (response.status !== 402) {
+ return { paid: false, status: response.status, response };
+ }
+
+ let parsed;
+ try {
+ parsed = await response.clone().json();
+ } catch {
+ throw Object.assign(
+ new Error(`${url} returned 402 but its body is not valid x402 JSON, so the price cannot be verified`),
+ { code: 'bad_402_body' },
+ );
+ }
+ const accepts = Array.isArray(parsed?.accepts) ? parsed.accepts : [];
+ if (accepts.length === 0) {
+ throw Object.assign(new Error(`${url} returned 402 with no payment options in "accepts"`), { code: 'bad_402_body' });
+ }
+ return { paid: false, status: 402, response, x402Version: parsed.x402Version ?? 2, accepts };
+}
+
+/** Which Solana cluster a CAIP-2-ish network id refers to. */
+export function clusterOf(network) {
+ const value = String(network || '').toLowerCase();
+ if (!value.startsWith('solana')) return null;
+ return value.includes('devnet') ? 'devnet' : 'mainnet';
+}
+
+/**
+ * Choose the payment option this agent can actually settle: the exact scheme,
+ * on our cluster, denominated in the mint the agent's allowance is in.
+ */
+export function selectRequirement({ accepts, mint, network }) {
+ const solana = accepts.filter((r) => clusterOf(r.network));
+ if (solana.length === 0) {
+ const offered = [...new Set(accepts.map((r) => r.network))].join(', ');
+ throw Object.assign(
+ new Error(
+ `this resource does not accept Solana payments (it offers: ${offered}). ` +
+ 'This agent wallet is Solana-native and will not pay on another chain.',
+ ),
+ { code: 'no_solana_option' },
+ );
+ }
+
+ const onCluster = solana.filter((r) => clusterOf(r.network) === network);
+ if (onCluster.length === 0) {
+ throw Object.assign(
+ new Error(
+ `the resource wants payment on Solana ${clusterOf(solana[0].network)} but this wallet is configured for ` +
+ `${network}. Refusing rather than paying on the wrong cluster.`,
+ ),
+ { code: 'wrong_cluster' },
+ );
+ }
+
+ const exact = onCluster.filter((r) => (r.scheme || 'exact') === 'exact');
+ if (exact.length === 0) {
+ throw Object.assign(
+ new Error(`the resource only offers the "${onCluster[0].scheme}" scheme, which this wallet does not implement`),
+ { code: 'unsupported_scheme' },
+ );
+ }
+
+ const matching = exact.find((r) => r.asset === mint);
+ if (!matching) {
+ const assets = [...new Set(exact.map((r) => r.asset))].join(', ');
+ throw Object.assign(
+ new Error(
+ `the resource wants payment in ${assets}, but this agent's allowance is denominated in ${mint}. ` +
+ 'Create an agent wallet for that mint, or ask the resource for a price in this one.',
+ ),
+ { code: 'asset_mismatch' },
+ );
+ }
+ return matching;
+}
+
+/** The price of a requirement, in base units. */
+export function requiredUnits(requirement) {
+ const raw = requirement.maxAmountRequired ?? requirement.amount;
+ if (raw === undefined || raw === null || raw === '') {
+ throw Object.assign(new Error('the payment requirement carries no amount'), { code: 'bad_402_body' });
+ }
+ let units;
+ try {
+ units = BigInt(String(raw));
+ } catch {
+ throw Object.assign(new Error(`the payment requirement amount "${raw}" is not an integer of base units`), {
+ code: 'bad_402_body',
+ });
+ }
+ if (units <= 0n) {
+ throw Object.assign(new Error('the payment requirement amount must be positive'), { code: 'bad_402_body' });
+ }
+ return units;
+}
+
+/**
+ * Pay and fetch. The agent's keypair signs the payment transfer; the facilitator
+ * pays the Solana fee and settles it.
+ */
+export async function payAndFetch({ url, method = 'GET', headers = {}, body, secretKey, network, requirement }) {
+ const signer = await createKeyPairSignerFromBytes(secretKey);
+ const client = new x402Client().register(requirement.network, new ExactSvmScheme(signer, { rpcUrl: rpcFor(network) }));
+ const paidFetch = wrapFetchWithPayment(fetch, client);
+
+ const response = await paidFetch(url, {
+ method,
+ headers: { accept: 'application/json', 'user-agent': USER_AGENT, ...headers },
+ body,
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
+ });
+
+ let settlement = null;
+ const header = response.headers.get('x-payment-response');
+ if (header) {
+ try {
+ settlement = decodePaymentResponseHeader(header);
+ } catch {
+ settlement = { raw: header };
+ }
+ }
+ return { response, settlement };
+}
+
+/** Read a response body once, as JSON when it is JSON, as text otherwise. */
+export async function readBody(response, maxChars = 20_000) {
+ const type = response.headers.get('content-type') || '';
+ if (type.includes('application/json')) {
+ try {
+ return { json: await response.json() };
+ } catch {
+ return { text: '(the server declared JSON but sent something else)' };
+ }
+ }
+ const text = await response.text();
+ return { text: text.length > maxChars ? `${text.slice(0, maxChars)}\n[truncated]` : text };
+}
diff --git a/packages/onchain-agent-wallets/src/tools/agent-pay.js b/packages/onchain-agent-wallets/src/tools/agent-pay.js
new file mode 100644
index 000000000..1b327f42a
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/agent-pay.js
@@ -0,0 +1,117 @@
+// `agent_pay`: the agent moves money.
+//
+// The agent signs as delegate over the owner's vault, so the token program
+// checks the amount against the delegated ceiling and decrements it. The agent
+// pays the fee from its own SOL. Nothing here can exceed what the owner
+// approved on-chain, and the guardrails narrow it further.
+
+import { z } from 'zod';
+
+import { NETWORK, REQUIRE_CONFIRM } from '../config.js';
+import { solBalance, toPublicKey, accountLink, LAMPORTS_PER_SOL, MIN_AGENT_FEE_LAMPORTS } from '../lib/solana.js';
+import { delegatedTransferInstructions } from '../lib/vault.js';
+import { agentContext, authorizeSpend, assertDelegated, logSpend } from '../lib/agent.js';
+import { agentAction, summarize } from '../lib/execute.js';
+
+export const def = {
+ name: 'agent_pay',
+ title: 'Let the agent send tokens inside its limits',
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Send tokens from the agent vault to a recipient, signed by the agent as the on-chain delegate. Every ' +
+ 'guardrail is checked first (per-transaction cap, rolling daily cap, recipient allowlist, expiry, pause) and ' +
+ 'the SPL Token program enforces the remaining allowance underneath. A refusal explains which rule stopped it. ' +
+ 'Requires confirm:true to broadcast.',
+ inputSchema: {
+ id: z.string().describe('The agent wallet spending the money.'),
+ to: z.string().describe('Recipient wallet address. Their associated token account is created if needed.'),
+ amount: z.string().describe('Amount in whole tokens (e.g. "1.25").'),
+ memo: z.string().max(200).optional().describe('Note recorded in the local spend log.'),
+ confirm: z.boolean().optional().describe('Set true to broadcast.'),
+ },
+ async handler(args) {
+ const ctx = await agentContext(args.id);
+ const { record, connection, decimals, programId } = ctx;
+ const recipient = toPublicKey(args.to, 'to').toBase58();
+ const amount = ctx.units(args.amount);
+
+ assertDelegated(ctx);
+ const decision = authorizeSpend(ctx, {
+ amount,
+ recipient,
+ confirm: args.confirm === true,
+ kind: 'transfer',
+ });
+
+ const summary = summarize({
+ action: `"${record.id}" sends ${args.amount}`,
+ amount: args.amount,
+ asset: record.mint,
+ from: record.vault,
+ to: recipient,
+ network: NETWORK,
+ extra: {
+ signed_by: `the agent (${record.agent_pubkey}) as delegate`,
+ allowance_after: ctx.human(ctx.vault.delegatedAmount - amount),
+ vault_balance_after: ctx.human(ctx.vault.balance - amount),
+ guardrails_passed: decision.checks.filter((c) => c.ok).map((c) => c.check),
+ },
+ });
+
+ if (REQUIRE_CONFIRM && args.confirm !== true) {
+ return {
+ ok: false,
+ action: 'confirm_required',
+ summary,
+ message: 'Nothing has been signed or broadcast. Re-issue with confirm:true to send.',
+ };
+ }
+
+ const agentSol = await solBalance(connection, record.agent_pubkey);
+ if (agentSol * LAMPORTS_PER_SOL < MIN_AGENT_FEE_LAMPORTS) {
+ throw Object.assign(
+ new Error(
+ `the agent holds ${agentSol} SOL, too little to pay the transaction fee. ` +
+ 'Ask the owner to run fund_agent_wallet with sol:"0.02".',
+ ),
+ { code: 'no_fee_sol' },
+ );
+ }
+
+ const { destination, instructions } = delegatedTransferInstructions({
+ vault: record.vault,
+ mint: record.mint,
+ recipientOwner: recipient,
+ agent: record.agent_pubkey,
+ amount,
+ decimals,
+ programId,
+ });
+
+ const sent = await agentAction({ connection, keypair: ctx.keypair(), instructions, network: NETWORK });
+
+ const entry = logSpend(ctx, {
+ kind: 'transfer',
+ amount: args.amount,
+ base_units: String(amount),
+ recipient,
+ destination_token_account: destination.toBase58(),
+ memo: args.memo || null,
+ signature: sent.signature,
+ });
+
+ return {
+ ok: true,
+ action: 'sent',
+ summary,
+ ...sent,
+ recipient,
+ recipient_link: accountLink(recipient, NETWORK),
+ spent: args.amount,
+ allowance_remaining: ctx.human(ctx.vault.delegatedAmount - amount),
+ vault_balance: ctx.human(ctx.vault.balance - amount),
+ spent_24h: ctx.human(ctx.spentToday + amount),
+ logged_at: entry.at,
+ };
+ },
+};
diff --git a/packages/onchain-agent-wallets/src/tools/agent-wallet-status.js b/packages/onchain-agent-wallets/src/tools/agent-wallet-status.js
new file mode 100644
index 000000000..21acccb81
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/agent-wallet-status.js
@@ -0,0 +1,68 @@
+// `agent_wallet_status`: everything true about an agent right now, read from
+// the chain rather than from local notes.
+
+import { z } from 'zod';
+
+import { NETWORK } from '../config.js';
+import { solBalance, accountLink, fromBaseUnits, MIN_AGENT_FEE_LAMPORTS, LAMPORTS_PER_SOL } from '../lib/solana.js';
+import { agentContext, describeAgent } from '../lib/agent.js';
+import { spentInWindow } from '../lib/policy.js';
+
+export const def = {
+ name: 'agent_wallet_status',
+ title: 'Live status of an agent wallet',
+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Show an agent wallet as it actually stands on-chain: vault balance, how much of the delegated allowance is ' +
+ 'left, what it can spend right now, its fee SOL, the guardrails in force, spend totals for the last 24 hours, ' +
+ 'and any warnings (revoked, expired, paused, out of fee SOL, allowance unbacked by balance). Read-only.',
+ inputSchema: {
+ id: z.string().describe('The agent wallet.'),
+ },
+ async handler(args) {
+ const ctx = await agentContext(args.id);
+ const described = describeAgent(ctx);
+ const agentSol = await solBalance(ctx.connection, ctx.record.agent_pubkey);
+ const spent7d = spentInWindow(ctx.ledger, { hours: 24 * 7 });
+
+ const warnings = [];
+ if (!ctx.vault.exists) warnings.push('The vault does not exist on-chain yet. Run create_agent_wallet.');
+ if (ctx.vault.exists && !ctx.vault.delegate) warnings.push('Revoked: the agent has no on-chain spending authority.');
+ if (ctx.vault.delegate && ctx.vault.delegate !== ctx.record.agent_pubkey) {
+ warnings.push(`The vault is delegated to ${ctx.vault.delegate}, which is not this agent.`);
+ }
+ if (ctx.policy.paused) warnings.push('Paused by the owner: this server refuses every spend.');
+ if (ctx.policy.expires_at && new Date(ctx.policy.expires_at) <= new Date()) {
+ warnings.push(`The delegation expired at ${ctx.policy.expires_at}.`);
+ }
+ if (agentSol * LAMPORTS_PER_SOL < MIN_AGENT_FEE_LAMPORTS) {
+ warnings.push(
+ `The agent holds ${agentSol} SOL, too little to pay transaction fees. Run fund_agent_wallet with sol:"0.02".`,
+ );
+ }
+ if (ctx.vault.exists && ctx.vault.delegatedAmount > ctx.vault.balance) {
+ warnings.push(
+ `The allowance (${ctx.human(ctx.vault.delegatedAmount)}) is larger than the vault balance ` +
+ `(${ctx.human(ctx.vault.balance)}), so only ${ctx.human(ctx.spendable)} is actually spendable.`,
+ );
+ }
+ if (ctx.vault.frozen) warnings.push('The vault token account is frozen by the mint authority.');
+
+ return {
+ ok: true,
+ ...described,
+ fee_sol: agentSol,
+ spent_7d: fromBaseUnits(spent7d, ctx.decimals),
+ spends_recorded: ctx.ledger.length,
+ links: {
+ vault: accountLink(ctx.record.vault, NETWORK),
+ agent: accountLink(ctx.record.agent_pubkey, NETWORK),
+ owner: accountLink(ctx.record.owner, NETWORK),
+ },
+ warnings,
+ custody:
+ `The vault is owned by ${ctx.record.owner}. The agent holds a delegation capped at ` +
+ `${ctx.human(ctx.vault.exists ? ctx.vault.delegatedAmount : 0n)} and can be revoked in one instruction.`,
+ };
+ },
+};
diff --git a/packages/onchain-agent-wallets/src/tools/approve-agent-allowance.js b/packages/onchain-agent-wallets/src/tools/approve-agent-allowance.js
new file mode 100644
index 000000000..58ecd9959
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/approve-agent-allowance.js
@@ -0,0 +1,79 @@
+// `approve_agent_allowance`: change the on-chain ceiling.
+//
+// SPL approve REPLACES the previous delegation rather than adding to it, so the
+// number passed here becomes the agent's entire remaining allowance. That is
+// also how you top an agent back up after it has spent down to zero.
+
+import { z } from 'zod';
+
+import { NETWORK } from '../config.js';
+import { toBaseUnits, fromBaseUnits } from '../lib/solana.js';
+import { approveInstruction } from '../lib/vault.js';
+import { agentContext, describeAgent } from '../lib/agent.js';
+import { ownerAction, summarize } from '../lib/execute.js';
+
+export const def = {
+ name: 'approve_agent_allowance',
+ title: "Set the agent's on-chain spending ceiling",
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
+ description:
+ 'Set how much the agent may spend from the vault, enforced by the SPL Token program. This REPLACES the ' +
+ 'existing allowance, it does not add to it: passing "50" leaves the agent with exactly 50 regardless of what ' +
+ 'it had before. Use it to raise, lower, or refill an allowance. Requires confirm:true to broadcast.',
+ inputSchema: {
+ id: z.string().describe('The agent wallet.'),
+ allowance: z.string().describe('The new total allowance in whole tokens. "0" is equivalent to a revoke.'),
+ secret: z.string().optional().describe('Owner secret key for this call only.'),
+ confirm: z.boolean().optional().describe('Set true to broadcast.'),
+ },
+ async handler(args) {
+ const ctx = await agentContext(args.id);
+ const { record, connection, decimals, programId } = ctx;
+
+ if (!ctx.vault.exists) {
+ throw Object.assign(new Error(`the vault for "${record.id}" does not exist yet. Run create_agent_wallet.`), {
+ code: 'no_vault',
+ });
+ }
+
+ const units = toBaseUnits(args.allowance, decimals);
+ const instructions = [
+ approveInstruction({
+ vault: record.vault,
+ mint: record.mint,
+ delegate: record.agent_pubkey,
+ owner: record.owner,
+ allowance: units,
+ decimals,
+ programId,
+ }),
+ ];
+
+ const summary = summarize({
+ action: `Set the "${record.id}" allowance to ${fromBaseUnits(units, decimals)}`,
+ network: NETWORK,
+ extra: {
+ agent_address: record.agent_pubkey,
+ vault: record.vault,
+ mint: record.mint,
+ previous_allowance: ctx.human(ctx.vault.delegatedAmount),
+ new_allowance: fromBaseUnits(units, decimals),
+ vault_balance: ctx.human(ctx.vault.balance),
+ note: 'Approve replaces the previous allowance rather than adding to it.',
+ },
+ });
+
+ const result = await ownerAction({
+ connection,
+ owner: record.owner,
+ instructions,
+ confirm: args.confirm === true,
+ secret: args.secret,
+ summary,
+ network: NETWORK,
+ note: `approve allowance for "${record.id}"`,
+ });
+
+ return { ...result, agent: describeAgent(ctx) };
+ },
+};
diff --git a/packages/onchain-agent-wallets/src/tools/create-agent-wallet.js b/packages/onchain-agent-wallets/src/tools/create-agent-wallet.js
new file mode 100644
index 000000000..140f1f1f0
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/create-agent-wallet.js
@@ -0,0 +1,204 @@
+// `create_agent_wallet`: the whole custody setup in one call.
+//
+// Generates the agent's keypair, derives its vault from the owner's address,
+// creates the vault, and delegates a capped allowance to the agent. The owner
+// signs once. After this the agent can spend up to the allowance and not one
+// unit more, and the owner can take it all back at any time.
+
+import { z } from 'zod';
+import { Keypair, SystemProgram, LAMPORTS_PER_SOL } from '@solana/web3.js';
+import bs58 from 'bs58';
+
+import { NETWORK } from '../config.js';
+import { connectionFor, mintDecimals, tokenProgramFor, toBaseUnits, fromBaseUnits, USDC_MINT, toPublicKey, accountLink } from '../lib/solana.js';
+import { assertAgentId, createVaultInstructions, vaultAddress, readVault } from '../lib/vault.js';
+import { normalizePolicy } from '../lib/policy.js';
+import { readState, updateState } from '../lib/store.js';
+import { ownerAction, resolveOwner, summarize } from '../lib/execute.js';
+
+export const def = {
+ name: 'create_agent_wallet',
+ title: 'Give an agent a wallet with an on-chain spending limit',
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Create an agent wallet on Solana. Generates a fresh keypair for the agent, creates a vault token account ' +
+ 'that YOU own (derived deterministically from your address plus the agent id), and delegates a capped ' +
+ 'allowance over it to the agent. The SPL Token program enforces that cap: the agent cannot spend past it, ' +
+ 'and every spend decrements it. You keep custody, you can revoke in one instruction, and you can withdraw ' +
+ 'the balance without the agent. Set guardrails (per_tx, daily, allowlists, expiry) in the same call. ' +
+ 'Signs with OWNER_SECRET_KEY if configured, otherwise returns an unsigned transaction for Phantom, ' +
+ 'Solflare, Backpack, or a Ledger. Requires confirm:true to broadcast.',
+ inputSchema: {
+ id: z
+ .string()
+ .min(1)
+ .max(27)
+ .describe('Short slug naming the agent, lowercase letters/digits/hyphens. Becomes the on-chain vault seed.'),
+ allowance: z
+ .string()
+ .describe('The on-chain ceiling, in whole tokens (e.g. "100"). The agent can never spend more than this without a new approval.'),
+ label: z.string().max(120).optional().describe('Human-readable name for your own reference.'),
+ owner: z
+ .string()
+ .optional()
+ .describe('Your wallet address. Omit to use the configured OWNER_SECRET_KEY. Pass it to keep the key off this machine and sign in your wallet.'),
+ mint: z.string().optional().describe(`SPL mint to spend. Defaults to USDC (${USDC_MINT.mainnet} on mainnet).`),
+ fee_sol: z
+ .string()
+ .optional()
+ .describe('SOL to send the agent so it can pay its own transaction fees. Default "0.02". This is the only value the agent itself holds.'),
+ per_tx: z.string().optional().describe('Guardrail: maximum single spend, in tokens.'),
+ daily: z.string().optional().describe('Guardrail: maximum spend per rolling 24 hours, in tokens.'),
+ confirm_over: z.string().optional().describe('Guardrail: spends above this amount need an explicit confirm:true from a human.'),
+ allow_recipients: z.array(z.string()).optional().describe('Guardrail: only these addresses may receive funds. Empty means unrestricted.'),
+ allow_hosts: z.array(z.string()).optional().describe('Guardrail: only these hosts may be paid over x402. Subdomains included. Empty means unrestricted.'),
+ expires_at: z.string().optional().describe('Guardrail: ISO timestamp after which every spend is refused.'),
+ agent_secret: z.string().optional().describe('Reuse an existing agent keypair (base58 or JSON array) instead of generating one.'),
+ secret: z.string().optional().describe('Owner secret key for this call only, overriding OWNER_SECRET_KEY.'),
+ confirm: z.boolean().optional().describe('Set true to actually build and broadcast. Without it you get the summary only.'),
+ },
+ async handler(args) {
+ const id = assertAgentId(args.id);
+ const owner = resolveOwner({ owner: args.owner, secret: args.secret });
+ const connection = connectionFor(NETWORK);
+ const mint = args.mint ? toPublicKey(args.mint, 'mint').toBase58() : USDC_MINT[NETWORK];
+ const programId = await tokenProgramFor(connection, mint);
+ const decimals = await mintDecimals(connection, mint, programId);
+
+ const existing = readState().agents[id];
+ if (existing && existing.owner !== owner) {
+ throw Object.assign(
+ new Error(`agent "${id}" already exists under owner ${existing.owner}. Pick a different id.`),
+ { code: 'agent_exists' },
+ );
+ }
+
+ const vault = (await vaultAddress(owner, id, programId)).toBase58();
+ const onchain = await readVault({ connection, vault, programId });
+ if (onchain.exists) {
+ throw Object.assign(
+ new Error(
+ `the vault for "${id}" already exists at ${vault}. Use approve_agent_allowance to change its ceiling, ` +
+ 'or fund_agent_wallet to top it up.',
+ ),
+ { code: 'vault_exists' },
+ );
+ }
+
+ // The delegate pubkey is baked into the approval, so the keypair must be
+ // stable between the preview call and the confirmed one. Generate and
+ // persist it now; this touches no chain and moves no funds.
+ const keypair = args.agent_secret
+ ? Keypair.fromSecretKey(
+ args.agent_secret.trim().startsWith('[')
+ ? Uint8Array.from(JSON.parse(args.agent_secret))
+ : bs58.decode(args.agent_secret.trim()),
+ )
+ : existing?.agent_secret
+ ? Keypair.fromSecretKey(bs58.decode(existing.agent_secret))
+ : Keypair.generate();
+ const agentPubkey = keypair.publicKey.toBase58();
+
+ const policy = normalizePolicy({
+ per_tx: args.per_tx,
+ daily: args.daily,
+ confirm_over: args.confirm_over,
+ allow_recipients: args.allow_recipients,
+ allow_hosts: args.allow_hosts,
+ expires_at: args.expires_at,
+ });
+
+ const allowanceUnits = toBaseUnits(args.allowance, decimals);
+ if (allowanceUnits <= 0n) {
+ throw Object.assign(new Error('allowance must be greater than zero'), { code: 'bad_amount' });
+ }
+ const feeSol = args.fee_sol === undefined ? '0.02' : String(args.fee_sol);
+ const feeLamports = BigInt(toBaseUnits(feeSol, 9));
+
+ updateState((state) => {
+ state.agents[id] = {
+ id,
+ label: args.label || null,
+ network: NETWORK,
+ owner,
+ agent_pubkey: agentPubkey,
+ agent_secret: bs58.encode(keypair.secretKey),
+ mint,
+ vault,
+ seed: `oaw1:${id}`,
+ policy,
+ created_at: existing?.created_at || new Date().toISOString(),
+ deployment: existing?.deployment || null,
+ };
+ });
+
+ const { instructions, rentLamports } = await createVaultInstructions({
+ connection,
+ owner,
+ agentId: id,
+ mint,
+ delegate: agentPubkey,
+ allowance: allowanceUnits,
+ decimals,
+ programId,
+ });
+ if (feeLamports > 0n) {
+ instructions.push(
+ SystemProgram.transfer({
+ fromPubkey: toPublicKey(owner, 'owner'),
+ toPubkey: keypair.publicKey,
+ lamports: Number(feeLamports),
+ }),
+ );
+ }
+
+ const summary = summarize({
+ action: `Create the "${id}" agent wallet and delegate ${args.allowance} to it`,
+ network: NETWORK,
+ extra: {
+ owner,
+ agent_address: agentPubkey,
+ vault,
+ asset: mint === USDC_MINT[NETWORK] ? 'USDC' : mint,
+ allowance: `${fromBaseUnits(allowanceUnits, decimals)} (the on-chain ceiling)`,
+ sol_to_agent: `${feeSol} SOL for the agent's own transaction fees`,
+ rent: `${fromBaseUnits(BigInt(rentLamports), 9)} SOL, recoverable when you close the vault`,
+ guardrails: policy,
+ custody: 'The vault is owned by you. The agent is only a delegate, capped at the allowance.',
+ },
+ });
+
+ const result = await ownerAction({
+ connection,
+ owner,
+ instructions,
+ confirm: args.confirm === true,
+ secret: args.secret,
+ summary,
+ network: NETWORK,
+ note: `create agent wallet "${id}"`,
+ });
+
+ return {
+ ...result,
+ agent: {
+ id,
+ agent_address: agentPubkey,
+ vault,
+ vault_link: accountLink(vault, NETWORK),
+ mint,
+ allowance: fromBaseUnits(allowanceUnits, decimals),
+ policy,
+ },
+ next_steps:
+ result.action === 'confirm_required'
+ ? ['Re-issue with confirm:true to create the wallet.']
+ : [
+ 'fund_agent_wallet: move tokens into the vault so the allowance is actually backed.',
+ 'agent_wallet_status: see live balances, the remaining allowance, and the guardrails.',
+ 'pay_x402 / agent_pay: let the agent spend inside its limits.',
+ 'revoke_agent_wallet: kill the delegation instantly, any time.',
+ ],
+ };
+ },
+};
diff --git a/packages/onchain-agent-wallets/src/tools/deploy-agent-onchain.js b/packages/onchain-agent-wallets/src/tools/deploy-agent-onchain.js
new file mode 100644
index 000000000..4dfea056c
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/deploy-agent-onchain.js
@@ -0,0 +1,152 @@
+// `deploy_agent_onchain`: publish the agent's identity where other agents can
+// find it, with its payment address attached.
+//
+// A wallet nobody can discover cannot be paid. This mints a Metaplex Core asset
+// carrying the agent's EIP-8004 registration document, flags x402 support, and
+// writes the agent's payment address, vault, and asset mint into the on-chain
+// Attributes plugin, so a counterparty can read where to pay this agent
+// straight off the chain.
+//
+// The mint itself is the sibling package's job (@three-ws/metaplex-agent-mcp),
+// reused as a library rather than reimplemented.
+
+import { z } from 'zod';
+
+import {
+ buildUmi,
+ buildAgentMint,
+ sendAgentMint,
+ agentLinks,
+ txLink,
+ toBase58Signature,
+} from '@three-ws/metaplex-agent-mcp/lib';
+
+import { NETWORK, REQUIRE_CONFIRM, OWNER_SECRET } from '../config.js';
+import { agentContext } from '../lib/agent.js';
+import { updateState } from '../lib/store.js';
+import { summarize } from '../lib/execute.js';
+
+export const def = {
+ name: 'deploy_agent_onchain',
+ title: 'Publish the agent on-chain with its payment address',
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Mint the agent an on-chain identity in the Metaplex Agent Registry on Solana, carrying its EIP-8004 ' +
+ 'registration document, an x402Support flag, and on-chain attributes naming its payment address, its vault, ' +
+ 'and the token it accepts. After this the agent is discoverable on metaplex.com/agents and any counterparty ' +
+ 'can read where to pay it. Costs about 0.007 SOL and needs an owner signing key (set OWNER_SECRET_KEY or pass ' +
+ '`secret`); to mint from Phantom or a Ledger instead, use prepare_agent_mint in @three-ws/metaplex-agent-mcp. ' +
+ 'Requires confirm:true to broadcast.',
+ inputSchema: {
+ id: z.string().describe('The agent wallet to publish.'),
+ name: z.string().max(32).optional().describe('On-chain name. Defaults to the agent label or id.'),
+ description: z.string().max(500).optional().describe('What this agent does.'),
+ image: z.string().url().optional().describe('Image URL for the asset.'),
+ model_url: z.string().url().optional().describe('GLB avatar URL, rendered on metaplex.com/agents.'),
+ services: z
+ .array(z.object({ name: z.string(), endpoint: z.string() }))
+ .optional()
+ .describe('Endpoints this agent serves, e.g. its own x402 API.'),
+ secret: z.string().optional().describe('Owner secret key for this call only.'),
+ confirm: z.boolean().optional().describe('Set true to broadcast.'),
+ },
+ async handler(args) {
+ const ctx = await agentContext(args.id);
+ const { record } = ctx;
+
+ if (record.deployment?.asset) {
+ throw Object.assign(
+ new Error(
+ `"${record.id}" is already deployed as ${record.deployment.asset}. ` +
+ 'Use the Metaplex registry tools to update its identity document.',
+ ),
+ { code: 'already_deployed' },
+ );
+ }
+
+ const secret = args.secret || OWNER_SECRET;
+ if (!secret) {
+ throw Object.assign(
+ new Error(
+ 'deploying mints an asset, which needs a signing key. Set OWNER_SECRET_KEY, pass `secret`, or mint ' +
+ 'from your browser wallet with prepare_agent_mint in @three-ws/metaplex-agent-mcp.',
+ ),
+ { code: 'no_signer' },
+ );
+ }
+
+ const name = args.name || record.label || record.id;
+ const attributes = [
+ { key: 'agent_wallet', value: record.agent_pubkey },
+ { key: 'payment_vault', value: record.vault },
+ { key: 'payment_mint', value: record.mint },
+ { key: 'payment_network', value: `solana:${NETWORK}` },
+ { key: 'custody', value: 'delegated:spl-token-approve' },
+ ];
+
+ const summary = summarize({
+ action: `Publish "${record.id}" to the Metaplex Agent Registry`,
+ network: NETWORK,
+ extra: {
+ name,
+ agent_wallet: record.agent_pubkey,
+ vault: record.vault,
+ accepts: record.mint,
+ x402: true,
+ estimated_cost: '~0.007 SOL (rent and fees)',
+ attributes,
+ },
+ });
+
+ if (REQUIRE_CONFIRM && args.confirm !== true) {
+ return {
+ ok: false,
+ action: 'confirm_required',
+ summary,
+ message: 'Nothing has been minted. Re-issue with confirm:true to publish.',
+ };
+ }
+
+ const umi = buildUmi({ network: NETWORK, secret, requireSigner: true });
+ const creator = umi.identity.publicKey.toString();
+ const mint = buildAgentMint(umi, {
+ network: NETWORK,
+ creator,
+ name,
+ description: args.description || `Agent wallet with an on-chain spending allowance. Pays with x402 on Solana.`,
+ image: args.image,
+ modelUrl: args.model_url,
+ services: args.services,
+ x402Support: true,
+ attributes,
+ metadataAttributes: attributes,
+ });
+
+ const asset = mint.assetSigner.publicKey.toString();
+ const sent = await sendAgentMint(umi, mint, { toBase58Signature });
+
+ const deployment = {
+ asset,
+ signatures: sent.signatures,
+ atomic: sent.atomic,
+ registry: 'metaplex-agent-registry',
+ deployed_at: new Date().toISOString(),
+ };
+ updateState((state) => {
+ state.agents[record.id].deployment = deployment;
+ });
+
+ return {
+ ok: true,
+ action: 'deployed',
+ summary,
+ agent: record.id,
+ asset,
+ signatures: sent.signatures.map((sig) => ({ signature: sig, link: txLink(sig, NETWORK) })),
+ links: agentLinks(asset, NETWORK),
+ registration: mint.registration,
+ attributes,
+ message: `"${record.id}" is live on-chain. Its payment address is published in the asset attributes.`,
+ };
+ },
+};
diff --git a/packages/onchain-agent-wallets/src/tools/export-agent-runtime.js b/packages/onchain-agent-wallets/src/tools/export-agent-runtime.js
new file mode 100644
index 000000000..f5f888539
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/export-agent-runtime.js
@@ -0,0 +1,85 @@
+// `export_agent_runtime`: hand the agent everything it needs to run somewhere
+// else, and nothing it does not.
+//
+// By default the export is safe to paste anywhere: addresses, limits, and the
+// MCP client config, with no key material. Ask for the key explicitly and you
+// get it, with the blast radius spelled out.
+
+import { z } from 'zod';
+
+import { NETWORK, STATE_DIR } from '../config.js';
+import { accountLink } from '../lib/solana.js';
+import { agentContext, describeAgent } from '../lib/agent.js';
+
+export const def = {
+ name: 'export_agent_runtime',
+ title: 'Export an agent wallet as a runnable MCP config',
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
+ description:
+ 'Produce the config that puts this agent wallet in front of a model: an mcp.json block, the equivalent ' +
+ 'claude mcp add command, the agent identity card (payment address, vault, token, limits), and the x402 ' +
+ 'details a counterparty needs to bill it. By default no key material is included, so the output is safe to ' +
+ 'paste into a repo or a ticket. Pass include_secret:true only when moving the agent to another machine.',
+ inputSchema: {
+ id: z.string().describe('The agent wallet to export.'),
+ include_secret: z
+ .boolean()
+ .optional()
+ .describe("Include the agent's secret key. Anyone holding it can spend up to the allowance. Default false."),
+ },
+ async handler(args) {
+ const ctx = await agentContext(args.id);
+ const described = describeAgent(ctx);
+ const { record } = ctx;
+
+ const env = {
+ OAW_NETWORK: NETWORK,
+ OAW_STATE_DIR: STATE_DIR,
+ };
+ if (args.include_secret === true) env.OAW_AGENT_SECRET = record.agent_secret;
+
+ const mcpConfig = {
+ mcpServers: {
+ 'onchain-agent-wallets': {
+ command: 'npx',
+ args: ['-y', '@three-ws/onchain-agent-wallets'],
+ env,
+ },
+ },
+ };
+
+ const cliArgs = Object.entries(env)
+ .map(([k, v]) => `-e ${k}=${v}`)
+ .join(' ');
+
+ return {
+ ok: true,
+ agent: described,
+ identity_card: {
+ agent: record.id,
+ pay_to: record.agent_pubkey,
+ accepts: record.mint,
+ network: `solana:${NETWORK}`,
+ x402: true,
+ vault: record.vault,
+ vault_link: accountLink(record.vault, NETWORK),
+ spending_limit: described.allowance_remaining,
+ custody: 'The owner holds the funds. This agent spends against a revocable on-chain delegation.',
+ onchain_identity: record.deployment?.asset || null,
+ },
+ mcp_json: mcpConfig,
+ claude_code: `claude mcp add onchain-agent-wallets ${cliArgs} -- npx -y @three-ws/onchain-agent-wallets`,
+ secret_included: args.include_secret === true,
+ ...(args.include_secret === true
+ ? {
+ warning:
+ 'This output contains the agent secret key. Anyone holding it can spend up to the remaining ' +
+ `allowance (${described.allowance_remaining}). It cannot touch the rest of the owner's funds, and ` +
+ 'revoke_agent_wallet cancels it instantly.',
+ }
+ : {
+ note: 'No key material included. The agent can only spend from the machine that holds its keypair.',
+ }),
+ };
+ },
+};
diff --git a/packages/onchain-agent-wallets/src/tools/fund-agent-wallet.js b/packages/onchain-agent-wallets/src/tools/fund-agent-wallet.js
new file mode 100644
index 000000000..85c59a805
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/fund-agent-wallet.js
@@ -0,0 +1,107 @@
+// `fund_agent_wallet`: move tokens into the vault and SOL to the agent for fees.
+//
+// The allowance is a ceiling, not a balance. An agent with a 100 allowance and
+// an empty vault can spend nothing. This is what backs it.
+
+import { z } from 'zod';
+import { SystemProgram } from '@solana/web3.js';
+
+import { NETWORK } from '../config.js';
+import { connectionFor, toBaseUnits, fromBaseUnits, toPublicKey, ataFor, tokenAccount, solBalance } from '../lib/solana.js';
+import { depositInstructions } from '../lib/vault.js';
+import { agentContext, describeAgent } from '../lib/agent.js';
+import { ownerAction, summarize } from '../lib/execute.js';
+
+export const def = {
+ name: 'fund_agent_wallet',
+ title: "Top up an agent's vault, and its fee SOL",
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Move tokens from your wallet into the agent vault, and optionally send the agent a little SOL for its own ' +
+ 'transaction fees. The vault stays owned by you; funding it does not raise the delegated allowance, so the ' +
+ 'agent still cannot spend past its ceiling. Requires confirm:true to broadcast.',
+ inputSchema: {
+ id: z.string().describe('The agent wallet to fund.'),
+ amount: z.string().optional().describe('Tokens to move into the vault, in whole units (e.g. "50").'),
+ sol: z.string().optional().describe('SOL to send the agent for transaction fees (e.g. "0.02").'),
+ secret: z.string().optional().describe('Owner secret key for this call only.'),
+ confirm: z.boolean().optional().describe('Set true to broadcast.'),
+ },
+ async handler(args) {
+ const ctx = await agentContext(args.id);
+ const { record, connection, decimals, programId } = ctx;
+ const owner = record.owner;
+
+ if (!args.amount && !args.sol) {
+ throw Object.assign(new Error('pass `amount` (tokens for the vault), `sol` (fees for the agent), or both'), {
+ code: 'validation_error',
+ });
+ }
+
+ const instructions = [];
+ const summaryExtra = { agent: record.id, vault: record.vault, agent_address: record.agent_pubkey };
+
+ if (args.amount) {
+ const units = toBaseUnits(args.amount, decimals);
+ if (units <= 0n) throw Object.assign(new Error('amount must be greater than zero'), { code: 'bad_amount' });
+
+ const source = ataFor(record.mint, owner, programId);
+ const sourceAccount = await tokenAccount(connection, source, programId);
+ if (!sourceAccount) {
+ throw Object.assign(
+ new Error(`your wallet has no token account for ${record.mint}. Acquire some of this token first.`),
+ { code: 'no_source_account' },
+ );
+ }
+ if (sourceAccount.amount < units) {
+ throw Object.assign(
+ new Error(
+ `your wallet holds ${fromBaseUnits(sourceAccount.amount, decimals)} but you are trying to move ${args.amount}.`,
+ ),
+ { code: 'insufficient_funds' },
+ );
+ }
+ instructions.push(
+ ...depositInstructions({ owner, vault: record.vault, mint: record.mint, amount: units, decimals, programId }),
+ );
+ summaryExtra.tokens_to_vault = `${fromBaseUnits(units, decimals)} (${record.mint})`;
+ summaryExtra.vault_balance_after = fromBaseUnits(ctx.vault.balance + units, decimals);
+ summaryExtra.allowance_remaining = ctx.human(ctx.vault.delegatedAmount);
+ }
+
+ if (args.sol) {
+ const lamports = toBaseUnits(args.sol, 9);
+ if (lamports <= 0n) throw Object.assign(new Error('sol must be greater than zero'), { code: 'bad_amount' });
+ instructions.push(
+ SystemProgram.transfer({
+ fromPubkey: toPublicKey(owner, 'owner'),
+ toPubkey: toPublicKey(record.agent_pubkey, 'agent'),
+ lamports: Number(lamports),
+ }),
+ );
+ const current = await solBalance(connection, record.agent_pubkey);
+ summaryExtra.sol_to_agent = `${args.sol} SOL (agent currently holds ${current})`;
+ }
+
+ const summary = summarize({
+ action: `Fund the "${record.id}" agent wallet`,
+ from: owner,
+ to: record.vault,
+ network: NETWORK,
+ extra: summaryExtra,
+ });
+
+ const result = await ownerAction({
+ connection,
+ owner,
+ instructions,
+ confirm: args.confirm === true,
+ secret: args.secret,
+ summary,
+ network: NETWORK,
+ note: `fund agent wallet "${record.id}"`,
+ });
+
+ return { ...result, agent: describeAgent(ctx) };
+ },
+};
diff --git a/packages/onchain-agent-wallets/src/tools/list-agent-wallets.js b/packages/onchain-agent-wallets/src/tools/list-agent-wallets.js
new file mode 100644
index 000000000..bcf744406
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/list-agent-wallets.js
@@ -0,0 +1,40 @@
+// `list_agent_wallets`: every agent this owner has on this network, with live
+// balances. One RPC round per agent, so it stays honest rather than fast.
+
+import { z } from 'zod';
+
+import { NETWORK } from '../config.js';
+import { listAgents } from '../lib/store.js';
+import { agentContext, describeAgent } from '../lib/agent.js';
+
+export const def = {
+ name: 'list_agent_wallets',
+ title: 'Every agent wallet on this machine',
+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },
+ description:
+ 'List the agent wallets configured here, each with its live vault balance, remaining on-chain allowance, and ' +
+ 'guardrails. Read-only.',
+ inputSchema: {
+ owner: z.string().optional().describe('Only agents belonging to this owner address.'),
+ },
+ async handler(args) {
+ const records = listAgents().filter((r) => !args.owner || r.owner === args.owner);
+ const agents = [];
+ for (const record of records) {
+ try {
+ agents.push(describeAgent(await agentContext(record.id)));
+ } catch (err) {
+ agents.push({ id: record.id, owner: record.owner, error: err.message, code: err.code || 'unreadable' });
+ }
+ }
+ return {
+ ok: true,
+ network: NETWORK,
+ count: agents.length,
+ agents,
+ ...(agents.length === 0
+ ? { empty: 'No agent wallets yet. Run create_agent_wallet to give an agent a spending allowance.' }
+ : {}),
+ };
+ },
+};
diff --git a/packages/onchain-agent-wallets/src/tools/pay-x402.js b/packages/onchain-agent-wallets/src/tools/pay-x402.js
new file mode 100644
index 000000000..16b383a99
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/pay-x402.js
@@ -0,0 +1,210 @@
+// `pay_x402`: the agent buys something.
+//
+// Probe the resource unpaid, show the price, run the guardrails, top the agent
+// up for exactly that price out of the owner's vault, pay, and return the
+// content. The owner's ceiling is enforced by the token program the whole way
+// through, and the agent is left holding nothing afterwards.
+
+import { z } from 'zod';
+
+import { NETWORK, REQUIRE_CONFIRM } from '../config.js';
+import {
+ solBalance,
+ ataFor,
+ tokenAccount,
+ fromBaseUnits,
+ LAMPORTS_PER_SOL,
+ MIN_AGENT_FEE_LAMPORTS,
+} from '../lib/solana.js';
+import { delegatedTransferInstructions } from '../lib/vault.js';
+import { agentContext, authorizeSpend, assertDelegated, logSpend } from '../lib/agent.js';
+import { agentAction, summarize } from '../lib/execute.js';
+import { probeResource, selectRequirement, requiredUnits, payAndFetch, readBody } from '../lib/x402.js';
+
+export const def = {
+ name: 'pay_x402',
+ title: 'Let the agent pay for an x402 API out of its allowance',
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Call an HTTP endpoint that charges with x402, paying from the agent allowance on Solana. The price is read ' +
+ 'from the unpaid 402 response first, so the guardrails (per-transaction cap, daily cap, host allowlist, ' +
+ 'expiry, pause) see the real amount before anything moves. The agent is topped up for exactly that amount ' +
+ 'from the vault, pays, and is left empty. If the endpoint is not charging, the content comes back with no ' +
+ 'payment at all. Requires confirm:true when the price is above the confirm threshold or confirmation is on.',
+ inputSchema: {
+ id: z.string().describe('The agent wallet paying.'),
+ url: z.string().url().describe('The resource to call.'),
+ method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).optional().describe('HTTP method. Default GET.'),
+ headers: z.record(z.string()).optional().describe('Extra request headers.'),
+ body: z.string().optional().describe('Request body, for POST/PUT/PATCH.'),
+ max_price: z.string().optional().describe('Refuse if the resource asks for more than this, in whole tokens. A ceiling for this call only.'),
+ confirm: z.boolean().optional().describe('Set true to authorize payment.'),
+ },
+ async handler(args) {
+ const ctx = await agentContext(args.id);
+ const { record, connection, decimals, programId } = ctx;
+ const method = args.method || 'GET';
+ const host = new URL(args.url).hostname;
+
+ const probe = await probeResource({ url: args.url, method, headers: args.headers, body: args.body });
+ if (probe.status !== 402) {
+ const content = await readBody(probe.response);
+ return {
+ ok: probe.response.ok,
+ action: 'fetched_free',
+ status: probe.status,
+ url: args.url,
+ paid: '0',
+ message: 'The resource did not ask for payment. Nothing was spent.',
+ ...content,
+ };
+ }
+
+ assertDelegated(ctx);
+
+ const requirement = selectRequirement({ accepts: probe.accepts, mint: record.mint, network: NETWORK });
+ const amount = requiredUnits(requirement);
+ const price = fromBaseUnits(amount, decimals);
+
+ if (args.max_price !== undefined) {
+ const ceiling = ctx.units(args.max_price);
+ if (amount > ceiling) {
+ throw Object.assign(
+ new Error(`the resource asks ${price} but max_price for this call is ${args.max_price}. Not paying.`),
+ { code: 'over_max_price' },
+ );
+ }
+ }
+
+ const decision = authorizeSpend(ctx, {
+ amount,
+ host,
+ confirm: args.confirm === true,
+ kind: 'x402',
+ resource: args.url,
+ });
+
+ const summary = summarize({
+ action: `"${record.id}" pays ${price} for ${args.url}`,
+ amount: price,
+ asset: record.mint,
+ from: record.vault,
+ to: requirement.payTo,
+ network: NETWORK,
+ extra: {
+ resource: args.url,
+ description: requirement.description || null,
+ host,
+ allowance_after: ctx.human(ctx.vault.delegatedAmount - amount),
+ guardrails_passed: decision.checks.filter((c) => c.ok).map((c) => c.check),
+ },
+ });
+
+ if (REQUIRE_CONFIRM && args.confirm !== true) {
+ return {
+ ok: false,
+ action: 'confirm_required',
+ summary,
+ price,
+ message: 'Nothing has been paid. Re-issue with confirm:true to buy this.',
+ };
+ }
+
+ const agentSol = await solBalance(connection, record.agent_pubkey);
+ if (agentSol * LAMPORTS_PER_SOL < MIN_AGENT_FEE_LAMPORTS) {
+ throw Object.assign(
+ new Error(
+ `the agent holds ${agentSol} SOL, too little to sign its top-up. ` +
+ 'Ask the owner to run fund_agent_wallet with sol:"0.02".',
+ ),
+ { code: 'no_fee_sol' },
+ );
+ }
+
+ // Top the agent's own account up for exactly the shortfall, pulled from
+ // the owner's vault against the delegation.
+ const agentAta = ataFor(record.mint, record.agent_pubkey, programId);
+ const held = (await tokenAccount(connection, agentAta, programId))?.amount ?? 0n;
+ let pullSignature = null;
+ if (held < amount) {
+ const shortfall = amount - held;
+ const { instructions } = delegatedTransferInstructions({
+ vault: record.vault,
+ mint: record.mint,
+ recipientOwner: record.agent_pubkey,
+ agent: record.agent_pubkey,
+ amount: shortfall,
+ decimals,
+ programId,
+ });
+ const pull = await agentAction({ connection, keypair: ctx.keypair(), instructions, network: NETWORK });
+ pullSignature = pull.signature;
+ }
+
+ let paid;
+ try {
+ paid = await payAndFetch({
+ url: args.url,
+ method,
+ headers: args.headers,
+ body: args.body,
+ secretKey: ctx.keypair().secretKey,
+ network: NETWORK,
+ requirement,
+ });
+ } catch (err) {
+ logSpend(ctx, {
+ kind: 'x402',
+ allowed: true,
+ settled: false,
+ amount: price,
+ base_units: String(amount),
+ resource: args.url,
+ host,
+ recipient: requirement.payTo,
+ pull_signature: pullSignature,
+ error: err.message,
+ });
+ throw Object.assign(
+ new Error(
+ `the payment did not settle: ${err.message}. ` +
+ (pullSignature
+ ? `${price} was moved into the agent's account (${agentAta.toBase58()}) and is still there; ` +
+ 'the next call to this tool will reuse it, or revoke_agent_wallet with withdraw:true recovers the vault.'
+ : 'Nothing left the vault.'),
+ ),
+ { code: 'settlement_failed', pull_signature: pullSignature },
+ );
+ }
+
+ const content = await readBody(paid.response);
+ const entry = logSpend(ctx, {
+ kind: 'x402',
+ settled: true,
+ amount: price,
+ base_units: String(amount),
+ resource: args.url,
+ host,
+ recipient: requirement.payTo,
+ signature: paid.settlement?.transaction || paid.settlement?.txHash || null,
+ pull_signature: pullSignature,
+ status: paid.response.status,
+ });
+
+ return {
+ ok: paid.response.ok,
+ action: 'paid',
+ status: paid.response.status,
+ url: args.url,
+ paid: price,
+ asset: record.mint,
+ paid_to: requirement.payTo,
+ settlement: paid.settlement,
+ vault_pull_signature: pullSignature,
+ allowance_remaining: ctx.human(ctx.vault.delegatedAmount - amount),
+ spent_24h: ctx.human(ctx.spentToday + amount),
+ logged_at: entry.at,
+ ...content,
+ };
+ },
+};
diff --git a/packages/onchain-agent-wallets/src/tools/revoke-agent-wallet.js b/packages/onchain-agent-wallets/src/tools/revoke-agent-wallet.js
new file mode 100644
index 000000000..4c54d4f78
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/revoke-agent-wallet.js
@@ -0,0 +1,110 @@
+// `revoke_agent_wallet`: the kill switch.
+//
+// One owner-signed instruction sets the vault's delegated amount to zero. From
+// that block on, every agent-signed transfer fails inside the token program,
+// whatever this server, the agent, or its model believes. Optionally sweeps the
+// vault balance back to the owner in the same transaction.
+
+import { z } from 'zod';
+
+import { NETWORK } from '../config.js';
+import { toBaseUnits, fromBaseUnits } from '../lib/solana.js';
+import { revokeInstruction, withdrawInstructions } from '../lib/vault.js';
+import { agentContext, describeAgent } from '../lib/agent.js';
+import { ownerAction, summarize } from '../lib/execute.js';
+import { updateState } from '../lib/store.js';
+
+export const def = {
+ name: 'revoke_agent_wallet',
+ title: "Revoke the agent's spending authority on-chain",
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
+ description:
+ "Cancel the agent's delegation on-chain. After this the SPL Token program refuses every transfer the agent " +
+ 'signs, permanently, until you approve a new allowance. Pass withdraw:true to also sweep the vault balance ' +
+ 'back to your wallet in the same transaction. For an instant free stop that needs no transaction and no SOL, ' +
+ 'use set_guardrails with paused:true instead: that blocks this server, while revoke blocks the chain itself. ' +
+ 'Requires confirm:true to broadcast.',
+ inputSchema: {
+ id: z.string().describe('The agent wallet to revoke.'),
+ withdraw: z.boolean().optional().describe('Also move the vault balance back to your wallet. Default false.'),
+ amount: z.string().optional().describe('Withdraw only this much instead of the whole balance.'),
+ secret: z.string().optional().describe('Owner secret key for this call only.'),
+ confirm: z.boolean().optional().describe('Set true to broadcast.'),
+ },
+ async handler(args) {
+ const ctx = await agentContext(args.id);
+ const { record, connection, decimals, programId } = ctx;
+
+ if (!ctx.vault.exists) {
+ throw Object.assign(new Error(`the vault for "${record.id}" does not exist on ${NETWORK}.`), { code: 'no_vault' });
+ }
+
+ const instructions = [];
+ if (ctx.vault.delegate) {
+ instructions.push(revokeInstruction({ vault: record.vault, owner: record.owner, programId }));
+ }
+
+ let withdrawUnits = 0n;
+ if (args.withdraw || args.amount) {
+ withdrawUnits = args.amount ? toBaseUnits(args.amount, decimals) : ctx.vault.balance;
+ if (withdrawUnits > ctx.vault.balance) {
+ throw Object.assign(
+ new Error(`the vault holds ${ctx.human(ctx.vault.balance)}, less than the ${args.amount} requested`),
+ { code: 'insufficient_vault' },
+ );
+ }
+ if (withdrawUnits > 0n) {
+ instructions.push(
+ ...withdrawInstructions({
+ owner: record.owner,
+ vault: record.vault,
+ mint: record.mint,
+ amount: withdrawUnits,
+ decimals,
+ programId,
+ }),
+ );
+ }
+ }
+
+ if (instructions.length === 0) {
+ return {
+ ok: true,
+ action: 'noop',
+ message: `"${record.id}" is already revoked and its vault is empty. Nothing to do.`,
+ agent: describeAgent(ctx),
+ };
+ }
+
+ const summary = summarize({
+ action: `Revoke "${record.id}"${withdrawUnits > 0n ? ` and withdraw ${fromBaseUnits(withdrawUnits, decimals)}` : ''}`,
+ network: NETWORK,
+ extra: {
+ agent_address: record.agent_pubkey,
+ vault: record.vault,
+ allowance_being_cancelled: ctx.human(ctx.vault.delegatedAmount),
+ withdrawing: withdrawUnits > 0n ? `${fromBaseUnits(withdrawUnits, decimals)} back to ${record.owner}` : 'nothing',
+ after: 'The agent can sign nothing against this vault until you approve a new allowance.',
+ },
+ });
+
+ const result = await ownerAction({
+ connection,
+ owner: record.owner,
+ instructions,
+ confirm: args.confirm === true,
+ secret: args.secret,
+ summary,
+ network: NETWORK,
+ note: `revoke agent wallet "${record.id}"`,
+ });
+
+ if (result.action === 'sent') {
+ updateState((state) => {
+ if (state.agents[record.id]) state.agents[record.id].revoked_at = new Date().toISOString();
+ });
+ }
+
+ return { ...result, agent: describeAgent(await agentContext(args.id)) };
+ },
+};
diff --git a/packages/onchain-agent-wallets/src/tools/send-signed-transaction.js b/packages/onchain-agent-wallets/src/tools/send-signed-transaction.js
new file mode 100644
index 000000000..3f609ec2b
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/send-signed-transaction.js
@@ -0,0 +1,28 @@
+// `send_signed_transaction`: the second half of the browser-wallet lane.
+// prepare returns an unsigned transaction, your wallet signs it, this
+// broadcasts it. No key is ever seen by this server.
+
+import { z } from 'zod';
+
+import { NETWORK } from '../config.js';
+import { connectionFor } from '../lib/solana.js';
+import { sendSignedBase64 } from '../lib/tx.js';
+
+export const def = {
+ name: 'send_signed_transaction',
+ title: 'Broadcast a transaction your wallet signed',
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
+ description:
+ 'Broadcast a base64 transaction that Phantom, Solflare, Backpack, or a Ledger already signed, and wait for ' +
+ 'confirmation. This is how the owner side works without any secret key on this machine: any tool that returns ' +
+ '"prepared_for_wallet" hands you a transaction_base64 to sign and pass here. Blockhashes expire in about 60 ' +
+ 'seconds, so if this reports an expired blockhash, re-run the tool that prepared it.',
+ inputSchema: {
+ signed_transaction: z.string().describe('The signed transaction, base64-encoded, as your wallet returned it.'),
+ },
+ async handler(args) {
+ const connection = connectionFor(NETWORK);
+ const sent = await sendSignedBase64({ connection, signedBase64: args.signed_transaction, network: NETWORK });
+ return { ok: true, network: NETWORK, ...sent };
+ },
+};
diff --git a/packages/onchain-agent-wallets/src/tools/set-guardrails.js b/packages/onchain-agent-wallets/src/tools/set-guardrails.js
new file mode 100644
index 000000000..c67f34ce0
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/set-guardrails.js
@@ -0,0 +1,61 @@
+// `set_guardrails`: the owner's rules, enforced before this server signs
+// anything. Free, instant, and needs no transaction, which is exactly why
+// paused:true is the fastest way to stop an agent mid-run. The on-chain
+// allowance is the backstop underneath; these are the finer rules on top.
+
+import { z } from 'zod';
+
+import { normalizePolicy } from '../lib/policy.js';
+import { updateState } from '../lib/store.js';
+import { agentContext, describeAgent } from '../lib/agent.js';
+
+export const def = {
+ name: 'set_guardrails',
+ title: "Change an agent's spending rules",
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
+ description:
+ 'Set the rules this server enforces before it signs a spend: per-transaction cap, rolling 24h cap, allowed ' +
+ 'recipients, allowed x402 hosts, an expiry, a confirm-above threshold, and a pause switch. Takes effect ' +
+ 'immediately, costs nothing, and needs no transaction. Only the fields you pass change; pass null to clear ' +
+ 'one. Empty allowlists mean unrestricted. These sit ON TOP of the on-chain allowance, which no software here ' +
+ 'can raise: to change that ceiling use approve_agent_allowance, and to cancel it entirely use ' +
+ 'revoke_agent_wallet.',
+ inputSchema: {
+ id: z.string().describe('The agent wallet.'),
+ per_tx: z.string().nullable().optional().describe('Maximum single spend, in tokens. null clears it.'),
+ daily: z.string().nullable().optional().describe('Maximum spend per rolling 24 hours. null clears it.'),
+ confirm_over: z.string().nullable().optional().describe('Spends above this need an explicit human confirm:true. null clears it.'),
+ allow_recipients: z.array(z.string()).nullable().optional().describe('Only these addresses may receive funds. Empty or null means unrestricted.'),
+ allow_hosts: z.array(z.string()).nullable().optional().describe('Only these hosts may be paid over x402, subdomains included. Empty or null means unrestricted.'),
+ expires_at: z.string().nullable().optional().describe('ISO timestamp after which every spend is refused. null clears it.'),
+ paused: z.boolean().optional().describe('true stops every spend immediately. false resumes.'),
+ },
+ async handler(args) {
+ const ctx = await agentContext(args.id);
+ const patch = {};
+ for (const key of ['per_tx', 'daily', 'confirm_over', 'allow_recipients', 'allow_hosts', 'expires_at', 'paused']) {
+ if (key in args && args[key] !== undefined) patch[key] = args[key];
+ }
+ if (Object.keys(patch).length === 0) {
+ throw Object.assign(new Error('pass at least one guardrail to change'), { code: 'validation_error' });
+ }
+
+ const before = ctx.policy;
+ const after = normalizePolicy(patch, before);
+ updateState((state) => {
+ state.agents[ctx.record.id].policy = after;
+ });
+
+ const changed = Object.keys(after).filter((k) => JSON.stringify(after[k]) !== JSON.stringify(before[k]));
+
+ return {
+ ok: true,
+ agent: ctx.record.id,
+ changed,
+ before,
+ after,
+ enforced_by: 'this server, before signing. The on-chain allowance is enforced by the SPL Token program.',
+ live: describeAgent({ ...ctx, policy: after }),
+ };
+ },
+};
diff --git a/packages/onchain-agent-wallets/src/tools/spend-log.js b/packages/onchain-agent-wallets/src/tools/spend-log.js
new file mode 100644
index 000000000..6ca0dced7
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/spend-log.js
@@ -0,0 +1,56 @@
+// `spend_log`: the audit trail. Every decision this server made, allowed and
+// refused alike, with the rule that decided it.
+
+import { z } from 'zod';
+
+import { spendHistory } from '../lib/store.js';
+import { agentContext } from '../lib/agent.js';
+import { spentInWindow } from '../lib/policy.js';
+import { fromBaseUnits, txLink } from '../lib/solana.js';
+import { NETWORK } from '../config.js';
+
+export const def = {
+ name: 'spend_log',
+ title: "An agent's spend history, including refusals",
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
+ description:
+ 'The audit trail for one agent: every spend that went through and every one the guardrails refused, with the ' +
+ 'amount, destination, transaction signature, and the rule that decided it. Refusals are recorded on purpose, ' +
+ 'so you can see what an agent tried to do. Read-only.',
+ inputSchema: {
+ id: z.string().describe('The agent wallet.'),
+ limit: z.number().int().min(1).max(500).optional().describe('How many entries to return, newest first. Default 50.'),
+ since: z.string().optional().describe('ISO timestamp: only entries at or after this time.'),
+ only: z.enum(['all', 'allowed', 'refused']).optional().describe('Filter by outcome. Default all.'),
+ },
+ async handler(args) {
+ const ctx = await agentContext(args.id);
+ const limit = args.limit || 50;
+ let rows = spendHistory(ctx.record.id, { since: args.since });
+ if (args.only === 'allowed') rows = rows.filter((r) => r.allowed);
+ if (args.only === 'refused') rows = rows.filter((r) => !r.allowed);
+
+ const recent = rows.slice(-limit).reverse().map((row) => ({
+ ...row,
+ ...(row.signature ? { link: txLink(row.signature, NETWORK) } : {}),
+ }));
+
+ const allowed = rows.filter((r) => r.allowed);
+ return {
+ ok: true,
+ agent: ctx.record.id,
+ returned: recent.length,
+ total_recorded: rows.length,
+ totals: {
+ spent_24h: fromBaseUnits(spentInWindow(ctx.ledger, { hours: 24 }), ctx.decimals),
+ spent_7d: fromBaseUnits(spentInWindow(ctx.ledger, { hours: 24 * 7 }), ctx.decimals),
+ spent_all_time: fromBaseUnits(
+ allowed.reduce((sum, r) => sum + BigInt(r.base_units || 0), 0n),
+ ctx.decimals,
+ ),
+ refusals: rows.length - allowed.length,
+ },
+ entries: recent,
+ };
+ },
+};
diff --git a/packages/onchain-agent-wallets/src/tools/withdraw-from-vault.js b/packages/onchain-agent-wallets/src/tools/withdraw-from-vault.js
new file mode 100644
index 000000000..0a3acbe41
--- /dev/null
+++ b/packages/onchain-agent-wallets/src/tools/withdraw-from-vault.js
@@ -0,0 +1,79 @@
+// `withdraw_from_vault`: take the money back. The owner needs no cooperation
+// from the agent to do this, and it works whether or not a delegation is live.
+
+import { z } from 'zod';
+
+import { NETWORK } from '../config.js';
+import { toBaseUnits, fromBaseUnits } from '../lib/solana.js';
+import { withdrawInstructions } from '../lib/vault.js';
+import { agentContext, describeAgent } from '../lib/agent.js';
+import { ownerAction, summarize } from '../lib/execute.js';
+
+export const def = {
+ name: 'withdraw_from_vault',
+ title: 'Move funds out of an agent vault back to the owner',
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ description:
+ 'Withdraw tokens from an agent vault back to your own wallet. The vault is yours, so this always works, ' +
+ 'with or without a live delegation, and the agent cannot block it. Leaves the allowance untouched: lowering ' +
+ 'the balance already limits what the agent can spend. Requires confirm:true to broadcast.',
+ inputSchema: {
+ id: z.string().describe('The agent wallet.'),
+ amount: z.string().optional().describe('Tokens to withdraw. Omit to withdraw the entire balance.'),
+ secret: z.string().optional().describe('Owner secret key for this call only.'),
+ confirm: z.boolean().optional().describe('Set true to broadcast.'),
+ },
+ async handler(args) {
+ const ctx = await agentContext(args.id);
+ const { record, connection, decimals, programId } = ctx;
+
+ if (!ctx.vault.exists || ctx.vault.balance === 0n) {
+ throw Object.assign(new Error(`the vault for "${record.id}" is empty. Nothing to withdraw.`), {
+ code: 'empty_vault',
+ });
+ }
+
+ const units = args.amount ? toBaseUnits(args.amount, decimals) : ctx.vault.balance;
+ if (units > ctx.vault.balance) {
+ throw Object.assign(
+ new Error(`the vault holds ${ctx.human(ctx.vault.balance)}, less than the ${args.amount} requested`),
+ { code: 'insufficient_vault' },
+ );
+ }
+
+ const instructions = withdrawInstructions({
+ owner: record.owner,
+ vault: record.vault,
+ mint: record.mint,
+ amount: units,
+ decimals,
+ programId,
+ });
+
+ const summary = summarize({
+ action: `Withdraw ${fromBaseUnits(units, decimals)} from the "${record.id}" vault`,
+ from: record.vault,
+ to: record.owner,
+ network: NETWORK,
+ extra: {
+ mint: record.mint,
+ vault_balance_after: fromBaseUnits(ctx.vault.balance - units, decimals),
+ allowance_remaining: ctx.human(ctx.vault.delegatedAmount),
+ note: 'The allowance is unchanged. The agent can still spend up to it, limited by whatever balance remains.',
+ },
+ });
+
+ const result = await ownerAction({
+ connection,
+ owner: record.owner,
+ instructions,
+ confirm: args.confirm === true,
+ secret: args.secret,
+ summary,
+ network: NETWORK,
+ note: `withdraw from "${record.id}"`,
+ });
+
+ return { ...result, agent: describeAgent(ctx) };
+ },
+};
diff --git a/packages/onchain-agent-wallets/test/guardrails.test.mjs b/packages/onchain-agent-wallets/test/guardrails.test.mjs
new file mode 100644
index 000000000..ce299c50d
--- /dev/null
+++ b/packages/onchain-agent-wallets/test/guardrails.test.mjs
@@ -0,0 +1,116 @@
+// The guardrail layer: exact decimal maths, and every rule that can refuse a
+// spend, including the ones that matter most when they are wrong.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import { toBaseUnits, fromBaseUnits } from '../src/lib/solana.js';
+import { normalizePolicy, normalizeHost, evaluateSpend, spentInWindow } from '../src/lib/policy.js';
+
+const D = 6;
+const u = (s) => toBaseUnits(s, D);
+
+test('amounts convert exactly, with no float drift', () => {
+ assert.equal(u('1'), 1_000_000n);
+ assert.equal(u('0.000001'), 1n);
+ assert.equal(u('1234.567891'), 1_234_567_891n);
+ assert.equal(fromBaseUnits(1_000_000n, D), '1');
+ assert.equal(fromBaseUnits(1n, D), '0.000001');
+ assert.equal(fromBaseUnits(1_234_567_891n, D), '1234.567891');
+ // 0.1 + 0.2 is the classic float failure. Base units make it exact.
+ assert.equal(u('0.1') + u('0.2'), u('0.3'));
+ assert.throws(() => u('1.1234567'), /decimal places/);
+ assert.throws(() => u('-5'), /positive decimal/);
+ assert.throws(() => u('abc'), /positive decimal/);
+});
+
+test('policy normalization rejects incoherent rules', () => {
+ assert.throws(() => normalizePolicy({ per_tx: '10', daily: '5' }), /never be reachable/);
+ assert.throws(() => normalizePolicy({ per_tx: 'lots' }), /positive decimal/);
+ assert.throws(() => normalizePolicy({ expires_at: 'soon' }), /ISO timestamp/);
+ assert.throws(() => normalizePolicy({ allow_recipients: ['not-an-address'] }), /valid Solana address/);
+
+ const cleared = normalizePolicy({ per_tx: null }, { per_tx: '5' });
+ assert.equal(cleared.per_tx, null, 'null clears a cap');
+
+ const kept = normalizePolicy({ daily: '50' }, { per_tx: '5' });
+ assert.equal(kept.per_tx, '5', 'unmentioned fields survive a patch');
+});
+
+test('hosts normalize from bare names and full URLs alike', () => {
+ assert.equal(normalizeHost('Example.COM'), 'example.com');
+ assert.equal(normalizeHost('https://api.example.com/v1/thing?x=1'), 'api.example.com');
+ assert.throws(() => normalizeHost(''), /cannot be empty/);
+});
+
+test('each guardrail refuses for its own reason', () => {
+ const policy = normalizePolicy({ per_tx: '5', daily: '20', allow_hosts: ['example.com'] });
+ const base = { policy, decimals: D, remainingAllowance: u('1000') };
+
+ assert.equal(evaluateSpend({ ...base, amount: u('1'), host: 'example.com' }).allowed, true);
+ assert.equal(evaluateSpend({ ...base, amount: u('6'), host: 'example.com' }).code, 'over_per_tx');
+ assert.equal(evaluateSpend({ ...base, amount: u('5'), spentToday: u('18'), host: 'example.com' }).code, 'over_daily');
+ assert.equal(evaluateSpend({ ...base, amount: u('1'), host: 'evil.com' }).code, 'host_not_allowed');
+ assert.equal(evaluateSpend({ ...base, amount: u('1'), host: 'api.example.com' }).allowed, true, 'subdomains inherit');
+ assert.equal(evaluateSpend({ ...base, amount: 0n, host: 'example.com' }).code, 'bad_amount');
+
+ const paused = normalizePolicy({ paused: true }, policy);
+ assert.equal(evaluateSpend({ ...base, policy: paused, amount: u('1'), host: 'example.com' }).code, 'paused');
+
+ const expired = normalizePolicy({ expires_at: '2020-01-01T00:00:00Z' }, policy);
+ assert.equal(evaluateSpend({ ...base, policy: expired, amount: u('1'), host: 'example.com' }).code, 'expired');
+});
+
+test('the on-chain allowance is checked even when local caps pass', () => {
+ const policy = normalizePolicy({ per_tx: '100' });
+ const decision = evaluateSpend({ policy, amount: u('50'), decimals: D, remainingAllowance: u('10') });
+ assert.equal(decision.allowed, false);
+ assert.equal(decision.code, 'over_allowance');
+});
+
+test('an empty allowlist means unrestricted, not locked out', () => {
+ const policy = normalizePolicy({ per_tx: '5' });
+ const decision = evaluateSpend({
+ policy,
+ amount: u('1'),
+ decimals: D,
+ remainingAllowance: u('100'),
+ recipient: 'So11111111111111111111111111111111111111112',
+ host: 'anywhere.example',
+ });
+ assert.equal(decision.allowed, true);
+ assert.ok(decision.checks.some((c) => c.check === 'recipient' && /unrestricted/.test(c.detail)));
+});
+
+test('the confirm threshold blocks once and passes when confirmed', () => {
+ const policy = normalizePolicy({ confirm_over: '1' });
+ const base = { policy, decimals: D, remainingAllowance: u('100') };
+
+ const blocked = evaluateSpend({ ...base, amount: u('2') });
+ assert.equal(blocked.allowed, false);
+ assert.equal(blocked.requires_confirm, true);
+ assert.equal(blocked.code, 'needs_confirmation');
+
+ assert.equal(evaluateSpend({ ...base, amount: u('2'), confirm: true }).allowed, true);
+ assert.equal(evaluateSpend({ ...base, amount: u('1') }).allowed, true, 'at the threshold is not over it');
+});
+
+test('a hard refusal outranks a confirmation prompt', () => {
+ // An over-cap spend must report the cap, never invite the caller to confirm
+ // its way past one.
+ const policy = normalizePolicy({ per_tx: '5', confirm_over: '1' });
+ const decision = evaluateSpend({ policy, amount: u('50'), decimals: D, remainingAllowance: u('1000') });
+ assert.equal(decision.code, 'over_per_tx');
+ assert.equal(decision.requires_confirm, false);
+});
+
+test('the daily window only counts allowed spends inside it', () => {
+ const now = new Date('2026-08-19T12:00:00Z');
+ const ledger = [
+ { at: '2026-08-19T11:00:00Z', allowed: true, base_units: '1000000' },
+ { at: '2026-08-19T10:00:00Z', allowed: false, base_units: '9000000' },
+ { at: '2026-08-17T10:00:00Z', allowed: true, base_units: '5000000' },
+ ];
+ assert.equal(spentInWindow(ledger, { hours: 24, now }), 1_000_000n, 'refusals and old rows are excluded');
+ assert.equal(spentInWindow(ledger, { hours: 24 * 7, now }), 6_000_000n);
+});
diff --git a/packages/onchain-agent-wallets/test/token-delegation.test.mjs b/packages/onchain-agent-wallets/test/token-delegation.test.mjs
new file mode 100644
index 000000000..b4327dfcc
--- /dev/null
+++ b/packages/onchain-agent-wallets/test/token-delegation.test.mjs
@@ -0,0 +1,248 @@
+// The custody thesis, proven against the real SPL Token program.
+//
+// solana-bankrun runs the actual token program ELF in process, so these are not
+// assertions about our own code: they are the token program itself refusing an
+// agent that tries to spend past the ceiling its owner approved.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import { start } from 'solana-bankrun';
+import { Keypair, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
+import {
+ MINT_SIZE,
+ TOKEN_PROGRAM_ID,
+ createInitializeMint2Instruction,
+ createAssociatedTokenAccountInstruction,
+ createMintToInstruction,
+ getAssociatedTokenAddressSync,
+} from '@solana/spl-token';
+
+import {
+ createVaultInstructions,
+ depositInstructions,
+ withdrawInstructions,
+ delegatedTransferInstructions,
+ revokeInstruction,
+ readVault,
+ spendableUnits,
+} from '../src/lib/vault.js';
+
+const DECIMALS = 6;
+const unit = (n) => BigInt(Math.round(n * 10 ** DECIMALS));
+
+/**
+ * The two Connection methods our vault code actually calls, backed by bankrun.
+ * This exercises the real readVault and createVaultInstructions rather than a
+ * parallel reimplementation.
+ */
+function connectionAdapter(client, rent) {
+ return {
+ rpcEndpoint: 'bankrun://test',
+ async getAccountInfo(address) {
+ const account = await client.getAccount(new PublicKey(address));
+ if (!account) return null;
+ return { ...account, data: Buffer.from(account.data) };
+ },
+ async getMinimumBalanceForRentExemption(space) {
+ return Number(rent.minimumBalance(BigInt(space)));
+ },
+ };
+}
+
+async function send(ctx, instructions, signers) {
+ const tx = new Transaction();
+ tx.recentBlockhash = ctx.lastBlockhash;
+ tx.feePayer = signers[0].publicKey;
+ for (const ix of instructions) tx.add(ix);
+ tx.sign(...signers);
+ return ctx.banksClient.processTransaction(tx);
+}
+
+test('an agent cannot spend past the allowance its owner approved', async (t) => {
+ const ctx = await start([], []);
+ const client = ctx.banksClient;
+ const rent = await client.getRent();
+ const connection = connectionAdapter(client, rent);
+
+ const owner = ctx.payer;
+ const agent = Keypair.generate();
+ const merchant = Keypair.generate();
+ const mint = Keypair.generate();
+ const agentId = 'researcher';
+
+ // A real mint, and 1000 tokens in the owner's own account.
+ const ownerAta = getAssociatedTokenAddressSync(mint.publicKey, owner.publicKey);
+ await send(
+ ctx,
+ [
+ SystemProgram.createAccount({
+ fromPubkey: owner.publicKey,
+ newAccountPubkey: mint.publicKey,
+ lamports: Number(rent.minimumBalance(BigInt(MINT_SIZE))),
+ space: MINT_SIZE,
+ programId: TOKEN_PROGRAM_ID,
+ }),
+ createInitializeMint2Instruction(mint.publicKey, DECIMALS, owner.publicKey, null),
+ createAssociatedTokenAccountInstruction(owner.publicKey, ownerAta, owner.publicKey, mint.publicKey),
+ createMintToInstruction(mint.publicKey, ownerAta, owner.publicKey, unit(1000)),
+ // The agent needs its own SOL to pay fees, and nothing else.
+ SystemProgram.transfer({ fromPubkey: owner.publicKey, toPubkey: agent.publicKey, lamports: 50_000_000 }),
+ ],
+ [owner, mint],
+ );
+
+ await t.test('the owner creates the vault and delegates a capped allowance', async () => {
+ const { vault, instructions } = await createVaultInstructions({
+ connection,
+ owner: owner.publicKey,
+ agentId,
+ mint: mint.publicKey,
+ delegate: agent.publicKey,
+ allowance: unit(100),
+ decimals: DECIMALS,
+ });
+ instructions.push(
+ ...depositInstructions({
+ owner: owner.publicKey,
+ vault,
+ mint: mint.publicKey,
+ amount: unit(500),
+ decimals: DECIMALS,
+ }),
+ );
+ await send(ctx, instructions, [owner]);
+
+ const state = await readVault({ connection, vault });
+ assert.equal(state.exists, true);
+ assert.equal(state.owner, owner.publicKey.toBase58(), 'the vault is owned by the owner, not the agent');
+ assert.equal(state.balance, unit(500), 'the vault holds the deposit');
+ assert.equal(state.delegate, agent.publicKey.toBase58(), 'the agent is the delegate');
+ assert.equal(state.delegatedAmount, unit(100), 'capped at the approved allowance');
+ assert.equal(spendableUnits(state), unit(100), 'spendable is the allowance, not the balance');
+ });
+
+ await t.test('the agent spends inside the allowance, and the chain decrements it', async () => {
+ const { vault } = await createVaultInstructions({
+ connection,
+ owner: owner.publicKey,
+ agentId,
+ mint: mint.publicKey,
+ delegate: agent.publicKey,
+ allowance: 0n,
+ decimals: DECIMALS,
+ });
+ const { instructions } = delegatedTransferInstructions({
+ vault,
+ mint: mint.publicKey,
+ recipientOwner: merchant.publicKey,
+ agent: agent.publicKey,
+ amount: unit(40),
+ decimals: DECIMALS,
+ });
+ await send(ctx, instructions, [agent]);
+
+ const state = await readVault({ connection, vault });
+ assert.equal(state.balance, unit(460), 'the vault paid out 40');
+ assert.equal(state.delegatedAmount, unit(60), 'the allowance dropped by exactly what was spent');
+ });
+
+ await t.test('the token program refuses a spend above the remaining allowance', async () => {
+ const vault = (
+ await createVaultInstructions({
+ connection,
+ owner: owner.publicKey,
+ agentId,
+ mint: mint.publicKey,
+ delegate: agent.publicKey,
+ allowance: 0n,
+ decimals: DECIMALS,
+ })
+ ).vault;
+
+ // 61 is under the 460 sitting in the vault, and over the 60 left on the
+ // delegation. Only the on-chain cap can stop this.
+ const { instructions } = delegatedTransferInstructions({
+ vault,
+ mint: mint.publicKey,
+ recipientOwner: merchant.publicKey,
+ agent: agent.publicKey,
+ amount: unit(61),
+ decimals: DECIMALS,
+ });
+
+ await assert.rejects(
+ () => send(ctx, instructions, [agent]),
+ (err) => /0x1|insufficient/i.test(String(err)),
+ 'the SPL Token program must reject a transfer above delegated_amount',
+ );
+
+ const state = await readVault({ connection, vault });
+ assert.equal(state.balance, unit(460), 'nothing moved');
+ assert.equal(state.delegatedAmount, unit(60), 'the allowance is untouched');
+ });
+
+ await t.test('revoke is a hard stop the agent cannot route around', async () => {
+ const vault = (
+ await createVaultInstructions({
+ connection,
+ owner: owner.publicKey,
+ agentId,
+ mint: mint.publicKey,
+ delegate: agent.publicKey,
+ allowance: 0n,
+ decimals: DECIMALS,
+ })
+ ).vault;
+
+ await send(ctx, [revokeInstruction({ vault, owner: owner.publicKey })], [owner]);
+
+ const revoked = await readVault({ connection, vault });
+ assert.equal(revoked.delegate, null, 'no delegate remains');
+ assert.equal(spendableUnits(revoked), 0n, 'nothing is spendable');
+
+ const { instructions } = delegatedTransferInstructions({
+ vault,
+ mint: mint.publicKey,
+ recipientOwner: merchant.publicKey,
+ agent: agent.publicKey,
+ amount: unit(1),
+ decimals: DECIMALS,
+ });
+ await assert.rejects(
+ () => send(ctx, instructions, [agent]),
+ 'a revoked agent cannot move even one unit',
+ );
+ });
+
+ await t.test('the owner recovers the balance without the agent', async () => {
+ const vault = (
+ await createVaultInstructions({
+ connection,
+ owner: owner.publicKey,
+ agentId,
+ mint: mint.publicKey,
+ delegate: agent.publicKey,
+ allowance: 0n,
+ decimals: DECIMALS,
+ })
+ ).vault;
+
+ await send(
+ ctx,
+ withdrawInstructions({
+ owner: owner.publicKey,
+ vault,
+ mint: mint.publicKey,
+ amount: unit(460),
+ decimals: DECIMALS,
+ }),
+ [owner],
+ );
+
+ const state = await readVault({ connection, vault });
+ assert.equal(state.balance, 0n, 'the vault is empty');
+ const ownerAccount = await readVault({ connection, vault: ownerAta });
+ assert.equal(ownerAccount.balance, unit(960), 'the owner holds 500 kept back plus the 460 recovered');
+ });
+});
diff --git a/packages/onchain-agent-wallets/test/x402-selection.test.mjs b/packages/onchain-agent-wallets/test/x402-selection.test.mjs
new file mode 100644
index 000000000..4724f50c5
--- /dev/null
+++ b/packages/onchain-agent-wallets/test/x402-selection.test.mjs
@@ -0,0 +1,71 @@
+// Choosing which payment option to settle. These refusals are the ones that
+// stop an agent paying on the wrong chain, in the wrong asset, or on mainnet
+// when it was configured for devnet.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import { clusterOf, selectRequirement, requiredUnits } from '../src/lib/x402.js';
+
+const MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const solanaOption = (over = {}) => ({
+ scheme: 'exact',
+ network: 'solana:mainnet',
+ asset: MINT,
+ maxAmountRequired: '10000',
+ payTo: 'So11111111111111111111111111111111111111112',
+ ...over,
+});
+
+test('cluster ids resolve, and non-Solana networks resolve to nothing', () => {
+ assert.equal(clusterOf('solana:mainnet'), 'mainnet');
+ assert.equal(clusterOf('solana:devnet'), 'devnet');
+ assert.equal(clusterOf('SOLANA:MAINNET'), 'mainnet');
+ assert.equal(clusterOf('eip155:8453'), null);
+ assert.equal(clusterOf(undefined), null);
+});
+
+test('a Solana option is chosen out of a mixed list', () => {
+ const accepts = [
+ { scheme: 'exact', network: 'eip155:8453', asset: '0xa0b8', maxAmountRequired: '10000' },
+ solanaOption(),
+ ];
+ const picked = selectRequirement({ accepts, mint: MINT, network: 'mainnet' });
+ assert.equal(picked.network, 'solana:mainnet');
+ assert.equal(requiredUnits(picked), 10_000n);
+});
+
+test('an EVM-only resource is refused rather than paid on another chain', () => {
+ const accepts = [{ scheme: 'exact', network: 'eip155:8453', asset: '0xa0b8', maxAmountRequired: '10000' }];
+ assert.throws(
+ () => selectRequirement({ accepts, mint: MINT, network: 'mainnet' }),
+ (err) => err.code === 'no_solana_option',
+ );
+});
+
+test('a mainnet price is refused by a devnet wallet', () => {
+ assert.throws(
+ () => selectRequirement({ accepts: [solanaOption()], mint: MINT, network: 'devnet' }),
+ (err) => err.code === 'wrong_cluster',
+ );
+});
+
+test('a price in another token is refused', () => {
+ assert.throws(
+ () => selectRequirement({ accepts: [solanaOption({ asset: 'SomeOtherMint1111111111111111111111111111' })], mint: MINT, network: 'mainnet' }),
+ (err) => err.code === 'asset_mismatch',
+ );
+});
+
+test('an unsupported scheme is refused', () => {
+ assert.throws(
+ () => selectRequirement({ accepts: [solanaOption({ scheme: 'upto' })], mint: MINT, network: 'mainnet' }),
+ (err) => err.code === 'unsupported_scheme',
+ );
+});
+
+test('a malformed or non-positive amount is refused', () => {
+ assert.throws(() => requiredUnits(solanaOption({ maxAmountRequired: '' })), /no amount/);
+ assert.throws(() => requiredUnits(solanaOption({ maxAmountRequired: '1.5' })), /base units/);
+ assert.throws(() => requiredUnits(solanaOption({ maxAmountRequired: '0' })), /must be positive/);
+});
diff --git a/public/changelog.json b/public/changelog.json
index dad2b16e1..c529c45e7 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-19T03:49:12.341Z",
+ "generated_at": "2026-08-19T20:35:11.335Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -38,6 +38,18 @@
"feature"
]
},
+ {
+ "date": "2026-08-19",
+ "type": "update",
+ "title": "Agents can now hold a spending allowance instead of your private key",
+ "summary": "Handing an AI agent a wallet has always meant handing it a private key, which means handing it everything in that wallet. The new onchain-agent-wallets MCP server replaces that with an allowance. Your money stays in an account you own, and the agent gets permission to spend a slice of it that the Solana token program enforces on-chain: it cannot spend past the ceiling however it is prompted, every spend decrements what is left, and you can cancel the whole thing in one instruction or take the balance back without the agent's cooperation. On top of that you set the rules it runs under: a maximum per transaction, a maximum per day, which addresses it may pay, which APIs it may buy from, an expiry, and a pause switch that stops it instantly for free. It can pay x402 APIs out of the allowance, and the price is always read before any money moves. Every decision, including every refusal and the reason for it, is written to an audit log you can read. You never have to put a secret key on the machine: owner actions come back as an unsigned transaction for Phantom, Solflare, or a Ledger to sign.",
+ "link": null,
+ "tags": [
+ "feature",
+ "sdk",
+ "security"
+ ]
+ },
{
"date": "2026-08-19",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index ab8717f1f..32224bd41 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -30,6 +30,14 @@
<category>improvement</category>
<description>The studio page every agent link opens now carries the agent's real substance. Its Capabilities tab lists the skills it genuinely exposes with the real per-call price of each, and a summary line telling you the cheapest paid call up front (or that everything is free). Skill names read as words instead of raw slugs, with the exact slug shown underneath for anyone wiring an integration. Under the title there is now a row of real counters: skills, conversations, wallet, whether the identity is on-chain, and how long the agent has been around. Below the fold, an agent recommends similar agents rather than unrelated avatars, each rendered as a live 3D card. The page also loads better: a skeleton in the real layout instead of a line of text, cards that show a picture while their 3D model downloads, and full keyboard support on the section tabs with a shareable link per tab.</description>
</item>
+ <item>
+ <title>Agents can now hold a spending allowance instead of your private key</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-08-19:Agents can now hold a spending allowance instead of your private key</guid>
+ <pubDate>Wed, 19 Aug 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Handing an AI agent a wallet has always meant handing it a private key, which means handing it everything in that wallet. The new onchain-agent-wallets MCP server replaces that with an allowance. Your money stays in an account you own, and the agent gets permission to spend a slice of it that the Solana token program enforces on-chain: it cannot spend past the ceiling however it is prompted, every spend decrements what is left, and you can cancel the whole thing in one instruction or take the balance back without the agent's cooperation. On top of that you set the rules it runs under: a maximum per transaction, a maximum per day, which addresses it may pay, which APIs it may buy from, an expiry, and a pause switch that stops it instantly for free. It can pay x402 APIs out of the allowance, and the price is always read before any money moves. Every decision, including every refusal and the reason for it, is written to an audit log you can read. You never have to put a secret key on the machine: owner actions come back as an unsigned transaction for Phantom, Solflare, or a Ledger to sign.</description>
+ </item>
<item>
<title>Every three.ws package on npm is current again</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 1d0144896..f1bfe2b1e 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-19T03:49:12.324Z",
+ "generated_at": "2026-08-19T20:35:11.326Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",