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(marketplace): agents buy assets and trade coins from their own wallets

nirholasf1c01ad1a0e7
diff --git a/api/_lib/agent-purchase.js b/api/_lib/agent-purchase.js
index 535c95766..354ecf30f 100644
--- a/api/_lib/agent-purchase.js
+++ b/api/_lib/agent-purchase.js
@@ -4,7 +4,7 @@
*
* Two marketplace surfaces sell things an agent can buy for itself: individual
* skills (`skill_purchases`, via /api/marketplace/purchase-as-agent) and whole
- * assets — avatars, agents, plugins (`asset_purchases`, via
+ * assets (avatars, agents, plugins; `asset_purchases`, via
* /api/marketplace/buy-asset with an `agent_id`). Both spend real USDC out of the
* same wallet under the same owner-configured ceiling, so the cap accounting,
* keypair recovery and transfer construction live here rather than being forked
@@ -16,14 +16,14 @@
* assets. Enforcement is two-phase at every call site, and the second phase is
* the authoritative one:
*
- * 1. Pre-check before doing expensive work — a cheap early rejection, and a
+ * 1. Pre-check before doing expensive work: a cheap early rejection, and a
* TOCTOU on its own (concurrent buys all read the same pre-spend SUM).
* 2. Re-check AFTER the pending row is inserted. The row is now counted by the
* same SUM, so every concurrent in-flight purchase is visible and the total
* cannot be collectively overshot. Fails safe: contending requests abort
* rather than risk exceeding the owner's limit.
*
- * Nothing here decides WHETHER a purchase is allowed beyond the cap — ownership,
+ * Nothing here decides WHETHER a purchase is allowed beyond the cap. Ownership,
* rate limits, self-dealing and already-owned checks stay with the endpoints,
* which have the surface-specific context to answer them.
*/
@@ -42,7 +42,7 @@ import { ensureAgentWallet, recoverSolanaAgentKeypair } from './agent-wallet.js'
export const USDC_DECIMALS = 6;
-/** Start of the current UTC day, as an ISO string — the cap window boundary. */
+/** Start of the current UTC day, as an ISO string: the cap window boundary. */
export function dayStartIso() {
const d = new Date();
d.setUTCHours(0, 0, 0, 0);
@@ -51,7 +51,7 @@ export function dayStartIso() {
/**
* Read the owner-configured autonomous purchase ceiling off an agent's meta.
- * @param {object|null} meta — agent_identities.meta
+ * @param {object|null} meta - agent_identities.meta
* @returns {{ enabled: boolean, limitUsdc: number|null, limitAtomics: bigint }}
*/
export function readPurchaseCap(meta) {
@@ -92,8 +92,10 @@ export async function sumDailyPurchaseAtomics({ userId, currencyMint }) {
AND currency_mint = ${currencyMint}
AND status NOT IN ('failed', 'expired')
), 0)
- )::numeric AS total
+ )::bigint AS total
`;
+ // ::bigint (not ::numeric) is load-bearing: SUM() yields numeric, which the
+ // driver can hand back as "2500000.00", a string BigInt() refuses to parse.
return BigInt(row?.total ?? 0);
}
@@ -110,7 +112,7 @@ export function capExceededMessage(limitUsdc) {
* missing or corrupt. Every decrypt is audit-logged with `reason` into
* usage_events + the owner-viewable custody trail.
*
- * The caller must ALREADY have verified that `userId` owns `agentId` — this
+ * The caller must ALREADY have verified that `userId` owns `agentId`; this
* function does not authorize, it only loads.
*
* @param {{ agentId: string, userId: string, reason: string, meta?: object }} args
diff --git a/api/marketplace/purchase-as-agent.js b/api/marketplace/purchase-as-agent.js
index bd451d528..667b81824 100644
--- a/api/marketplace/purchase-as-agent.js
+++ b/api/marketplace/purchase-as-agent.js
@@ -224,8 +224,7 @@ export default wrap(async (req, res) => {
purchase_id: pur.id, buyer_agent_id, skill,
spent: spentAtomics.toString(), limit_atomics: limitAtomics.toString(),
});
- return error(res, 402, 'spend_cap_exceeded',
- `daily spend cap of ${limitUsdc} USDC reached — increase meta.auto_purchase_daily_limit_usdc or wait until UTC midnight`);
+ return error(res, 402, 'spend_cap_exceeded', capExceededMessage(limitUsdc));
}
}
diff --git a/docs/agent-wallets.md b/docs/agent-wallets.md
index f1ac56303..6174766a7 100644
--- a/docs/agent-wallets.md
+++ b/docs/agent-wallets.md
@@ -26,13 +26,14 @@ This is the same secret box used for coin treasuries and the launcher, so every
## Who can spend
-Four paths move funds out of an agent wallet, and **all four pass through one policy module** before anything is signed:
+Five paths move funds out of an agent wallet, and **all five pass through one policy module** before anything is signed:
| Path | Trigger |
|------|---------|
| Withdraw | The owner sweeps funds out |
-| x402 pay | The agent pays for a paid API call |
-| Trade | A discretionary buy/sell from the wallet hub |
+| x402 pay | The agent pays for a paid API call. Also reachable from any paid checkout on the site: the [x402 payment modal](tutorials/pay-for-x402-service.md) lists a signed-in user's agents next to Phantom, and picking one settles from that agent's wallet with no popup |
+| Trade | A discretionary buy/sell from the wallet hub, or from the in-world coin widget's **Pay with** selector (SOL-denominated coins) |
+| Purchase | The agent buys a marketplace skill or asset for itself (see [Marketplace](marketplace.md)), under its own daily purchase cap |
| Snipe | The autonomous sniper worker executes a strategy |
Because enforcement lives at the signing boundary rather than in each feature, a new feature cannot accidentally introduce an unguarded spend path.
diff --git a/docs/marketplace.md b/docs/marketplace.md
index e6b8bc01e..fb2de1a0b 100644
--- a/docs/marketplace.md
+++ b/docs/marketplace.md
@@ -20,8 +20,35 @@ before anything is granted.
| **Trial** (time-boxed skill access) | — | `start-trial.js` | `skill_purchases` (status `trial`) |
| **Bundle** | — | `purchase-bundle.js` | `skill_purchases` |
-Agents can buy on their own behalf through `purchase-as-agent.js`, paying from
-their custodial wallet (see [Agent wallets](agent-wallets.md)).
+Agents can buy on their own behalf, paying from their custodial wallet (see
+[Agent wallets](agent-wallets.md)) with no browser wallet involved:
+
+| Buying | Endpoint | Request |
+|---|---|---|
+| A **skill** | `POST /api/marketplace/purchase-as-agent` | `{ buyer_agent_id, seller_agent_id, skill }` |
+| An **asset** | `POST /api/marketplace/buy-asset` | `{ item_type, item_id, agent_id }` |
+
+Both are owner-authenticated (the session user must own the buying agent),
+CSRF-gated, rate-limited to 10 autonomous purchases per hour per agent, and
+settle in a single request: the server decrypts the agent key (audit-logged),
+signs an SPL `transferChecked` carrying the Solana Pay reference, submits it via
+`submitProtected`, validates the transfer on-chain, then grants through the same
+finalize path a browser purchase uses. Nothing is granted on an unverified
+transfer; a short or misdirected payment lands as `tipped`, never a grant.
+
+**One daily budget covers both.** `agent_identities.meta.auto_purchase_daily_limit_usdc`
+(a number, e.g. `10` = $10/day; unset means no cap) is summed across
+`skill_purchases` **and** `asset_purchases` by
+[`api/_lib/agent-purchase.js`](../api/_lib/agent-purchase.js), so budget spent on
+skills is not available again for assets. Enforcement is two-phase: a cheap
+pre-check, then an authoritative re-check after the pending row is written, which
+makes it race-safe against concurrent purchases (the persisted row is counted by
+the same SUM). Exceeding it returns `402 spend_cap_exceeded` before any
+transaction is broadcast.
+
+In the UI, the asset purchase modal lists owned agents with live USDC balances
+above the browser-wallet buttons; underfunded agents render disabled. Agent
+purchases are Solana-only: an EVM-priced asset returns `400 unsupported_chain`.
## Purchase flow (Solana Pay)
diff --git a/src/agent-detail.css b/src/agent-detail.css
index 72b15a09e..33959d227 100644
--- a/src/agent-detail.css
+++ b/src/agent-detail.css
@@ -2286,6 +2286,39 @@ div.ad-hero-avatar canvas {
.payment-wallet-area a {
color: var(--ad-text);
}
+/* Agent-wallet payment options: an owned agent pays from its own custodial
+ balance, so there is no browser-wallet popup at all. Rendered above the
+ browser wallet buttons and visually separated from them. */
+.agent-wallet-options {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding-bottom: 10px;
+ margin-bottom: 4px;
+ border-bottom: 1px solid var(--ad-line);
+}
+.agent-wallet-options .agent-wallet-label {
+ margin: 0 0 2px;
+}
+.agent-wallet-pick {
+ background: transparent;
+ color: var(--ad-text);
+ border: 1px solid var(--ad-green);
+ text-align: left;
+ transition: background 0.12s ease, border-color 0.12s ease;
+}
+.agent-wallet-pick:hover:not(:disabled) {
+ background: rgba(74, 222, 128, 0.12);
+}
+.agent-wallet-pick:disabled {
+ border-color: var(--ad-line-2);
+ color: var(--ad-dim);
+ cursor: not-allowed;
+}
+.agent-wallet-pick:focus-visible {
+ outline: 2px solid var(--ad-green);
+ outline-offset: 2px;
+}
.btn-primary,
.payment-confirm-btn {
width: 100%;
diff --git a/src/game/coin-buy.css b/src/game/coin-buy.css
index 035225f67..102084ec4 100644
--- a/src/game/coin-buy.css
+++ b/src/game/coin-buy.css
@@ -164,6 +164,26 @@
.cc-buy-wallet-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--cc-live); box-shadow: var(--cc-glow); flex: none; }
.cc-buy-wallet-off { color: var(--cc-faint); }
+/* Payer picker: trade from an owned agent's custodial wallet (server-signed,
+ no extension) instead of the browser wallet. Hidden unless the user is
+ signed in with agents AND the coin is SOL-denominated. */
+.cc-buy-payer {
+ display: flex; align-items: center; gap: 8px; margin-top: 8px;
+ color: var(--cc-dim); font-size: 12px;
+}
+.cc-buy-payer[hidden] { display: none; }
+.cc-buy-payer-label { color: var(--cc-faint); flex: none; }
+.cc-buy-payer-select {
+ flex: 1; min-width: 0;
+ padding: 6px 8px; border-radius: 8px;
+ border: 1px solid var(--cc-edge); background: rgba(255, 255, 255, 0.04);
+ color: var(--cc-text); font-size: 12px; font-family: inherit;
+ cursor: pointer;
+ transition: border-color 0.12s ease, background 0.12s ease;
+}
+.cc-buy-payer-select:hover { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.06); }
+.cc-buy-payer-select:focus-visible { outline: 2px solid var(--cc-live); outline-offset: 2px; }
+
.cc-buy-cta {
width: 100%; margin-top: 14px; padding: 14px;
background: var(--cc-accent); color: var(--cc-ink);
diff --git a/src/game/coin-buy.js b/src/game/coin-buy.js
index 6623373e6..4fe0d6c98 100644
--- a/src/game/coin-buy.js
+++ b/src/game/coin-buy.js
@@ -155,6 +155,12 @@ class TradeModal {
// Firewall verdict for the current (mint, amount). 'block' disables Buy.
this.safetyVerdict = null;
this._safetySeq = 0;
+ // Selected payer. null = the browser wallet (default); otherwise an owned
+ // agent whose custodial wallet signs server-side, so the trade needs no
+ // wallet extension at all. Only offered for SOL-denominated trades, which
+ // is what /api/agents/:id/solana/trade accepts.
+ this._payerAgent = null;
+ this._agents = null;
this._build();
this._detectP = this._detectDenom();
this._refreshWallet();
@@ -195,6 +201,7 @@ class TradeModal {
]);
this.walletLine = el('div', { class: 'cc-buy-wallet' });
+ this.payerLine = el('div', { class: 'cc-buy-payer', hidden: true });
// Pre-trade rug/honeypot firewall verdict — rendered right above the CTA on
// buys. A 'block' disables the Buy button; the user can still review checks.
@@ -248,6 +255,7 @@ class TradeModal {
this.feeLine,
this.slipRow,
this.walletLine,
+ this.payerLine,
this.smartMoneyHost,
this.safetyHost,
this.cta,
@@ -366,6 +374,9 @@ class TradeModal {
this._refreshBalances();
this._quote();
this._syncCta();
+ // The coin prices in USDC, which the agent-trade endpoint does not
+ // take, so withdraw the payer row (and any selection made on it).
+ this._renderPayers();
}
} catch { /* keep optimistic SOL — prep still auto-detects server-side */ }
}
@@ -391,6 +402,112 @@ class TradeModal {
this._wallet = w;
}
this._syncCta();
+ this._refreshPayers();
+ }
+
+ // ------------------------------------------------------------- agent payer
+ // An owned agent with SOL in its own custodial wallet can place this trade
+ // server-side via /api/agents/:id/solana/trade, the same endpoint the wallet
+ // hub uses, with the same spend guardrails, so no browser wallet is needed.
+ // Signed-out users and USDC-denominated buys (which that endpoint does not
+ // take) simply never see the row.
+ async _refreshPayers() {
+ if (this._agents === null) {
+ this._agents = [];
+ try {
+ const res = await fetch('/api/x402-pay?agents=1', { credentials: 'include' });
+ if (res.ok) {
+ const data = await res.json();
+ this._agents = (Array.isArray(data?.agents) ? data.agents : []).filter((a) => a?.solana_address);
+ }
+ } catch { /* signed out or offline; browser-wallet path is unaffected */ }
+ }
+ this._renderPayers();
+ }
+
+ _renderPayers() {
+ if (!this.payerLine) return;
+ const eligible = this.denom.kind === 'sol' && this._agents?.length;
+ if (!eligible) {
+ // A payer that is no longer offerable must not stay silently selected.
+ if (this._payerAgent) { this._payerAgent = null; this._syncCta(); }
+ this.payerLine.hidden = true;
+ this.payerLine.textContent = '';
+ return;
+ }
+ this.payerLine.hidden = false;
+ this.payerLine.textContent = '';
+ const select = el('select', { class: 'cc-buy-payer-select', 'aria-label': 'Pay with' });
+ select.append(el('option', { value: '', text: 'Browser wallet' }));
+ for (const a of this._agents.slice(0, 8)) {
+ const bal = typeof a.sol === 'number' ? ` · ${a.sol.toFixed(3)} SOL` : '';
+ select.append(el('option', { value: a.id, text: `${a.name || 'Agent'}${bal}` }));
+ }
+ select.value = this._payerAgent?.id || '';
+ select.addEventListener('change', () => {
+ this._payerAgent = this._agents.find((a) => String(a.id) === select.value) || null;
+ this._setStatus('', '', true);
+ this._syncCta();
+ });
+ this.payerLine.append(el('span', { class: 'cc-buy-payer-label', text: 'Pay with' }), select);
+ }
+
+ // Place the trade from the selected agent's custodial wallet. One request:
+ // the server enforces ownership, the agent's spend limits and the trade
+ // firewall, signs, submits and confirms.
+ async _tradeAsAgent(side) {
+ const agent = this._payerAgent;
+ if (!agent) return;
+ this.busy = true; this._syncCta();
+ try {
+ const body = { side, mint: this.coin.mint, network: NETWORK, slippage_bps: this.slippageBps };
+ if (side === 'buy') {
+ body.sol_amount = this.amount;
+ } else {
+ const tokens = this._sellBaseUnits();
+ if (!tokens || tokens === '0') { this._setStatus('Enter an amount to sell.', 'err'); this.busy = false; this._syncCta(); return; }
+ body.token_amount_raw = tokens;
+ }
+ this._setStatus(`${side === 'buy' ? 'Buying' : 'Selling'} from ${agent.name || 'your agent'}'s wallet…`, '');
+
+ const csrf = await fetch('/api/csrf-token', { credentials: 'include' })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j) => j?.data?.token || null)
+ .catch(() => null);
+ const res = await fetch(`/api/agents/${encodeURIComponent(agent.id)}/solana/trade`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json', ...(csrf ? { 'x-csrf-token': csrf } : {}) },
+ body: JSON.stringify(body),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ const e = new Error(data.error_description || data.message || data.error || `trade failed (${res.status})`);
+ e.status = res.status;
+ throw e;
+ }
+
+ const sig = data.data?.signature || data.signature || null;
+ // Prefer the server's own explorer link (it knows the network it signed on).
+ const url = data.data?.explorer || (sig ? solanaTxExplorerUrl(NETWORK, sig) : null);
+ const verbPast = side === 'buy' ? 'Bought' : 'Sold';
+ this.cta.textContent = `${verbPast} ${side === 'buy' ? this.sym : this.symTokens} ✓`;
+ this._setStatusNode(
+ el('span', {}, [
+ `${verbPast} from ${agent.name || 'your agent'}'s wallet. `,
+ ...(url ? [el('a', { href: url, target: '_blank', rel: 'noopener', text: 'View on Solscan ↗' })] : []),
+ ]),
+ 'ok',
+ );
+ this.busy = false;
+ this.cta.disabled = true;
+ // The agent's SOL changed, so the payer row's balances are stale.
+ this._agents = null;
+ setTimeout(() => { this._refreshBalances(); this._refreshPayers(); }, 1500);
+ } catch (err) {
+ this.busy = false; this._syncCta();
+ this._handleTradeError(err, side, () => this._tradeAsAgent(side));
+ }
}
// Fetch the wallet's USDC balance (USDC buys) and coin holdings (sells). A
@@ -477,8 +594,12 @@ class TradeModal {
const connected = !!w?.publicKey;
if (this.busy) { this.cta.disabled = true; return; }
const verb = this.mode === 'sell' ? 'sell' : 'buy';
- if (!w) { this.cta.textContent = `Get Phantom to ${verb}`; this.ctaLabel = 'install'; this.cta.disabled = false; return; }
- if (!connected) { this.cta.textContent = 'Connect wallet'; this.ctaLabel = 'connect'; this.cta.disabled = false; return; }
+ // An agent payer signs server-side, so the browser-wallet install/connect
+ // gates below do not apply to it.
+ if (!this._payerAgent) {
+ if (!w) { this.cta.textContent = `Get Phantom to ${verb}`; this.ctaLabel = 'install'; this.cta.disabled = false; return; }
+ if (!connected) { this.cta.textContent = 'Connect wallet'; this.ctaLabel = 'connect'; this.cta.disabled = false; return; }
+ }
if (this.mode === 'sell') {
// Holdings are advisory: a read can lag the chain, so a typed sell is
@@ -504,7 +625,10 @@ class TradeModal {
return;
}
this.ctaLabel = 'buy';
- this.cta.textContent = this.amount > 0 ? `Buy ${this.amount} ${this.denom.label} of ${this.sym}` : 'Enter an amount';
+ const payerSuffix = this._payerAgent ? ` with ${this._payerAgent.name || 'agent'}` : '';
+ this.cta.textContent = this.amount > 0
+ ? `Buy ${this.amount} ${this.denom.label} of ${this.sym}${payerSuffix}`
+ : 'Enter an amount';
this.cta.disabled = !(this.amount > 0);
}
@@ -715,6 +839,11 @@ class TradeModal {
// --------------------------------------------------------------- actions
async _onCta() {
if (this.busy) return;
+ // Agent payer: the server signs, so skip the browser-wallet install /
+ // connect handshake entirely and place the trade directly.
+ if (this._payerAgent) {
+ return this._tradeAsAgent(this.mode === 'sell' ? 'sell' : 'buy');
+ }
const w = detectSolanaWallet();
if (!w) { window.open('https://phantom.app/', '_blank', 'noopener'); return; }
if (!w.publicKey) {
diff --git a/src/shared/skill-purchase.js b/src/shared/skill-purchase.js
index 4530f1e56..4bb68eeb2 100644
--- a/src/shared/skill-purchase.js
+++ b/src/shared/skill-purchase.js
@@ -518,6 +518,11 @@ function updateWalletUI() {
<p>Connected via <strong>${escapeHtml(connectedWallet.name)}</strong>: ${pk.slice(0, 4)}…${pk.slice(-4)}</p>
<button class="btn-secondary" id="payment-disconnect-btn">Disconnect</button>`;
$('payment-disconnect-btn').addEventListener('click', disconnectWallet);
+ // A connected browser wallet does not hide the agent-wallet option: the
+ // buyer may still prefer to spend an agent's balance rather than their own.
+ if ($('payment-confirm-btn')?.dataset.mode === 'asset') {
+ renderAgentWalletOptions().catch(() => {});
+ }
refreshConfirmEnabled();
return;
}
@@ -552,6 +557,12 @@ function updateWalletUI() {
});
}
$('payment-show-qr')?.addEventListener('click', startQrPurchase);
+ // Asset purchases can also be paid by an owned agent's wallet, which needs no
+ // browser wallet at all. Rendered asynchronously so the balance read never
+ // delays the wallet buttons above.
+ if ($('payment-confirm-btn')?.dataset.mode === 'asset') {
+ renderAgentWalletOptions().catch(() => {});
+ }
refreshConfirmEnabled();
}
@@ -831,6 +842,118 @@ export function openAssetPurchaseFlow(asset) {
updateWalletUI();
}
+// ── Agent-wallet asset purchase ─────────────────────────────────────────────
+//
+// An owned agent with USDC in its own custodial wallet can buy an asset without
+// any browser wallet: POST /api/marketplace/buy-asset with `agent_id` makes the
+// server sign from that wallet, under the agent's daily purchase cap, and return
+// the confirmed purchase in one round trip (no prepare → sign → confirm dance).
+
+let _agentWalletsPromise = null;
+
+// Owned agents + live USDC/SOL balances. Cached per page load: the picker may
+// re-render several times (wallet connect/disconnect) and each render must not
+// re-hit the balance endpoint. Returns [] when signed out or unavailable, so the
+// section simply doesn't render.
+function fetchOwnedAgentWallets({ force = false } = {}) {
+ if (force) _agentWalletsPromise = null;
+ if (!_agentWalletsPromise) {
+ _agentWalletsPromise = fetch('/api/x402-pay?agents=1', { credentials: 'include' })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j) => (Array.isArray(j?.agents) ? j.agents.filter((a) => a?.solana_address) : []))
+ .catch(() => []);
+ }
+ return _agentWalletsPromise;
+}
+
+// Render the "Your agents" block into the modal's wallet area for asset mode.
+// Called after the browser-wallet buttons are in place, so the agent options
+// appear first without the wallet list waiting on this network read.
+async function renderAgentWalletOptions() {
+ const walletArea = $('payment-wallet-area');
+ const asset = pendingAssetPurchase;
+ if (!walletArea || !asset) return;
+
+ const agents = await fetchOwnedAgentWallets();
+ // The modal may have closed or switched modes while this was in flight.
+ if (!agents.length || pendingAssetPurchase !== asset || $('payment-modal-overlay')?.hidden) return;
+ if (walletArea.querySelector('.agent-wallet-pick')) return; // already rendered
+
+ const decimals = Number(asset.price?.mint_decimals ?? 6);
+ const priceUsdc = Number(asset.price?.amount || 0) / Math.pow(10, decimals);
+ const block = document.createElement('div');
+ block.className = 'agent-wallet-options';
+ block.innerHTML = `
+ <p class="muted small agent-wallet-label">Pay from an agent's own wallet, no popup</p>
+ ${agents.slice(0, 4).map((a) => {
+ const short = typeof a.usdc === 'number' && a.usdc < priceUsdc;
+ const bal = typeof a.usdc === 'number' ? `${a.usdc.toFixed(2)} USDC` : 'balance unavailable';
+ return `<button class="btn-primary agent-wallet-pick" data-agent-id="${escapeHtml(a.id)}" ${short ? 'disabled' : ''}
+ title="${escapeHtml(a.solana_address)}">
+ Pay with ${escapeHtml(a.name || 'agent')} · ${escapeHtml(bal)}${short ? ' (not enough)' : ''}
+ </button>`;
+ }).join('')}
+ `;
+ walletArea.prepend(block);
+ block.querySelectorAll('.agent-wallet-pick').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const agent = agents.find((a) => String(a.id) === btn.dataset.agentId);
+ if (agent) handleAssetPurchaseAsAgent(agent);
+ });
+ });
+}
+
+// Buy the pending asset from `agent`'s custodial wallet. One POST: the server
+// enforces ownership, the rate limit and the daily cap, signs, verifies the
+// on-chain transfer, and grants the asset.
+async function handleAssetPurchaseAsAgent(agent) {
+ const asset = pendingAssetPurchase;
+ if (!asset) { setStatus('No asset selected.', 'err'); return; }
+ const confirmBtn = $('payment-confirm-btn');
+ if (confirmBtn) confirmBtn.disabled = true;
+ $('payment-wallet-area')?.querySelectorAll('button').forEach((b) => { b.disabled = true; });
+ setStatus(`Paying from ${agent.name || 'agent'}'s wallet…`);
+
+ try {
+ const r = await apiPostWithCsrf('/api/marketplace/buy-asset', {
+ item_type: asset.item_type,
+ item_id: asset.item_id,
+ agent_id: agent.id,
+ });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j.error_description || j.error || 'Purchase failed');
+
+ _agentWalletsPromise = null; // balance changed
+ const target = assetViewTarget(asset);
+ if (j.data?.already_owned) {
+ renderPaymentSuccess({
+ title: 'Already owned',
+ message: `You already purchased ${asset.label}.`,
+ primaryHref: target.href,
+ primaryLabel: target.label,
+ });
+ return;
+ }
+ showToast(`${asset.label} purchased by ${agent.name || 'your agent'}.`, { type: 'success' });
+ renderPaymentSuccess({
+ title: `${asset.label} purchased`,
+ message: `Paid from ${agent.name || 'your agent'}'s wallet. ${
+ asset.item_type === 'avatar' ? 'Your new avatar' : asset.item_type === 'agent' ? 'Your new agent' : 'Your purchase'
+ } is in your dashboard.`,
+ primaryHref: target.href,
+ primaryLabel: target.label,
+ });
+ cfg.onPurchased(asset.item_id).catch(() => {});
+ } catch (e) {
+ log.error('[skill-purchase] agent asset purchase failed', e);
+ showToast(e.message || 'Purchase failed', { type: 'error' });
+ setStatus(e.message || 'Purchase failed', 'err');
+ if (confirmBtn) confirmBtn.disabled = false;
+ // Re-render so the agent buttons (and their balances) come back enabled.
+ updateWalletUI();
+ }
+}
+
async function createPendingAssetPurchase(itemType, itemId, buyerPublicKey = null) {
const body = { item_type: itemType, item_id: itemId };
if (buyerPublicKey) body.buyer_public_key = buyerPublicKey;
diff --git a/tests/api/agent-purchase-cap.test.js b/tests/api/agent-purchase-cap.test.js
new file mode 100644
index 000000000..a17401010
--- /dev/null
+++ b/tests/api/agent-purchase-cap.test.js
@@ -0,0 +1,117 @@
+// Unit tests for the shared autonomous-purchase plumbing (api/_lib/agent-purchase.js).
+//
+// The important property under test is that ONE daily budget governs BOTH
+// purchase surfaces: skills (/api/marketplace/purchase-as-agent, skill_purchases)
+// and whole assets (/api/marketplace/buy-asset with agent_id, asset_purchases).
+// Before this was shared, an agent that spent its cap on skills could turn around
+// and spend the same cap again on assets.
+//
+// Pure logic + a mocked `sql` tag. No DB, no RPC, no signing.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const sqlCalls = [];
+let sqlResult = [{ total: '0' }];
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (strings, ...values) => {
+ sqlCalls.push({ text: strings.join('?'), values });
+ return Promise.resolve(sqlResult);
+ },
+}));
+
+const {
+ readPurchaseCap,
+ sumDailyPurchaseAtomics,
+ capExceededMessage,
+ dayStartIso,
+ USDC_DECIMALS,
+} = await import('../../api/_lib/agent-purchase.js');
+
+beforeEach(() => {
+ sqlCalls.length = 0;
+ sqlResult = [{ total: '0' }];
+});
+
+describe('readPurchaseCap', () => {
+ it('is disabled when the owner has set no limit', () => {
+ expect(readPurchaseCap(null).enabled).toBe(false);
+ expect(readPurchaseCap({}).enabled).toBe(false);
+ expect(readPurchaseCap({ auto_purchase_daily_limit_usdc: null }).enabled).toBe(false);
+ });
+
+ it('converts a dollar limit to USDC atomics', () => {
+ const cap = readPurchaseCap({ auto_purchase_daily_limit_usdc: 10 });
+ expect(cap.enabled).toBe(true);
+ expect(cap.limitUsdc).toBe(10);
+ expect(cap.limitAtomics).toBe(10_000_000n);
+ expect(USDC_DECIMALS).toBe(6);
+ });
+
+ it('handles fractional limits without floating-point drift', () => {
+ expect(readPurchaseCap({ auto_purchase_daily_limit_usdc: 0.07 }).limitAtomics).toBe(70_000n);
+ expect(readPurchaseCap({ auto_purchase_daily_limit_usdc: 1.23 }).limitAtomics).toBe(1_230_000n);
+ });
+
+ it('treats zero, negative, NaN and non-numbers as no cap (never as a zero budget)', () => {
+ // A zero-or-garbage value must not silently block every purchase; the knob
+ // is opt-in, so anything that isn't a positive number means "unset".
+ for (const v of [0, -5, NaN, Infinity, '10', true, {}]) {
+ expect(readPurchaseCap({ auto_purchase_daily_limit_usdc: v }).enabled).toBe(false);
+ }
+ });
+});
+
+describe('sumDailyPurchaseAtomics', () => {
+ it('sums skill AND asset purchases in one query', async () => {
+ sqlResult = [{ total: '2500000' }];
+ const total = await sumDailyPurchaseAtomics({ userId: 'u1', currencyMint: 'MintABC' });
+
+ expect(total).toBe(2_500_000n);
+ expect(sqlCalls).toHaveLength(1);
+ const { text, values } = sqlCalls[0];
+ // Both tables are counted against the same budget.
+ expect(text).toContain('skill_purchases');
+ expect(text).toContain('asset_purchases');
+ // Each table is keyed by its own buyer column.
+ expect(text).toContain('user_id =');
+ expect(text).toContain('buyer_user_id =');
+ // Terminal failures never consume budget; pending does (it is in flight).
+ expect(text).toContain("NOT IN ('failed', 'expired')");
+ expect(values).toContain('u1');
+ expect(values).toContain('MintABC');
+ });
+
+ it('returns 0n when the user has spent nothing today', async () => {
+ sqlResult = [{ total: '0' }];
+ expect(await sumDailyPurchaseAtomics({ userId: 'u1', currencyMint: 'M' })).toBe(0n);
+ });
+
+ it('returns a BigInt for amounts beyond Number.MAX_SAFE_INTEGER', async () => {
+ // USDC atomics of a large treasury purchase must not lose precision.
+ sqlResult = [{ total: '9007199254740993' }];
+ const total = await sumDailyPurchaseAtomics({ userId: 'u1', currencyMint: 'M' });
+ expect(total).toBe(9007199254740993n);
+ expect(typeof total).toBe('bigint');
+ });
+
+ it('treats a missing row as zero rather than throwing', async () => {
+ sqlResult = [];
+ expect(await sumDailyPurchaseAtomics({ userId: 'u1', currencyMint: 'M' })).toBe(0n);
+ });
+
+ it('scopes the window to the start of the current UTC day', async () => {
+ await sumDailyPurchaseAtomics({ userId: 'u1', currencyMint: 'M' });
+ const since = sqlCalls[0].values.find((v) => typeof v === 'string' && v.endsWith('T00:00:00.000Z'));
+ expect(since).toBeTruthy();
+ expect(since).toBe(dayStartIso());
+ });
+});
+
+describe('capExceededMessage', () => {
+ it('names the limit and how to change it', () => {
+ const msg = capExceededMessage(10);
+ expect(msg).toContain('10 USDC');
+ expect(msg).toContain('auto_purchase_daily_limit_usdc');
+ });
+});
diff --git a/workers/agent-sniper/README.md b/workers/agent-sniper/README.md
index 585155ac2..b70333249 100644
--- a/workers/agent-sniper/README.md
+++ b/workers/agent-sniper/README.md
@@ -94,6 +94,36 @@ Enforced in `executeBuy`, short-circuiting before any transaction:
> position with its actual proceeds (`error = 'reconciled_onchain'`) instead of
> retrying a sell that can only revert (pump error 6023, `NotEnoughTokensToSell`);
> a short balance clamps the sell to what the wallet really holds.
+>
+> The search covers the DERIVED associated-token address for both token programs,
+> not just live token accounts: an emptying sell usually closes the account in the
+> same transaction to reclaim rent, and a closed account keeps its signature
+> history but disappears from an account listing.
+>
+> **When the emptying tx cannot be found**, the position parks as
+> `reconcile_pending` with `reconcile_pending_since` stamped. A park is not free:
+> `countOpenPositions()` counts `opening`/`open`/`closing`, so a parked position
+> holds one of its arm's `max_concurrent_positions` slots. Two bounds keep that
+> from becoming permanent:
+>
+> - After `RECONCILE_GIVE_UP_MS` (6 h) the position books `closed` with
+> `error = 'reconcile_unresolved'` and realized P&L left **NULL** — the bag is
+> provably gone but its proceeds are unknowable, and every P&L query filters
+> NULL out, so the slot frees without inventing a number.
+> - A `closing` lock older than 10 minutes is released back to `open` by
+> `getOpenPositions()`. `closing` is held for seconds around a broadcast, so an
+> older one is an abandoned attempt from a worker restart; the release keys off
+> `last_quoted_at`, so a position still being worked is never disturbed.
+>
+> **A settled position can never return to `open`.** A database trigger
+> (`sniper_block_resurrect`) coerces the status back and records the attempt in
+> `sniper_resurrect_attempts`. The invariant lives in the DB because the worker is
+> deployed separately: an old image with the unguarded park cannot violate it, and
+> a non-empty recent window in that table means such an image is still running.
+>
+> To clear positions already parked without waiting for a worker deploy:
+> `node scripts/sniper-reconcile-wedged.mjs` (re-reads every real on-chain balance
+> and skips anything still holding tokens).
## Decision modes and the experiment fleet