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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: A2A cart mandate verification and pay-what-you-want skill pricing
nirholasccdfd68e6fbd
diff --git a/api/_lib/a2a/cart-mandate.js b/api/_lib/a2a/cart-mandate.jsnew file mode 100644index 000000000..d62b76668--- /dev/null+++ b/api/_lib/a2a/cart-mandate.js@@ -0,0 +1,276 @@+// Cart Mandate — AP2's per-transaction approval, the companion to the Intent+// Mandate in api/_lib/a2a/mandate.js.+//+// Where an Intent Mandate is a STANDING authorization ("agent X may spend up to+// $N on my behalf, under these caps"), a Cart Mandate is a SPECIFIC, now-or-never+// approval of one exact transaction: this resource, this amount, this currency,+// on this network, for these line items. It is signed at settlement time and+// cryptographically bound to the Intent Mandate it draws on (by the intent's+// jti) and to the cart contents (by a SHA-256 hash), so it is a non-repudiable+// record that says: "the holder of intent mandate <id>, owned by <user>,+// authorized paying <resource> exactly <amount> <currency> for <this cart>."+//+// This mirrors Google's Agent Payments Protocol (AP2), where the Cart Mandate is+// the artifact a merchant retains as proof of what was agreed before settlement.+// In three.ws it composes with x402: the Intent Mandate gates whether a payment+// is allowed (api/agents/a2a-call.js), the Cart Mandate records exactly what was+// paid, and x402 performs the settlement.+//+// Signed as a compact JWS (HS256) with the same A2A_MANDATE_SECRET the Intent+// Mandate uses — the platform is the mandate authority. Verification is fully+// offline and recomputes the cart hash, so a presented Cart Mandate whose body+// was altered fails the same way a bad signature does.++import * as jose from 'jose';++import { env } from '../env.js';+import { MandateError } from './mandate.js';++export const CART_MANDATE_TYPE = 'a2a-cart-mandate';+export const CART_MANDATE_VERSION = 1;++// A specific cart is a now-or-never approval — short-lived by design. 5 min+// default covers a quote→settle round-trip; 1 hour is the hard ceiling.+export const DEFAULT_CART_TTL_SECONDS = 5 * 60;+export const MAX_CART_TTL_SECONDS = 60 * 60;++function secretKey() {+ const secret = env.A2A_MANDATE_SECRET;+ if (!secret) {+ throw new MandateError(+ 'mandate_signing_unconfigured',+ 'A2A_MANDATE_SECRET (or JWT_SECRET) must be set to issue or verify cart mandates',+ 500,+ );+ }+ return new TextEncoder().encode(secret);+}++function toPositiveAtomics(value, field) {+ let bi;+ try {+ bi = typeof value === 'bigint' ? value : BigInt(String(value).trim());+ } catch {+ throw new MandateError('invalid_amount', `${field} must be an integer atomic amount`);+ }+ if (bi <= 0n) throw new MandateError('invalid_amount', `${field} must be greater than zero`);+ return bi;+}++// Normalize a cart into a canonical, deterministically-ordered object so its+// hash is stable regardless of input key order or extra fields. Line items are+// reduced to {name, amountAtomics} and sorted, so the same cart always hashes the+// same on both the issuing and verifying side.+function canonicalCart(cart) {+ const items = Array.isArray(cart.items)+ ? cart.items+ .map((it) => ({+ name: String(it?.name ?? ''),+ amountAtomics: it?.amountAtomics != null ? String(it.amountAtomics) : '',+ }))+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))+ : [];+ // Fixed key order — JSON.stringify preserves insertion order for string keys.+ return JSON.stringify({+ amountAtomics: String(cart.amountAtomics),+ currency: String(cart.currency || ''),+ items,+ network: String(cart.network || ''),+ resource: String(cart.resource || ''),+ taskId: String(cart.taskId || ''),+ });+}++// SHA-256 of the canonical cart, hex-encoded. Web Crypto (subtle) keeps this+// runtime-agnostic across Node and the edge runtime.+async function cartHash(cart) {+ const data = new TextEncoder().encode(canonicalCart(cart));+ const digest = await globalThis.crypto.subtle.digest('SHA-256', data);+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');+}++function validateCart(cart) {+ if (!cart || typeof cart !== 'object') {+ throw new MandateError('invalid_cart', 'cart is required');+ }+ if (!cart.resource || !/^https?:\/\//i.test(String(cart.resource))) {+ throw new MandateError('invalid_cart', 'cart.resource must be an http(s) URL');+ }+ toPositiveAtomics(cart.amountAtomics, 'cart.amountAtomics');+ if (!cart.network) throw new MandateError('invalid_cart', 'cart.network is required');+ if (cart.items != null && !Array.isArray(cart.items)) {+ throw new MandateError('invalid_cart', 'cart.items must be an array');+ }+}++function decodeFromClaims(claims, registered) {+ const c = claims.c || {};+ return {+ cartMandateId: registered.jti,+ intentMandateId: claims.intent,+ ownerUserId: claims.owner,+ subjectAgentId: registered.sub,+ resource: c.resource,+ amountAtomics: c.amountAtomics,+ currency: c.currency,+ network: c.network,+ items: Array.isArray(c.items) ? c.items : [],+ taskId: c.taskId || '',+ hash: c.hash,+ issuedAt: registered.iat,+ expiresAt: registered.exp,+ };+}++/**+ * Issue (sign) a Cart Mandate bound to a verified Intent Mandate.+ *+ * @param {object} opts+ * @param {object} opts.intentMandate Decoded Intent Mandate (from verifyIntentMandate).+ * @param {object} opts.cart { resource, amountAtomics, currency, network, items?, taskId? }+ * @param {number} [opts.ttlSec] Lifetime (1..MAX_CART_TTL_SECONDS).+ * @returns {Promise<{ jws: string, cartMandate: object }>}+ */+export async function issueCartMandate({ intentMandate, cart, ttlSec = DEFAULT_CART_TTL_SECONDS }) {+ if (!intentMandate?.mandateId || !intentMandate.ownerUserId || !intentMandate.subjectAgentId) {+ throw new MandateError('invalid_mandate', 'a verified intent mandate is required', 400);+ }+ validateCart(cart);++ const ttl = Number(ttlSec);+ if (!Number.isFinite(ttl) || ttl < 1 || ttl > MAX_CART_TTL_SECONDS) {+ throw new MandateError('invalid_ttl', `ttlSec must be between 1 and ${MAX_CART_TTL_SECONDS}`);+ }++ const normalizedCart = {+ resource: String(cart.resource),+ amountAtomics: String(toPositiveAtomics(cart.amountAtomics, 'cart.amountAtomics')),+ currency: String(cart.currency || intentMandate.currency || ''),+ network: String(cart.network),+ taskId: String(cart.taskId || ''),+ items: Array.isArray(cart.items) ? cart.items : [],+ };+ const hash = await cartHash(normalizedCart);++ const nowSec = Math.floor(Date.now() / 1000);+ const mandateId = globalThis.crypto.randomUUID();+ const claims = {+ typ: CART_MANDATE_TYPE,+ ver: CART_MANDATE_VERSION,+ owner: intentMandate.ownerUserId,+ intent: intentMandate.mandateId,+ c: { ...normalizedCart, hash },+ };++ const jws = await new jose.SignJWT(claims)+ .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })+ .setSubject(intentMandate.subjectAgentId)+ .setIssuer(env.APP_ORIGIN)+ .setIssuedAt(nowSec)+ .setExpirationTime(nowSec + ttl)+ .setJti(mandateId)+ .sign(secretKey());++ return {+ jws,+ cartMandate: decodeFromClaims(claims, {+ jti: mandateId,+ sub: intentMandate.subjectAgentId,+ iat: nowSec,+ exp: nowSec + ttl,+ }),+ };+}++/**+ * Verify a Cart Mandate's signature, expiry, type, and — critically — that its+ * body still hashes to the signed hash (tamper detection). Optionally assert it+ * was issued under a specific Intent Mandate.+ *+ * @param {string} jws+ * @param {{ expectedIntentMandateId?: string }} [opts]+ * @returns {Promise<object>} decoded cart mandate+ */+export async function verifyCartMandate(jws, { expectedIntentMandateId } = {}) {+ if (!jws || typeof jws !== 'string') {+ throw new MandateError('invalid_cart_mandate', 'cart mandate (compact JWS) is required', 400);+ }+ let payload;+ try {+ ({ payload } = await jose.jwtVerify(jws, secretKey(), {+ issuer: env.APP_ORIGIN,+ algorithms: ['HS256'],+ }));+ } catch (err) {+ const expired = err?.code === 'ERR_JWT_EXPIRED';+ throw new MandateError(+ expired ? 'cart_mandate_expired' : 'invalid_cart_mandate',+ expired ? 'cart mandate has expired' : `cart mandate verification failed: ${err.message}`,+ 401,+ );+ }+ if (payload.typ !== CART_MANDATE_TYPE) {+ throw new MandateError('invalid_cart_mandate', 'not a cart mandate', 401);+ }++ const mandate = decodeFromClaims(payload, {+ jti: payload.jti,+ sub: payload.sub,+ iat: payload.iat,+ exp: payload.exp,+ });++ // Recompute the hash from the signed body: a valid signature over a tampered+ // `c` (impossible with a shared secret, but verify defensively) is rejected.+ const recomputed = await cartHash({+ resource: mandate.resource,+ amountAtomics: mandate.amountAtomics,+ currency: mandate.currency,+ network: mandate.network,+ taskId: mandate.taskId,+ items: mandate.items,+ });+ if (recomputed !== mandate.hash) {+ throw new MandateError('cart_hash_mismatch', 'cart mandate body does not match its hash', 401);+ }++ if (expectedIntentMandateId && mandate.intentMandateId !== expectedIntentMandateId) {+ throw new MandateError(+ 'intent_mismatch',+ 'cart mandate was not issued under the expected intent mandate',+ 401,+ );+ }++ return mandate;+}++/**+ * Assert a Cart Mandate authorizes exactly the payment about to settle. Used as a+ * defensive check before forwarding settlement, and by any third party verifying+ * that a presented cart matches what they were asked to fulfill.+ *+ * @param {object} opts+ * @param {object} opts.cartMandate Decoded, verified cart mandate.+ * @param {string|number|bigint} opts.amountAtomics+ * @param {string} opts.network+ * @param {string} opts.resource+ * @param {string} [opts.currency]+ */+export function assertCartMatchesPayment({ cartMandate, amountAtomics, network, resource, currency }) {+ if (!cartMandate || typeof cartMandate !== 'object') {+ throw new MandateError('invalid_cart_mandate', 'cart mandate is required', 400);+ }+ if (BigInt(cartMandate.amountAtomics) !== toPositiveAtomics(amountAtomics, 'amount')) {+ throw new MandateError('cart_amount_mismatch', 'payment amount does not match the cart', 402);+ }+ if (network && cartMandate.network && network !== cartMandate.network) {+ throw new MandateError('cart_network_mismatch', 'payment network does not match the cart', 402);+ }+ if (resource && cartMandate.resource && resource !== cartMandate.resource) {+ throw new MandateError('cart_resource_mismatch', 'payment resource does not match the cart', 402);+ }+ if (currency && cartMandate.currency && currency !== cartMandate.currency) {+ throw new MandateError('cart_currency_mismatch', 'payment currency does not match the cart', 402);+ }+}diff --git a/api/_lib/execution-engine.js b/api/_lib/execution-engine.jsindex cac1431bc..8bd3d5ebc 100644--- a/api/_lib/execution-engine.js+++ b/api/_lib/execution-engine.js@@ -373,7 +373,12 @@ export async function submitProtected({ network, connection, payer, instructions// instruction of the same kind makes the runtime reject the whole transaction.// No-op for the trade path (passes none); lets migrated send paths hand us their// raw instructions untouched without each having to remember to drop their own.- const userIxs = instructions.filter((ix) => !ix.programId.equals(ComputeBudgetProgram.programId));+ const computeBudgetId = ComputeBudgetProgram.programId.toBase58();+ const userIxs = instructions.filter((ix) => {+ const pid = ix?.programId;+ const id = typeof pid?.toBase58 === 'function' ? pid.toBase58() : String(pid ?? '');+ return id !== computeBudgetId;+ });const t0 = Date.now();// 1. Data-driven compute budget. Estimate the priority fee and the CU limit indiff --git a/api/_lib/migrations/20260621190000_skill_pwyw_pricing.sql b/api/_lib/migrations/20260621190000_skill_pwyw_pricing.sqlnew file mode 100644index 000000000..46fb6caaf--- /dev/null+++ b/api/_lib/migrations/20260621190000_skill_pwyw_pricing.sql@@ -0,0 +1,37 @@+-- Migration: "Pay What You Want" (PWYW) skill pricing.+--+-- Adds two columns to agent_skill_prices so a creator can mark a skill as+-- PWYW instead of fixed-price:+-- • pricing_type — 'fixed' (default, unchanged behavior) or 'pwyw'.+-- • minimum_amount — atomic-units floor for a PWYW purchase (nullable; NULL or+-- 0 means "any amount, including free + a tip"). Ignored+-- for fixed-price skills, where `amount` is authoritative.+--+-- For a PWYW skill, agent_skill_prices.amount remains the SUGGESTED price the+-- buyer UI pre-fills; the actual charged amount is the buyer-chosen value+-- snapshotted onto skill_purchases.amount at create time and verified on-chain at+-- confirm — the existing fee/referral/revenue math already keys off that snapshot,+-- so it bills exactly what the buyer paid.+--+-- Idempotent. Migration-only — schema.sql is left untouched per repo policy.+begin;++alter table agent_skill_prices+ add column if not exists pricing_type text not null default 'fixed',+ add column if not exists minimum_amount bigint;++-- Constrain pricing_type to the known set. Added separately + guarded so the+-- migration is safe to re-run and won't fail if the constraint already exists.+do $$+begin+ if not exists (+ select 1 from pg_constraint+ where conname = 'agent_skill_prices_pricing_type_chk'+ ) then+ alter table agent_skill_prices+ add constraint agent_skill_prices_pricing_type_chk+ check (pricing_type in ('fixed', 'pwyw'));+ end if;+end $$;++commit;diff --git a/api/_lib/services/MonetizationService.js b/api/_lib/services/MonetizationService.jsindex 4b9bbbc0b..b706ab6a5 100644--- a/api/_lib/services/MonetizationService.js+++ b/api/_lib/services/MonetizationService.js@@ -81,7 +81,8 @@ export class MonetizationService {async getSkillPricesForAgent(agentId) {return this.sql`SELECT skill, amount, currency_mint, chain, mint_decimals,- trial_uses, time_pass_hours, time_pass_amount+ trial_uses, time_pass_hours, time_pass_amount,+ pricing_type, minimum_amountFROM agent_skill_pricesWHERE agent_id = ${agentId} AND is_active = trueORDER BY skill@@ -111,10 +112,13 @@ export class MonetizationService {...prices.map((p) => this.sql`INSERT INTO agent_skill_prices- (agent_id, skill, amount, currency_mint, chain, is_active, trial_uses, time_pass_hours, time_pass_amount)+ (agent_id, skill, amount, currency_mint, chain, is_active, trial_uses,+ time_pass_hours, time_pass_amount, pricing_type, minimum_amount)VALUES(${agentId}, ${p.skill}, ${p.amount}, ${p.currency_mint}, ${p.chain}, true,- ${p.trial_uses ?? 0}, ${p.time_pass_hours ?? null}, ${p.time_pass_amount ?? null})+ ${p.trial_uses ?? 0}, ${p.time_pass_hours ?? null}, ${p.time_pass_amount ?? null},+ ${p.pricing_type === 'pwyw' ? 'pwyw' : 'fixed'},+ ${p.pricing_type === 'pwyw' ? (p.minimum_amount ?? 0) : null})ON CONFLICT (agent_id, skill) DO UPDATE SETamount = EXCLUDED.amount,currency_mint = EXCLUDED.currency_mint,@@ -123,6 +127,8 @@ export class MonetizationService {trial_uses = EXCLUDED.trial_uses,time_pass_hours = EXCLUDED.time_pass_hours,time_pass_amount = EXCLUDED.time_pass_amount,+ pricing_type = EXCLUDED.pricing_type,+ minimum_amount = EXCLUDED.minimum_amount,updated_at = now()`,),@@ -158,7 +164,7 @@ export class MonetizationService {* @param {string|null} [opts.referrerUserId] - resolved referrer (handler reads the request).* @param {string|null} [opts.recipientUserId] - gift beneficiary (resolved by the handler).*/- async preparePurchaseTransaction(agentId, skillName, { durationHours = null, referrerUserId = null, recipientUserId = null } = {}) {+ async preparePurchaseTransaction(agentId, skillName, { durationHours = null, referrerUserId = null, recipientUserId = null, payAmount = null } = {}) {this.requireAuth();const isGift = !!recipientUserId && recipientUserId !== this.userId;@@ -168,12 +174,15 @@ export class MonetizationService {const beneficiaryId = isGift ? recipientUserId : this.userId;const [price] = await this.sql`- SELECT amount, currency_mint, chain, mint_decimals, trial_uses, time_pass_hours, time_pass_amount+ SELECT amount, currency_mint, chain, mint_decimals, trial_uses,+ time_pass_hours, time_pass_amount, pricing_type, minimum_amountFROM agent_skill_pricesWHERE agent_id = ${agentId} AND skill = ${skillName} AND is_active = true`;if (!price) throw svcError(404, 'not_found', 'this skill is not for sale');+ const isPwyw = price.pricing_type === 'pwyw';+const payoutAddress = await resolvePayoutAddress(agentId, price.chain);if (!payoutAddress) {throw svcError(412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');@@ -227,9 +236,23 @@ export class MonetizationService {`;// Time-pass: prefer an explicit duration, else the skill's configured window.- const effectiveDurationHours = durationHours ?? (price.time_pass_hours || null);+ // PWYW is a permanent-purchase pricing mode and takes precedence over the+ // time-pass path — a buyer who names their own price is buying the skill+ // outright, not renting a window.+ const effectiveDurationHours = isPwyw ? null : (durationHours ?? (price.time_pass_hours || null));const isTimePass = effectiveDurationHours != null;- const purchaseAmount = isTimePass && price.time_pass_amount ? price.time_pass_amount : price.amount;++ // Resolve the amount the buyer will be charged. Fixed skills bill the+ // listed price (or the time-pass price). PWYW skills bill the buyer-chosen+ // `payAmount`, validated against the configured minimum and a sane ceiling.+ let purchaseAmount;+ if (isPwyw) {+ purchaseAmount = this.resolvePwywAmount(payAmount, price);+ } else if (isTimePass && price.time_pass_amount) {+ purchaseAmount = price.time_pass_amount;+ } else {+ purchaseAmount = price.amount;+ }const purchaseKind = isTimePass ? 'time_pass' : 'purchase';// Platform fee (Solana only — the split is one atomic SPL transfer the buyer@@ -272,6 +295,22 @@ export class MonetizationService {`;row = inserted;await logEvent(row.reference, 'created', { agent_id: agentId, skill: skillName, kind: purchaseKind, gift: isGift });+ } else if (isPwyw && BigInt(pending.amount) !== BigInt(purchaseAmount)) {+ // PWYW: the buyer changed their chosen amount on a retry. Re-sync the+ // reused pending row (and its persisted fee split) so the quote — and the+ // on-chain amount confirm verifies against — match the NEW amount.+ const [resynced] = await this.sql`+ UPDATE skill_purchases+ SET amount = ${purchaseAmount},+ platform_fee_amount = ${platformFeeAmount.toString()},+ platform_fee_wallet = ${platformFeeWallet},+ expires_at = now() + interval '30 minutes'+ WHERE reference = ${pending.reference} AND status = 'pending'+ RETURNING reference, amount, currency_mint, chain, expires_at, valid_until,+ platform_fee_amount, platform_fee_wallet+ `;+ row = resynced ?? pending;+ await logEvent(pending.reference, 'pwyw_amount_updated', { agent_id: agentId, skill: skillName, amount: String(purchaseAmount) });} else {await logEvent(pending.reference, 'create_idempotent_hit', { agent_id: agentId, skill: skillName });}@@ -309,12 +348,79 @@ export class MonetizationService {...feeBlock,...(isGift ? { is_gift: true, gift_recipient_id: recipientUserId } : {}),...(isTimePass ? { duration_hours: effectiveDurationHours } : {}),- ...(price.time_pass_hours+ ...(price.time_pass_hours && !isPwyw? { time_pass_hours: price.time_pass_hours, time_pass_amount: price.time_pass_amount }: {}),+ ...(isPwyw+ ? {+ pricing_type: 'pwyw',+ minimum_amount: String(price.minimum_amount ?? 0),+ suggested_amount: String(price.amount),+ }+ : {}),};}+ /**+ * Validate and normalize a buyer-supplied "pay what you want" amount against a+ * PWYW skill's price row. Returns the atomic-units amount to charge.+ *+ * Rules:+ * • Must be a finite, non-negative integer in atomic units.+ * • Must be ≥ the configured `minimum_amount` (NULL/0 means no floor).+ * • Must not exceed a sane ceiling (1,000,000 whole tokens, scaled by the+ * mint's decimals) — a guard against fat-finger / overflow inputs, not a+ * business cap.+ * • Omitted (`null`) defaults to the suggested price (`amount`) only when+ * that already satisfies the minimum; otherwise the buyer must choose.+ *+ * @param {string|number|bigint|null} payAmount - buyer-chosen atomic amount.+ * @param {{amount:any, minimum_amount:any, mint_decimals:number}} price+ * @returns {bigint} amount in atomic units to charge+ * @throws 400 invalid_amount / amount_below_minimum / amount_too_large+ */+ resolvePwywAmount(payAmount, price) {+ const minimum = price.minimum_amount == null ? 0n : BigInt(price.minimum_amount);+ const decimals = Number(price.mint_decimals ?? 6);+ const ceiling = 1_000_000n * 10n ** BigInt(Number.isFinite(decimals) ? decimals : 6);++ let chosen;+ if (payAmount == null || payAmount === '') {+ // No explicit amount — fall back to the suggested price if it clears the+ // minimum; otherwise require the buyer to name a figure.+ const suggested = BigInt(price.amount ?? 0);+ if (suggested < minimum) {+ throw svcError(400, 'invalid_amount', 'choose how much to pay for this skill');+ }+ chosen = suggested;+ } else {+ let parsed;+ try {+ // Reject decimals / non-integers up front: atomic units are whole.+ const s = String(payAmount).trim();+ if (!/^\d+$/.test(s)) throw new Error('not an integer');+ parsed = BigInt(s);+ } catch {+ throw svcError(400, 'invalid_amount', 'amount must be a whole number of atomic units');+ }+ chosen = parsed;+ }++ if (chosen < 0n) throw svcError(400, 'invalid_amount', 'amount cannot be negative');+ if (chosen < minimum) {+ throw svcError(400, 'amount_below_minimum', 'amount is below this skill’s minimum');+ }+ // A purchase must move value: a zero-amount "purchase" can't be verified+ // on-chain. A creator who wants a free skill should not list a price at all.+ if (chosen === 0n) {+ throw svcError(400, 'invalid_amount', 'amount must be greater than zero');+ }+ if (chosen > ceiling) {+ throw svcError(400, 'amount_too_large', 'amount exceeds the maximum allowed');+ }+ return chosen;+ }+/*** Confirm a pending purchase the current user owns, identified by its* Solana-Pay reference. Solana scans the chain by reference; EVM settles by adiff --git a/api/_lib/skill-price-cache.js b/api/_lib/skill-price-cache.jsindex c1ac7f2d4..d6902b631 100644--- a/api/_lib/skill-price-cache.js+++ b/api/_lib/skill-price-cache.js@@ -33,7 +33,8 @@ function keyFor(agentId) {async function loadFromDb(agentId) {return sql`SELECT skill, amount, currency_mint, chain, mint_decimals,- trial_uses, time_pass_hours, time_pass_amount+ trial_uses, time_pass_hours, time_pass_amount,+ pricing_type, minimum_amountFROM agent_skill_pricesWHERE agent_id = ${agentId} AND is_active = true`;@@ -103,6 +104,8 @@ export function skillPriceMap(rows) {trial_uses: p.trial_uses ?? 0,time_pass_hours: p.time_pass_hours ?? null,time_pass_amount: p.time_pass_amount ?? null,+ pricing_type: p.pricing_type === 'pwyw' ? 'pwyw' : 'fixed',+ minimum_amount: p.minimum_amount == null ? null : String(p.minimum_amount),};}return map;diff --git a/api/_lib/solana-wallet.js b/api/_lib/solana-wallet.jsindex ea44b804d..e3f63651f 100644--- a/api/_lib/solana-wallet.js+++ b/api/_lib/solana-wallet.js@@ -25,6 +25,11 @@ export async function loadWallet(encryptedSecret) {return tx;}+ // NOT routed through submitProtected: this is a generic signer used by signing+ // skills (pump-fun-trade, jupiter-swap) that hand us an already-built tx, not+ // raw instructions — so the instruction-rebuilding protected sender doesn't+ // apply. We broadcast the caller's tx and confirm via confirmOrThrow (a revert+ // throws). Skills that DO have instructions should prefer submitProtected.async function sendAndConfirm(tx, conn) {signTransaction(tx);const raw = tx.serialize();diff --git a/api/_lib/token/buyback.js b/api/_lib/token/buyback.jsindex 23dbabd22..864b1f2c4 100644--- a/api/_lib/token/buyback.js+++ b/api/_lib/token/buyback.js@@ -213,6 +213,11 @@ export async function executeBuyback(signer, plan) {const payer = signer.publicKey;// 1) Buy: deserialize Jupiter's tx, sign as the buyer, broadcast, confirm.+ // NOT routed through submitProtected: Jupiter returns a fully-built tx tied to+ // its own quote, blockhash, and CU/priority-fee layout — rebuilding it from+ // instructions (what submitProtected does) would invalidate the quote. We sign+ // and broadcast the SDK's bytes as-is and confirm via confirmOrThrow (a revert+ // throws). The sweep that follows IS a plain transfer, so it uses submitProtected.const swapB64 = await jupiterSwapTx(plan.quote, payer.toBase58());const buyTx = VersionedTransaction.deserialize(Buffer.from(swapB64, 'base64'));buyTx.sign([signer]);diff --git a/api/agents/[id]/skills-pricing.js b/api/agents/[id]/skills-pricing.jsindex b2fbc2199..21bdd28f6 100644--- a/api/agents/[id]/skills-pricing.js+++ b/api/agents/[id]/skills-pricing.js@@ -4,15 +4,24 @@ import { requireCsrf } from '../../_lib/csrf.js';import { MonetizationService } from '../../_lib/services/MonetizationService.js';import { z } from 'zod';-const priceSchema = z.object({- skill: z.string().trim().min(1).max(100),- amount: z.number().int().min(1),- currency_mint: z.string().trim().min(1).max(100),- chain: z.string().trim().min(1).max(20),- trial_uses: z.number().int().min(0).max(10).default(0),- time_pass_hours: z.number().int().min(1).max(720).nullable().optional(),- time_pass_amount: z.number().int().min(1).nullable().optional(),-});+const priceSchema = z+ .object({+ skill: z.string().trim().min(1).max(100),+ amount: z.number().int().min(1),+ currency_mint: z.string().trim().min(1).max(100),+ chain: z.string().trim().min(1).max(20),+ trial_uses: z.number().int().min(0).max(10).default(0),+ time_pass_hours: z.number().int().min(1).max(720).nullable().optional(),+ time_pass_amount: z.number().int().min(1).nullable().optional(),+ // Pay-what-you-want: 'fixed' (default) bills `amount`; 'pwyw' lets the buyer+ // name an amount at or above `minimum_amount` (atomic units, 0 = no floor).+ pricing_type: z.enum(['fixed', 'pwyw']).default('fixed'),+ minimum_amount: z.number().int().min(0).nullable().optional(),+ })+ .refine((p) => p.pricing_type !== 'pwyw' || (p.minimum_amount ?? 0) <= p.amount, {+ message: 'minimum cannot exceed the suggested amount',+ path: ['minimum_amount'],+ });const pricingUpdateSchema = z.object({prices: z.array(priceSchema),diff --git a/api/agents/a2a-call.js b/api/agents/a2a-call.jsindex 02f94e20e..5698cbcb8 100644--- a/api/agents/a2a-call.js+++ b/api/agents/a2a-call.js@@ -24,6 +24,7 @@ import { limits } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';import { assertMandateAllows, MandateError, verifyIntentMandate } from '../_lib/a2a/mandate.js';+import { issueCartMandate } from '../_lib/a2a/cart-mandate.js';import { release, reserve } from '../_lib/a2a/spend-ledger.js';import { assertReputationOk, ReputationError } from '../_lib/a2a/reputation-gate.js';import {@@ -205,6 +206,31 @@ export default wrap(async (req, res) => {);}+ // ── Cart Mandate: sign the exact transaction (AP2 per-tx approval) ──────+ // Bound to the intent mandate + the precise cart, this is the non-repudiable+ // record of WHAT was paid. Issued before settlement so it accompanies the+ // payment and is returned to the caller as a verifiable receipt.+ const cartCurrency = currencyOf(accept) || null;+ let cartMandateJws = null;+ let cartMandate = null;+ try {+ ({ jws: cartMandateJws, cartMandate } = await issueCartMandate({+ intentMandate: mandate,+ cart: {+ resource: safeEndpoint,+ amountAtomics: amount,+ currency: cartCurrency || mandate.currency,+ network,+ taskId: quote.taskId,+ items: [{ name: text, amountAtomics: amount }],+ },+ }));+ } catch (err) {+ await release(mandate.mandateId, amount);+ if (err instanceof MandateError) return respondError(res, err.status, err.code, err);+ throw err;+ }+try {const resource = quote.required.resource || { url: safeEndpoint, mimeType: 'application/json' };let signer;@@ -245,10 +271,14 @@ export default wrap(async (req, res) => {task_id: quote.taskId,amount,network,- currency: currencyOf(accept) || null,+ currency: cartCurrency,payer: payerAddress,spent: reservation.spent,cap: reservation.cap,+ // AP2 Cart Mandate: a signed, independently-verifiable proof of this exact+ // transaction (verify via POST /api/agents/a2a-cart-verify).+ cart_mandate: cartMandateJws,+ cart: cartMandate,receipts: result.receipts || [],artifacts,});diff --git a/api/agents/a2a-cart-verify.js b/api/agents/a2a-cart-verify.jsnew file mode 100644index 000000000..e5983e570--- /dev/null+++ b/api/agents/a2a-cart-verify.js@@ -0,0 +1,54 @@+// POST /api/agents/a2a-cart-verify — verify a Cart Mandate.+//+// Cart Mandates are signed HS256 with the platform's mandate secret (three.ws is+// the mandate authority), so a peer or merchant that receives one can't verify it+// alone — they present it here. We check the signature, expiry, type, and that the+// cart body still hashes to the signed hash, then return the decoded cart. The+// caller can pass `expected` constraints to assert the mandate authorizes exactly+// the transaction they were asked to fulfill, in one round-trip.+//+// No auth: this is a public verification utility over a self-contained token; it+// reveals nothing the token holder doesn't already possess. Rate-limited.++import { cors, json, method, rateLimited, readJson, respondError, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { MandateError } from '../_lib/a2a/mandate.js';+import { assertCartMatchesPayment, verifyCartMandate } from '../_lib/a2a/cart-mandate.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.mcpAgent(clientIp(req) || 'anon');+ if (!rl.success) return rateLimited(res, rl, 'cart verify rate limit exceeded');++ const body = await readJson(req);+ const { cartMandate: jws, expectedIntentMandateId, expected } = body || {};++ try {+ const cartMandate = await verifyCartMandate(jws, { expectedIntentMandateId });++ // Optional: assert the cart authorizes exactly the payment the verifier+ // expects (amount/network/resource/currency).+ if (expected && typeof expected === 'object') {+ assertCartMatchesPayment({+ cartMandate,+ amountAtomics: expected.amountAtomics,+ network: expected.network,+ resource: expected.resource,+ currency: expected.currency,+ });+ }++ return json(res, 200, { ok: true, valid: true, cart: cartMandate });+ } catch (err) {+ if (err instanceof MandateError) {+ // A failed verification is a normal, expected outcome — report it as a+ // structured 200 so callers can branch on `valid` without try/catch,+ // except for misconfiguration (500) which is a real server fault.+ if (err.status === 500) return respondError(res, 500, err.code, err);+ return json(res, 200, { ok: true, valid: false, code: err.code, reason: err.message });+ }+ throw err;+ }+});diff --git a/api/agents/talk.js b/api/agents/talk.jsindex f6b291891..a03a485de 100644--- a/api/agents/talk.js+++ b/api/agents/talk.js@@ -22,6 +22,7 @@ import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/import { limits, clientIp } from '../_lib/rate-limit.js';import { normalizeLegacyPolicy } from '../_lib/embed-policy.js';import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';+import { hasSkillAccess } from '../_lib/skill-access.js';import { isUuid } from '../_lib/validate.js';const ALLOWED_MODELS = new Set([@@ -37,6 +38,53 @@ const bodySchema = z.object({model: z.string().min(1).max(100).optional(),});+// Build the agent's skill_ownership context for one requesting user. Every skill+// the agent declares is classified as premium (priced + active in+// agent_skill_prices) or free; for premium skills we resolve the caller's real+// access via hasSkillAccess (purchase / subscription / trial). Anonymous callers+// (userId === null) own no premium skill. Returns a compact, structured prompt+// section, or null when the agent has no skills worth describing.+async function buildSkillOwnershipBlock(agent, userId) {+ const skills = Array.isArray(agent.skills) ? agent.skills.filter(Boolean) : [];+ if (skills.length === 0) return null;++ // One query for all of this agent's active prices, then classify in memory —+ // avoids a per-skill price lookup. hasSkillAccess re-checks the price row, but+ // only for skills we already know are premium.+ const priceRows = await sql`+ SELECT skill FROM agent_skill_prices+ WHERE agent_id = ${agent.id} AND is_active = true+ `;+ const pricedSkills = new Set(priceRows.map((r) => r.skill));++ const ownership = {};+ for (const skill of skills) {+ if (!pricedSkills.has(skill)) {+ ownership[skill] = { is_premium: false, is_owned: true };+ continue;+ }+ if (!userId) {+ ownership[skill] = { is_premium: true, is_owned: false };+ continue;+ }+ const access = await hasSkillAccess(userId, agent.id, skill);+ ownership[skill] = { is_premium: true, is_owned: Boolean(access.owned) };+ }++ const hasPremium = Object.values(ownership).some((o) => o.is_premium);+ if (!hasPremium) return null; // nothing to monetize — keep the prompt lean.++ return [+ '## Skill access (current user)',+ 'The JSON below maps each of your skills to whether it is premium (paid) and whether THIS user has already unlocked it:',+ JSON.stringify(ownership),+ 'Behaviour rules:',+ '- Use any skill where is_owned is true freely, without mentioning payment.',+ '- If the user asks to use a skill where is_premium is true and is_owned is false, do NOT perform it. Politely explain it is a paid skill and invite them to unlock it from your agent profile page, then offer the free skills you can do instead.',+ '- Never invent prices, never reveal another user\'s access, and never claim a skill is unlocked when is_owned is false.',+ ].join('\n');+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: false })) return;if (!method(req, res, ['POST'])) return;@@ -50,6 +98,7 @@ export default wrap(async (req, res) => {const session = await getSessionUser(req);const principal = session ?? (await authenticateBearer(extractBearer(req)));if (!principal) return error(res, 401, 'unauthorized', 'sign in required');+ const userId = session?.id ?? principal?.userId ?? null;const rl = await limits.agentDelegate(clientIp(req));if (!rl.success) return rateLimited(res, rl, 'agent delegate rate limit');@@ -76,7 +125,7 @@ export default wrap(async (req, res) => {if (!isUuid(agentId)) return error(res, 404, 'agent_not_found', 'agent not found');const [agent] = await sql`- SELECT id, name, description, embed_policy, meta+ SELECT id, name, description, embed_policy, meta, skillsFROM agent_identitiesWHERE id = ${agentId} AND deleted_at IS NULL`;@@ -91,10 +140,16 @@ export default wrap(async (req, res) => {const model =requestedModel && ALLOWED_MODELS.has(requestedModel) ? requestedModel : defaultModel;- const systemPrompt =+ const basePrompt =agent.meta?.brain?.instructions ||`You are ${agent.name}. ${agent.description || ''}`.trim();+ // Real per-user skill-ownership context: lets the agent know which of its+ // skills are premium and whether THIS caller has already unlocked them, so it+ // can use owned skills freely and offer to sell the ones the user lacks.+ const ownershipBlock = await buildSkillOwnershipBlock(agent, userId);+ const systemPrompt = ownershipBlock ? `${basePrompt}\n\n${ownershipBlock}` : basePrompt;+const started = Date.now();let result;try {diff --git a/api/marketplace/purchase.js b/api/marketplace/purchase.jsindex 1cceec0ee..85cb80395 100644--- a/api/marketplace/purchase.js+++ b/api/marketplace/purchase.js@@ -84,6 +84,17 @@ async function handleCreate(req, res) {if (!agentId || !skill) {return error(res, 400, 'validation_error', 'agent_id and skill required');}+ // Pay-what-you-want: the buyer may name an amount (atomic units). Accepted as a+ // number or numeric string; the service validates it against the skill's+ // minimum + a ceiling, and ignores it for fixed-price skills.+ let payAmount = null;+ if (body?.pay_amount != null && body.pay_amount !== '') {+ const raw = typeof body.pay_amount === 'number' ? Math.trunc(body.pay_amount) : String(body.pay_amount).trim();+ if (!/^\d+$/.test(String(raw))) {+ return error(res, 400, 'validation_error', 'pay_amount must be a whole number of atomic units');+ }+ payAmount = String(raw);+ }// Optional: when the browser wallet is already connected it passes its// pubkey so we can return a platform-sponsored (gasless) transaction.const buyerPublicKey =@@ -119,7 +130,7 @@ async function handleCreate(req, res) {const service = new MonetizationService(auth);let result;try {- result = await service.preparePurchaseTransaction(agentId, skill, { durationHours, referrerUserId, recipientUserId });+ result = await service.preparePurchaseTransaction(agentId, skill, { durationHours, referrerUserId, recipientUserId, payAmount });} catch (e) {if (e.status) return error(res, e.status, e.code, e.message);throw e;diff --git a/src/agent-edit.js b/src/agent-edit.jsindex f3bb29b3a..baf4a22b1 100644--- a/src/agent-edit.js+++ b/src/agent-edit.js@@ -214,6 +214,11 @@ function renderMonetization() {const isPaid = !!price;const amount = isPaid ? (price.amount / 1e6).toFixed(2) : '';const trialUses = isPaid ? (price.trial_uses ?? 0) : 0;+ const pricingType = isPaid && price.pricing_type === 'pwyw' ? 'pwyw' : 'fixed';+ const isPwyw = pricingType === 'pwyw';+ const minimum = isPwyw && price.minimum_amount != null+ ? (Number(price.minimum_amount) / 1e6).toFixed(2)+ : '';return `<div class="skill-item" data-skill-name="${escapeHtml(skillName)}">@@ -223,13 +228,31 @@ function renderMonetization() {<input type="checkbox" class="price-toggle" ${isPaid ? 'checked' : ''}><span class="slider"></span></label>- <div class="price-input-wrapper" style="display: ${isPaid ? 'flex' : 'none'}; align-items:center; gap:8px;">- <input type="number" class="price-input" min="0" step="0.01" placeholder="0.50" value="${amount}">- <span>USDC</span>- <label style="font-size:12px;color:#a1a1aa;margin-left:8px;white-space:nowrap">- Free trials:- <input type="number" class="trial-uses-input" min="0" max="10" step="1" placeholder="0" value="${trialUses}" style="width:52px;margin-left:4px">- </label>+ <div class="price-input-wrapper" style="display: ${isPaid ? 'flex' : 'none'}; flex-direction:column; align-items:flex-start; gap:8px;">+ <div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap;">+ <label class="pricing-type-field" style="font-size:12px;color:#a1a1aa;white-space:nowrap">+ Pricing:+ <select class="pricing-type-select" aria-label="Pricing model for ${escapeHtml(skillName)}" style="margin-left:4px">+ <option value="fixed" ${isPwyw ? '' : 'selected'}>Fixed price</option>+ <option value="pwyw" ${isPwyw ? 'selected' : ''}>Pay what you want</option>+ </select>+ </label>+ </div>+ <div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap;">+ <label class="price-field" style="display:flex;align-items:center;gap:6px">+ <span class="price-field-label" style="font-size:12px;color:#a1a1aa;white-space:nowrap">${isPwyw ? 'Suggested:' : 'Price:'}</span>+ <input type="number" class="price-input" min="0" step="0.01" placeholder="0.50" value="${amount}" aria-label="${isPwyw ? 'Suggested' : 'Price'} for ${escapeHtml(skillName)} in USDC">+ </label>+ <label class="min-field" style="display:${isPwyw ? 'flex' : 'none'};align-items:center;gap:6px">+ <span style="font-size:12px;color:#a1a1aa;white-space:nowrap">Minimum:</span>+ <input type="number" class="min-amount-input" min="0" step="0.01" placeholder="0.00" value="${minimum}" aria-label="Minimum amount for ${escapeHtml(skillName)} in USDC">+ </label>+ <span>USDC</span>+ <label style="font-size:12px;color:#a1a1aa;margin-left:8px;white-space:nowrap">+ Free trials:+ <input type="number" class="trial-uses-input" min="0" max="10" step="1" placeholder="0" value="${trialUses}" style="width:52px;margin-left:4px" aria-label="Free trial uses for ${escapeHtml(skillName)}">+ </label>+ </div></div></div></div>@@ -242,6 +265,19 @@ function renderMonetization() {wrapper.style.display = e.target.checked ? 'flex' : 'none';});});++ // Toggle the minimum-amount field + suggested/price label when the creator+ // switches a skill between Fixed and Pay-what-you-want.+ container.querySelectorAll('.pricing-type-select').forEach(select => {+ select.addEventListener('change', (e) => {+ const controls = e.target.closest('.price-input-wrapper');+ const minField = controls.querySelector('.min-field');+ const priceLabel = controls.querySelector('.price-field-label');+ const isPwyw = e.target.value === 'pwyw';+ if (minField) minField.style.display = isPwyw ? 'flex' : 'none';+ if (priceLabel) priceLabel.textContent = isPwyw ? 'Suggested:' : 'Price:';+ });+ });}function renderLaunchTokenState() {@@ -998,13 +1034,22 @@ $('monetization-save').addEventListener('click', async () => {if (Number.isNaN(parsed) || parsed <= 0) return;const trialInput = item.querySelector('.trial-uses-input');const trialUses = trialInput ? Math.max(0, Math.min(10, parseInt(trialInput.value || '0', 10) || 0)) : 0;- prices.push({+ const typeSelect = item.querySelector('.pricing-type-select');+ const pricingType = typeSelect && typeSelect.value === 'pwyw' ? 'pwyw' : 'fixed';+ const entry = {skill,amount: Math.round(parsed * 1e6),currency_mint: USDC_MINT,chain: 'solana',trial_uses: trialUses,- });+ pricing_type: pricingType,+ };+ if (pricingType === 'pwyw') {+ const minInput = item.querySelector('.min-amount-input');+ const minVal = minInput ? parseFloat(minInput.value || '0') : 0;+ entry.minimum_amount = Number.isNaN(minVal) || minVal < 0 ? 0 : Math.round(minVal * 1e6);+ }+ prices.push(entry);}});diff --git a/src/shared/skill-purchase.js b/src/shared/skill-purchase.jsindex cc580d067..8828083fe 100644--- a/src/shared/skill-purchase.js+++ b/src/shared/skill-purchase.js@@ -23,6 +23,7 @@*/import { log } from './log.js';+import { showToast } from '../ui-helpers.js';export const USDC_MAINNET_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';@@ -70,6 +71,16 @@ const MODAL_HTML = `<span>Total</span><strong id="payment-price-display"></strong></div>+ <div class="payment-pwyw" id="payment-pwyw-area" hidden>+ <label class="payment-pwyw-label" for="payment-pwyw-input">Name your price</label>+ <div class="payment-pwyw-row">+ <input type="number" id="payment-pwyw-input" class="payment-pwyw-input"+ inputmode="decimal" min="0" step="0.01"+ autocomplete="off" aria-describedby="payment-pwyw-hint" />+ <span class="payment-pwyw-unit" id="payment-pwyw-unit">USDC</span>+ </div>+ <div class="payment-pwyw-hint" id="payment-pwyw-hint" role="status" aria-live="polite"></div>+ </div><div class="payment-gift" id="payment-gift-area" hidden><label class="payment-gift-toggle"><input type="checkbox" id="payment-gift-toggle-input" />@@ -103,6 +114,7 @@ function ensureModal() {}$('payment-modal-close')?.addEventListener('click', closePaymentModal);$('payment-confirm-btn')?.addEventListener('click', handlePurchase);+ $('payment-pwyw-input')?.addEventListener('input', onPwywInput);$('payment-gift-toggle-input')?.addEventListener('change', onGiftToggle);$('payment-gift-input')?.addEventListener('input', onGiftInput);$('payment-modal-overlay')?.addEventListener('click', (e) => {@@ -212,6 +224,90 @@ function renderPaymentVerifyAgain({ txid, message, retryFn }) {// resolved user id to the server, which re-resolves and records it as the// purchase's recipient.+// ── Pay-what-you-want ─────────────────────────────────────────────────────────+//+// When a skill is priced PWYW the modal shows an amount input instead of a fixed+// total. The buyer types a human amount; we enforce the creator's minimum+// client-side (the server re-validates), gate the confirm button on a valid+// figure, and pass the chosen atomic amount to the purchase create call.++let pwywState = { active: false, decimals: 6, minAtomics: 0n, symbol: 'USDC' };++function setupPwywUI({ active, price }) {+ const area = $('payment-pwyw-area');+ const input = $('payment-pwyw-input');+ const unit = $('payment-pwyw-unit');+ if (!active) {+ pwywState = { active: false, decimals: 6, minAtomics: 0n, symbol: 'USDC' };+ if (area) area.hidden = true;+ setPwywHint('');+ return;+ }+ const decimals = Number(price.mint_decimals ?? 6);+ const minAtomics = price.minimum_amount != null ? BigInt(price.minimum_amount) : 0n;+ const symbol = shortMintLabel(price.currency_mint);+ pwywState = { active: true, decimals, minAtomics, symbol };+ const suggested = Number(price.amount) / Math.pow(10, decimals);+ if (input) input.value = suggested > 0 ? suggested.toFixed(decimals === 6 ? 2 : 4).replace(/\.?0+$/, '') : '';+ if (unit) unit.textContent = symbol;+ if (area) area.hidden = false;+ updatePwywHint();+}++function pwywMinHuman() {+ return Number(pwywState.minAtomics) / Math.pow(10, pwywState.decimals);+}++// Parse the input into atomic units; null when blank or non-numeric.+function pwywChosenAtomics() {+ const raw = ($('payment-pwyw-input')?.value || '').trim();+ if (!raw) return null;+ const human = Number(raw);+ if (!Number.isFinite(human) || human < 0) return null;+ return BigInt(Math.round(human * Math.pow(10, pwywState.decimals)));+}++function setPwywHint(text, kind) {+ const el = $('payment-pwyw-hint');+ if (!el) return;+ el.textContent = text || '';+ el.className = 'payment-pwyw-hint' + (kind ? ' ' + kind : '');+}++function updatePwywHint() {+ if (!pwywState.active) return;+ const chosen = pwywChosenAtomics();+ if (chosen == null) {+ setPwywHint(+ pwywState.minAtomics > 0n+ ? `Minimum ${pwywMinHuman()} ${pwywState.symbol}.`+ : `Enter how much you'd like to pay.`,+ );+ return;+ }+ if (chosen <= 0n) {+ setPwywHint('Enter an amount greater than zero.', 'err');+ return;+ }+ if (chosen < pwywState.minAtomics) {+ setPwywHint(`That's below the ${pwywMinHuman()} ${pwywState.symbol} minimum.`, 'err');+ return;+ }+ setPwywHint(`You'll pay ${(Number(chosen) / Math.pow(10, pwywState.decimals))} ${pwywState.symbol}.`, 'ok');+}++function onPwywInput() {+ updatePwywHint();+ refreshConfirmEnabled();+}++// Is the current PWYW amount valid? Trivially true when not in PWYW mode.+function pwywAmountValid() {+ if (!pwywState.active) return true;+ const chosen = pwywChosenAtomics();+ return chosen != null && chosen > 0n && chosen >= pwywState.minAtomics;+}+let giftState = { enabled: false, active: false, recipient: null, resolving: false, seq: 0 };let giftLookupTimer = null;@@ -241,6 +337,7 @@ function refreshConfirmEnabled() {if (!btn) return;let enabled = !!connectedWallet;if (giftState.active && (!giftState.recipient || giftState.resolving)) enabled = false;+ if (!pwywAmountValid()) enabled = false;btn.disabled = !enabled;}@@ -346,6 +443,7 @@ function closePaymentModal() {if (success) { success.hidden = true; success.innerHTML = ''; }setPaymentBadge('');setStatus('');+ setupPwywUI({ active: false });setupGiftUI({ enabled: false });pendingAssetPurchase = null;pendingSubscription = null;@@ -542,7 +640,7 @@ async function sendPurchaseTransaction(purchase) {// ── Server purchase records ─────────────────────────────────────────────────-async function createPendingPurchase(agentId, skill, durationHours = null, buyerPublicKey = null, recipient = null) {+async function createPendingPurchase(agentId, skill, durationHours = null, buyerPublicKey = null, recipient = null, payAmountAtomics = null) {const body = { agent_id: agentId, skill };if (durationHours) body.duration_hours = durationHours;// Hand the server our wallet pubkey so it can return a gasless, pre-signed@@ -550,6 +648,10 @@ async function createPendingPurchase(agentId, skill, durationHours = null, buyerif (buyerPublicKey) body.buyer_public_key = buyerPublicKey;// Gift: the resolved recipient's user id; the server re-resolves + validates.if (recipient) body.recipient = recipient;+ // Pay-what-you-want: the buyer's chosen amount in atomic units. The server+ // validates it against the skill's minimum + ceiling and ignores it for+ // fixed-price skills.+ if (payAmountAtomics != null) body.pay_amount = String(payAmountAtomics);const r = await apiPostWithCsrf('/api/marketplace/purchase', body);const j = await r.json();if (!r.ok) throw new Error(j.error_description || j.error || 'Failed to create purchase');@@ -583,18 +685,32 @@ export async function openPurchaseFlow(agentId, skill) {const decimals = Number(price.mint_decimals ?? 6);const human = (Number(price.amount) / Math.pow(10, decimals)).toFixed(decimals === 6 ? 2 : 4);+ const isPwyw = price.pricing_type === 'pwyw';setPaymentTitle('Unlock skill');- setPaymentLede('You are purchasing permanent access to this skill:');+ setPaymentLede(isPwyw+ ? 'Choose how much to pay for permanent access to this skill:'+ : 'You are purchasing permanent access to this skill:');setPaymentFromLabel('on agent');setPaymentBadge('');$('payment-skill-name').textContent = skill;$('payment-agent-name').textContent = agent.name;- $('payment-price-display').textContent = `${human} ${shortMintLabel(price.currency_mint)}`;+ // For PWYW the amount input below carries the total, so the static "Total"+ // line shows the floor (or "Pay what you want") instead of a fixed figure.+ if (isPwyw) {+ const minAtomics = price.minimum_amount != null ? Number(price.minimum_amount) : 0;+ const minHuman = (minAtomics / Math.pow(10, decimals)).toString();+ $('payment-price-display').textContent = minAtomics > 0+ ? `From ${minHuman} ${shortMintLabel(price.currency_mint)}`+ : 'Pay what you want';+ } else {+ $('payment-price-display').textContent = `${human} ${shortMintLabel(price.currency_mint)}`;+ }const confirmBtn = $('payment-confirm-btn');if (confirmBtn) confirmBtn.textContent = 'Confirm purchase';const qr = $('payment-qr'); if (qr) qr.innerHTML = '';setStatus('');+ setupPwywUI({ active: isPwyw, price });setupGiftUI({ enabled: true });$('payment-modal-overlay').hidden = false;updateWalletUI();@@ -624,6 +740,7 @@ export async function openTimePassFlow(agentId, skill, durationHours, btn) {$('payment-price-display').textContent = `${human} ${shortMintLabel(price.currency_mint)}`;const qr = $('payment-qr'); if (qr) qr.innerHTML = '';setStatus('');+ setupPwywUI({ active: false });setupGiftUI({ enabled: true });$('payment-modal-overlay').hidden = false;updateWalletUI();@@ -643,15 +760,16 @@ export async function openTrialFlow(agentId, skill, btn) {const r = await apiPostWithCsrf('/api/marketplace/start-trial', { agent_id: agentId, skill });const j = await r.json().catch(() => ({}));if (!r.ok) {- if (j.error === 'already_owned') alert('You already own this skill.');- else if (j.error === 'trial_used') alert('You have already used the trial for this skill.');+ if (j.error === 'already_owned') showToast('You already own this skill.', { type: 'info' });+ else if (j.error === 'trial_used') showToast('You have already used the trial for this skill.', { type: 'warning' });else if (r.status === 401) { location.href = `/login?next=${encodeURIComponent(location.pathname)}`; return; }- else alert(j.error_description || j.error || 'Failed to start trial');+ else showToast(j.error_description || j.error || 'Failed to start trial', { type: 'error' });return;}await cfg.onPurchased(agentId);+ showToast(`Free trial of ${skill} started.`, { type: 'success' });} catch (err) {- alert(err.message || 'Failed to start trial');+ showToast(err.message || 'Failed to start trial', { type: 'error' });} finally {if (btn) { btn.disabled = false; btn.textContent = 'Try free'; }}@@ -691,6 +809,7 @@ export function openAssetPurchaseFlow(asset) {const qr = $('payment-qr'); if (qr) qr.innerHTML = '';setStatus('');+ setupPwywUI({ active: false });setupGiftUI({ enabled: false });$('payment-modal-overlay').hidden = false;updateWalletUI();@@ -745,10 +864,30 @@ async function handlePurchase() {// Snapshot the gift recipient at click time so a late keystroke can't change// who the in-flight purchase is for.const giftRecipient = activeGiftRecipient();+ // Snapshot the PWYW amount the same way — the figure in flight must be the one+ // the buyer saw when they clicked. Guarded by refreshConfirmEnabled (the button+ // is disabled until the amount clears the minimum), but re-checked here so a+ // programmatic call can't bypass it.+ let payAmountAtomics = null;+ if (pwywState.active) {+ const chosen = pwywChosenAtomics();+ if (!pwywAmountValid() || chosen == null) {+ confirmBtn.disabled = false;+ setStatus(+ pwywState.minAtomics > 0n+ ? `Enter at least ${pwywMinHuman()} ${pwywState.symbol}.`+ : 'Enter how much you want to pay.',+ 'err',+ );+ return;+ }+ payAmountAtomics = chosen.toString();+ }const onUnlocked = async () => {await cfg.onPurchased(agentId);if (giftRecipient) {+ showToast(`Gift sent to ${giftLabel(giftRecipient)} — ${skill} unlocked.`, { type: 'success' });renderPaymentSuccess({title: 'Gift sent 🎁',message: durationHours@@ -759,6 +898,10 @@ async function handlePurchase() {});return;}+ showToast(+ durationHours ? `${durationHours}h access to ${skill} unlocked.` : `${skill} unlocked.`,+ { type: 'success' },+ );renderPaymentSuccess({title: durationHours ? `${durationHours}h access unlocked` : 'Skill unlocked',message: durationHours@@ -771,7 +914,7 @@ async function handlePurchase() {let purchase;try {- purchase = await createPendingPurchase(agentId, skill, durationHours, connectedWallet.publicKey.toBase58(), giftRecipient?.id || null);+ purchase = await createPendingPurchase(agentId, skill, durationHours, connectedWallet.publicKey.toBase58(), giftRecipient?.id || null, payAmountAtomics);if (purchase.already_owned) {await cfg.onPurchased(agentId);renderPaymentSuccess({@@ -827,6 +970,7 @@ async function handlePurchase() {});return;}+ showToast(e.message || 'Purchase failed', { type: 'error' });setStatus(e.message || 'Purchase failed', 'err');confirmBtn.disabled = false;}@@ -872,6 +1016,7 @@ async function handleAssetPurchase() {const ok = await pollAssetConfirm(purchase.reference, 60_000);const succeed = () => {const target = assetViewTarget(asset);+ showToast(`${asset.label} purchased.`, { type: 'success' });renderPaymentSuccess({title: `${asset.label} purchased`,message: `${asset.item_type === 'avatar' ? 'Your new avatar' : asset.item_type === 'agent' ? 'Your new agent' : 'Your purchase'} is in your dashboard.`,@@ -903,6 +1048,7 @@ async function handleAssetPurchase() {const ok2 = await pollAssetConfirm(purchase.reference, 60_000);if (!ok2) throw new Error('Still not confirmed — wait a few seconds and try again.');const target = assetViewTarget(asset);+ showToast(`${asset.label} purchased.`, { type: 'success' });renderPaymentSuccess({title: `${asset.label} purchased`,message: `${asset.item_type === 'avatar' ? 'Your new avatar' : 'Your purchase'} is in your dashboard.`,@@ -913,6 +1059,7 @@ async function handleAssetPurchase() {});return;}+ showToast(e.message || 'Purchase failed', { type: 'error' });setStatus(e.message || 'Purchase failed', 'err');confirmBtn.disabled = false;}@@ -961,6 +1108,7 @@ export async function openSubscribeFlow(agentId, tier) {}const qr = $('payment-qr'); if (qr) qr.innerHTML = '';setStatus('');+ setupPwywUI({ active: false });setupGiftUI({ enabled: false });$('payment-modal-overlay').hidden = false;updateWalletUI();@@ -1020,6 +1168,7 @@ async function handleSubscription() {const succeed = () => {cfg.onPurchased(agentId).catch(() => {});+ showToast(`Subscribed to ${tier.name}.`, { type: 'success' });renderPaymentSuccess({title: `Subscribed to ${tier.name}`,message: `You now have access to ${agent?.name || 'this agent'}'s paid skills. Billed every ${cycle}.`,@@ -1075,6 +1224,7 @@ async function handleSubscription() {});return;}+ showToast(e.message || 'Subscription failed', { type: 'error' });setStatus(e.message || 'Subscription failed', 'err');confirmBtn.disabled = false;}@@ -1088,10 +1238,27 @@ async function startQrPurchase() {const skill = $('payment-skill-name').textContent;const giftRecipient = activeGiftRecipient();+ // PWYW over the mobile QR path: enforce the same amount validity before we+ // mint the Solana Pay reference, so the QR encodes the buyer-chosen amount.+ let payAmountAtomics = null;+ if (pwywState.active) {+ const chosen = pwywChosenAtomics();+ if (!pwywAmountValid() || chosen == null) {+ setStatus(+ pwywState.minAtomics > 0n+ ? `Enter at least ${pwywMinHuman()} ${pwywState.symbol}.`+ : 'Enter how much you want to pay.',+ 'err',+ );+ return;+ }+ payAmountAtomics = chosen.toString();+ }+setStatus('Creating purchase…');let purchase;try {- purchase = await createPendingPurchase(agentId, skill, null, null, giftRecipient?.id || null);+ purchase = await createPendingPurchase(agentId, skill, null, null, giftRecipient?.id || null, payAmountAtomics);if (purchase.already_owned) {await cfg.onPurchased(agentId);renderPaymentSuccess({@@ -1128,6 +1295,10 @@ async function startQrPurchase() {const qrSuccess = async () => {await cfg.onPurchased(agentId);+ showToast(+ giftRecipient ? `Gift sent to ${giftLabel(giftRecipient)} — ${skill} unlocked.` : `${skill} unlocked.`,+ { type: 'success' },+ );renderPaymentSuccess({title: giftRecipient ? 'Gift sent 🎁' : 'Skill unlocked',message: giftRecipientdiff --git a/src/ui-helpers.js b/src/ui-helpers.jsnew file mode 100644index 000000000..7a78fc382--- /dev/null+++ b/src/ui-helpers.js@@ -0,0 +1,316 @@+/**+ * Shared UI helpers — toast notifications.+ *+ * A single, self-contained toast system any page can import without shipping+ * markup or CSS: the fixed container and its styles are injected into the DOM on+ * first use, styled entirely from the design tokens in public/tokens.css so it+ * tracks the active theme (dark/light) automatically.+ *+ * Why a helper instead of per-page toasts: feedback for saves, payments, and+ * errors was previously ad-hoc — status text next to buttons, page-local toast+ * functions with divergent look and a11y. This is the one toast surface.+ *+ * API+ * ───+ * import { showToast } from './ui-helpers.js';+ *+ * showToast(message, options?) -> dismiss()+ *+ * message string — text shown to the user (rendered as text, never HTML).+ * options object — all optional:+ * type 'info' | 'success' | 'error' | 'warning' (default 'info')+ * duration number ms before auto-dismiss; 0 / Infinity = sticky+ * (default 4000; errors default 6000 so they're readable).+ * action { label: string, onClick: (dismiss) => void }+ * renders an inline action button (e.g. "Undo", "Retry").+ *+ * Returns a dismiss() function so callers can close a sticky toast manually.+ *+ * Behaviour+ * ─────────+ * · Stacked, newest on top, capped at MAX_TOASTS (oldest evicted first).+ * · Auto-dismiss with pause-on-hover and pause-on-focus-within, so a toast+ * under the pointer or holding keyboard focus won't vanish mid-read.+ * · Manual dismiss via the × button or the action callback.+ * · Accessible: container is aria-live; errors announce assertively+ * (role="alert"), others politely (role="status"). Action + close buttons+ * are real <button>s with aria-labels and visible focus rings.+ * · prefers-reduced-motion: enter/exit animations collapse to instant.+ *+ * No central registration is required — it's an ES module; import where used.+ */++const CONTAINER_ID = 'three-toast-container';+const STYLE_ID = 'three-toast-styles';+const MAX_TOASTS = 4;++const DEFAULT_DURATIONS = { info: 4000, success: 4000, warning: 5000, error: 6000 };++const prefersReducedMotion = () =>+ typeof window !== 'undefined' &&+ typeof window.matchMedia === 'function' &&+ window.matchMedia('(prefers-reduced-motion: reduce)').matches;++const ICONS = {+ success: '✓',+ error: '✕',+ warning: '!',+ info: 'i',+};++function injectStyles() {+ if (document.getElementById(STYLE_ID)) return;+ const style = document.createElement('style');+ style.id = STYLE_ID;+ style.textContent = `+#${CONTAINER_ID} {+ position: fixed;+ bottom: var(--space-md, 16px);+ right: var(--space-md, 16px);+ z-index: 2147483000;+ display: flex;+ flex-direction: column-reverse;+ gap: var(--space-sm, 10px);+ max-width: min(360px, calc(100vw - 2 * var(--space-md, 16px)));+ pointer-events: none;+}+#${CONTAINER_ID} .three-toast {+ pointer-events: auto;+ display: flex;+ align-items: flex-start;+ gap: var(--space-sm, 10px);+ padding: var(--space-sm, 10px) var(--space-md, 16px);+ border-radius: var(--radius-md, 10px);+ border: 1px solid var(--color-border, rgba(255,255,255,0.08));+ border-left-width: 3px;+ background: var(--bg-1, #1a1a1a);+ color: var(--color-text, #e8e8e8);+ font-family: var(--font-body, system-ui, sans-serif);+ font-size: 14px;+ line-height: 1.4;+ box-shadow: var(--shadow-2, 0 4px 24px rgba(0,0,0,0.4));+ transition: opacity var(--duration-base, 220ms) var(--ease-out, ease),+ transform var(--duration-base, 220ms) var(--ease-emphasized, ease);+ opacity: 0;+ transform: translateX(12px);+}+#${CONTAINER_ID} .three-toast.is-visible {+ opacity: 1;+ transform: translateX(0);+}+#${CONTAINER_ID} .three-toast.is-leaving {+ opacity: 0;+ transform: translateX(12px);+}+#${CONTAINER_ID} .three-toast-icon {+ flex: 0 0 auto;+ width: 18px;+ height: 18px;+ margin-top: 1px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border-radius: 999px;+ font-size: 11px;+ font-weight: 700;+ line-height: 1;+ color: var(--bg-0, #0a0a0a);+}+#${CONTAINER_ID} .three-toast-body {+ flex: 1 1 auto;+ min-width: 0;+ word-break: break-word;+}+#${CONTAINER_ID} .three-toast-action {+ margin-top: var(--space-2xs, 4px);+ display: inline-block;+ background: transparent;+ border: 1px solid var(--color-border-strong, rgba(255,255,255,0.14));+ border-radius: var(--radius-sm, 6px);+ color: var(--color-text-bright, #fff);+ font: inherit;+ font-size: 13px;+ font-weight: 600;+ padding: 3px 10px;+ cursor: pointer;+ transition: background var(--duration-fast, 140ms) ease, border-color var(--duration-fast, 140ms) ease;+}+#${CONTAINER_ID} .three-toast-action:hover {+ background: var(--surface-2, rgba(255,255,255,0.05));+ border-color: var(--color-text-dim, #888);+}+#${CONTAINER_ID} .three-toast-close {+ flex: 0 0 auto;+ background: transparent;+ border: none;+ color: var(--color-text-dim, #888);+ font-size: 18px;+ line-height: 1;+ padding: 0 0 0 var(--space-2xs, 4px);+ margin: -2px -4px -2px 0;+ cursor: pointer;+ border-radius: var(--radius-sm, 6px);+ transition: color var(--duration-fast, 140ms) ease;+}+#${CONTAINER_ID} .three-toast-close:hover {+ color: var(--color-text-bright, #fff);+}+#${CONTAINER_ID} .three-toast-action:focus-visible,+#${CONTAINER_ID} .three-toast-close:focus-visible {+ outline: 2px solid var(--focus-ring-color, var(--accent, #fff));+ outline-offset: 2px;+}+#${CONTAINER_ID} .three-toast.toast-success { border-left-color: var(--color-success, #4ade80); }+#${CONTAINER_ID} .three-toast.toast-error { border-left-color: var(--color-danger, #f87171); }+#${CONTAINER_ID} .three-toast.toast-warning { border-left-color: var(--color-warning, #fbbf24); }+#${CONTAINER_ID} .three-toast.toast-info { border-left-color: var(--color-accent, #fff); }+#${CONTAINER_ID} .three-toast.toast-success .three-toast-icon { background: var(--color-success, #4ade80); }+#${CONTAINER_ID} .three-toast.toast-error .three-toast-icon { background: var(--color-danger, #f87171); }+#${CONTAINER_ID} .three-toast.toast-warning .three-toast-icon { background: var(--color-warning, #fbbf24); }+#${CONTAINER_ID} .three-toast.toast-info .three-toast-icon { background: var(--color-accent, #fff); }+@media (prefers-reduced-motion: reduce) {+ #${CONTAINER_ID} .three-toast {+ transition: opacity 1ms linear;+ transform: none;+ }+ #${CONTAINER_ID} .three-toast.is-leaving { transform: none; }+}+`;+ document.head.appendChild(style);+}++function ensureContainer() {+ let container = document.getElementById(CONTAINER_ID);+ if (!container) {+ injectStyles();+ container = document.createElement('div');+ container.id = CONTAINER_ID;+ // Polite by default; per-toast role overrides to assertive for errors.+ container.setAttribute('aria-live', 'polite');+ container.setAttribute('aria-atomic', 'false');+ document.body.appendChild(container);+ }+ return container;+}++function evictOldest(container) {+ while (container.children.length >= MAX_TOASTS) {+ const oldest = container.firstElementChild;+ if (!oldest) break;+ oldest.dataset.evicting = '1';+ oldest.remove();+ }+}++/**+ * Display a toast notification.+ * @param {string} message+ * @param {{ type?: 'info'|'success'|'error'|'warning', duration?: number,+ * action?: { label: string, onClick: (dismiss: () => void) => void } }} [options]+ * @returns {() => void} dismiss — closes the toast immediately.+ */+export function showToast(message, options = {}) {+ if (typeof document === 'undefined' || !document.body) return () => {};++ const type = ['info', 'success', 'error', 'warning'].includes(options.type) ? options.type : 'info';+ const isError = type === 'error';+ const duration =+ options.duration === undefined ? DEFAULT_DURATIONS[type] : Number(options.duration);+ const sticky = !Number.isFinite(duration) || duration <= 0;++ const container = ensureContainer();+ evictOldest(container);++ const toast = document.createElement('div');+ toast.className = `three-toast toast-${type}`;+ // Errors interrupt; everything else is announced politely.+ toast.setAttribute('role', isError ? 'alert' : 'status');+ toast.setAttribute('aria-live', isError ? 'assertive' : 'polite');++ const icon = document.createElement('span');+ icon.className = 'three-toast-icon';+ icon.setAttribute('aria-hidden', 'true');+ icon.textContent = ICONS[type];++ const body = document.createElement('div');+ body.className = 'three-toast-body';+ const text = document.createElement('span');+ text.className = 'three-toast-text';+ text.textContent = String(message ?? '');+ body.appendChild(text);++ let timer = null;+ let removed = false;++ const remove = () => {+ if (removed) return;+ removed = true;+ clearTimeout(timer);+ toast.classList.add('is-leaving');+ toast.classList.remove('is-visible');+ const done = () => toast.remove();+ if (prefersReducedMotion()) {+ done();+ } else {+ let settled = false;+ const onEnd = () => {+ if (settled) return;+ settled = true;+ done();+ };+ toast.addEventListener('transitionend', onEnd, { once: true });+ // Failsafe in case the transition never fires (tab hidden, etc.).+ setTimeout(onEnd, 400);+ }+ };++ const startTimer = () => {+ if (sticky) return;+ clearTimeout(timer);+ timer = setTimeout(remove, duration);+ };+ const pauseTimer = () => clearTimeout(timer);++ if (options.action && options.action.label) {+ const actionBtn = document.createElement('button');+ actionBtn.type = 'button';+ actionBtn.className = 'three-toast-action';+ actionBtn.textContent = options.action.label;+ actionBtn.addEventListener('click', () => {+ try {+ options.action.onClick?.(remove);+ } finally {+ remove();+ }+ });+ body.appendChild(actionBtn);+ }++ const closeBtn = document.createElement('button');+ closeBtn.type = 'button';+ closeBtn.className = 'three-toast-close';+ closeBtn.setAttribute('aria-label', 'Dismiss notification');+ closeBtn.textContent = '×';+ closeBtn.addEventListener('click', remove);++ toast.appendChild(icon);+ toast.appendChild(body);+ toast.appendChild(closeBtn);++ // Pause auto-dismiss while hovered or holding keyboard focus, so the user can+ // finish reading / interact with the action before it disappears.+ toast.addEventListener('mouseenter', pauseTimer);+ toast.addEventListener('mouseleave', startTimer);+ toast.addEventListener('focusin', pauseTimer);+ toast.addEventListener('focusout', startTimer);++ container.appendChild(toast);++ // Force a reflow so the enter transition runs from the initial state.+ void toast.offsetWidth;+ toast.classList.add('is-visible');++ startTimer();++ return remove;+}diff --git a/tests/a2a-cart-mandate.test.js b/tests/a2a-cart-mandate.test.jsnew file mode 100644index 000000000..98d8213a4--- /dev/null+++ b/tests/a2a-cart-mandate.test.js@@ -0,0 +1,169 @@+// Tests for the AP2 Cart Mandate: the signed, tamper-evident per-transaction+// approval bound to an Intent Mandate. Covers issue/verify round-trip, hash+// tamper detection, intent binding, payment matching, and TTL bounds.++import { describe, expect, it } from 'vitest';+import * as jose from 'jose';++process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-jwt-secret';+process.env.A2A_MANDATE_SECRET = 'test-a2a-mandate-secret';++import { env } from '../api/_lib/env.js';+import {+ assertCartMatchesPayment,+ CART_MANDATE_TYPE,+ issueCartMandate,+ MAX_CART_TTL_SECONDS,+ verifyCartMandate,+} from '../api/_lib/a2a/cart-mandate.js';++// A decoded Intent Mandate, the shape verifyIntentMandate returns.+const intentMandate = {+ mandateId: 'intent-123',+ ownerUserId: 'user-1',+ subjectAgentId: 'agent-1',+ currency: 'USDC',+};++const baseCart = {+ resource: 'https://peer.example/api/agents/a2a',+ amountAtomics: '500000', // $0.50+ currency: 'USDC',+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ taskId: 'task-9',+ items: [{ name: 'crypto intel report', amountAtomics: '500000' }],+};++describe('Cart Mandate', () => {+ it('issues and verifies a cart mandate bound to its intent mandate', async () => {+ const { jws, cartMandate } = await issueCartMandate({ intentMandate, cart: baseCart });+ expect(typeof jws).toBe('string');++ const verified = await verifyCartMandate(jws);+ expect(verified.cartMandateId).toBe(cartMandate.cartMandateId);+ expect(verified.intentMandateId).toBe('intent-123');+ expect(verified.ownerUserId).toBe('user-1');+ expect(verified.subjectAgentId).toBe('agent-1');+ expect(verified.amountAtomics).toBe('500000');+ expect(verified.resource).toBe(baseCart.resource);+ expect(verified.network).toBe(baseCart.network);+ expect(verified.taskId).toBe('task-9');+ expect(verified.hash).toMatch(/^[0-9a-f]{64}$/);+ });++ it('rejects a tampered/garbage token', async () => {+ await expect(verifyCartMandate('not.a.jwt')).rejects.toMatchObject({ code: 'invalid_cart_mandate' });+ const { jws } = await issueCartMandate({ intentMandate, cart: baseCart });+ await expect(verifyCartMandate(jws + 'x')).rejects.toMatchObject({ code: 'invalid_cart_mandate' });+ });++ it('detects a body whose hash does not match (recomputed on verify)', async () => {+ // Forge a validly-signed token whose cart amount disagrees with its hash —+ // the recompute guard must catch it even though the signature is valid.+ const secret = new TextEncoder().encode(process.env.A2A_MANDATE_SECRET);+ const now = Math.floor(Date.now() / 1000);+ const forged = await new jose.SignJWT({+ typ: CART_MANDATE_TYPE,+ ver: 1,+ owner: 'user-1',+ intent: 'intent-123',+ c: {+ resource: baseCart.resource,+ amountAtomics: '999999999', // lies — does not match the hash below+ currency: 'USDC',+ network: baseCart.network,+ taskId: 'task-9',+ items: [],+ hash: 'deadbeef'.repeat(8),+ },+ })+ .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })+ .setSubject('agent-1')+ .setIssuer(env.APP_ORIGIN)+ .setIssuedAt(now)+ .setExpirationTime(now + 300)+ .setJti('forged-1')+ .sign(secret);++ await expect(verifyCartMandate(forged)).rejects.toMatchObject({ code: 'cart_hash_mismatch' });+ });++ it('enforces the expected intent mandate binding', async () => {+ const { jws } = await issueCartMandate({ intentMandate, cart: baseCart });+ await expect(+ verifyCartMandate(jws, { expectedIntentMandateId: 'some-other-intent' }),+ ).rejects.toMatchObject({ code: 'intent_mismatch' });+ // Correct intent id passes.+ await expect(verifyCartMandate(jws, { expectedIntentMandateId: 'intent-123' })).resolves.toBeTruthy();+ });++ it('rejects an expired cart mandate', async () => {+ const secret = new TextEncoder().encode(process.env.A2A_MANDATE_SECRET);+ const past = Math.floor(Date.now() / 1000) - 3600;+ const expired = await new jose.SignJWT({ typ: CART_MANDATE_TYPE, ver: 1, owner: 'u', intent: 'i', c: {} })+ .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })+ .setSubject('agent-1')+ .setIssuer(env.APP_ORIGIN)+ .setIssuedAt(past - 60)+ .setExpirationTime(past)+ .setJti('exp-1')+ .sign(secret);+ await expect(verifyCartMandate(expired)).rejects.toMatchObject({ code: 'cart_mandate_expired' });+ });++ it('rejects an out-of-bounds TTL and a malformed cart at issuance', async () => {+ await expect(+ issueCartMandate({ intentMandate, cart: baseCart, ttlSec: MAX_CART_TTL_SECONDS + 1 }),+ ).rejects.toMatchObject({ code: 'invalid_ttl' });+ await expect(+ issueCartMandate({ intentMandate, cart: { ...baseCart, resource: 'ftp://nope' } }),+ ).rejects.toMatchObject({ code: 'invalid_cart' });+ await expect(+ issueCartMandate({ intentMandate, cart: { ...baseCart, amountAtomics: '0' } }),+ ).rejects.toMatchObject({ code: 'invalid_amount' });+ });+});++describe('assertCartMatchesPayment', () => {+ it('passes when the payment matches the cart exactly', async () => {+ const { cartMandate } = await issueCartMandate({ intentMandate, cart: baseCart });+ expect(() =>+ assertCartMatchesPayment({+ cartMandate,+ amountAtomics: '500000',+ network: baseCart.network,+ resource: baseCart.resource,+ currency: 'USDC',+ }),+ ).not.toThrow();+ });++ it('rejects a payment that differs from the cart', async () => {+ const { cartMandate } = await issueCartMandate({ intentMandate, cart: baseCart });+ const codeOf = (fn) => {+ try {+ fn();+ } catch (e) {+ return e.code;+ }+ return null;+ };+ expect(codeOf(() => assertCartMatchesPayment({ cartMandate, amountAtomics: '600000' }))).toBe(+ 'cart_amount_mismatch',+ );+ expect(+ codeOf(() =>+ assertCartMatchesPayment({ cartMandate, amountAtomics: '500000', network: 'eip155:1' }),+ ),+ ).toBe('cart_network_mismatch');+ expect(+ codeOf(() =>+ assertCartMatchesPayment({+ cartMandate,+ amountAtomics: '500000',+ resource: 'https://evil.example/x',+ }),+ ),+ ).toBe('cart_resource_mismatch');+ });+});diff --git a/tests/api/purchase-as-agent.test.js b/tests/api/purchase-as-agent.test.jsindex 24912ad7f..7dd3c609b 100644--- a/tests/api/purchase-as-agent.test.js+++ b/tests/api/purchase-as-agent.test.js@@ -88,6 +88,15 @@ vi.mock('@solana/web3.js', async (orig) => {};});+// The handler now sends via the shared protected sender (submitProtected), which+// builds/simulates/signs a real v0 tx — incompatible with the stubbed web3.js+// primitives above. Mock it at the module boundary: these tests verify handler+// logic (status codes, self-deal flagging, DB writes), not the send mechanism.+const submitProtectedMock = vi.fn(async () => ({ signature: 'txSig', slot: 1, route: 'protected' }));+vi.mock('../../api/_lib/execution-engine.js', () => ({+ submitProtected: (...a) => submitProtectedMock(...a),+}));+vi.mock('@solana/spl-token', () => ({getAssociatedTokenAddressSync: vi.fn(() => ({ toBase58: () => 'ATA' })),createTransferCheckedInstruction: vi.fn(() => ({@@ -154,6 +163,8 @@ beforeEach(() => {rlState.success = true;confirmResult.status = 'confirmed';confirmResult.tx_signature = 'sig123';+ submitProtectedMock.mockReset();+ submitProtectedMock.mockResolvedValue({ signature: 'txSig', slot: 1, route: 'protected' });});// ── Tests ────────────────────────────────────────────────────────────────────@@ -274,8 +285,8 @@ describe('POST /api/marketplace/purchase-as-agent', () => {});it('returns 502 when the on-chain transaction fails', async () => {- // Temporarily make sendRawTransaction throw- fakeConn.sendRawTransaction.mockRejectedValueOnce(new Error('insufficient funds'));+ // Temporarily make the protected send throw+ submitProtectedMock.mockRejectedValueOnce(new Error('insufficient funds'));sqlQueue.push([BUYER_ROW]);sqlQueue.push([SELLER_ROW]);