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.

9.1 KB
Raw Blame
// Buyer-side fetch helper with spending-cap enforcement (USE-22).
//
// Wraps the standard 402 dance into one call, with `caps` enforcement
// installed via the lifecycle-style enforceCap → commit / rollback
// transaction so caps are honored even for callers that aren't using
// the @x402/fetch SDK directly.
//
// Usage:
//   const { ok, response, payment, settled } = await buyerFetch(url, {
//     method: 'POST',
//     body: { url: 'https://three.ws/avatar.glb' },
//     caps: {
//       address: '0xMyAgent',
//       maxPerCall: '50000',     // $0.05 per call
//       maxPerHour: '1000000',   // $1/hr
//       maxPerDay:  '5000000',   // $5/day
//     },
//     signPayment,               // ({ requirement }) => paymentPayload
//   });
//
// `signPayment` is supplied by the caller because signing logic varies
// (EIP-712 transferWithAuthorization for Base, signed VersionedTransaction
// for Solana, contract call for BSC). This module owns the cap check +
// header dance + settlement parsing only.

import { enforceCap, commit, releaseUnusedCap, rollbackReservation } from './x402-spending-cap.js';
import { BUILDER_CODE } from './x402-builder-code.js';
import { env } from './env.js';
import { readSolanaChargeChallenges, readSolanaChargeReceipt, solanaChargeAuthorization } from './mpp-solana.js';

function selectRequirement(challenge, prefer, preferScheme) {
	let accepts = Array.isArray(challenge?.accepts) ? challenge.accepts : [];
	// `preferScheme: 'upto'` takes an escrow-backed offer when one is advertised
	// (pay the measured charge, not the cap); otherwise the list is unchanged.
	if (preferScheme && accepts.some((a) => a.scheme === preferScheme)) {
		accepts = accepts.filter((a) => a.scheme === preferScheme);
	}
	if (typeof prefer === 'function') {
		const picked = prefer(accepts);
		if (picked) return picked;
	}
	if (typeof prefer === 'string') {
		const found = accepts.find((a) => a.network === prefer);
		if (found) return found;
	}
	return accepts[0] || null;
}

function ensureBuilderCodeEcho(challenge, paymentPayload) {
	const declared = challenge?.extensions?.[BUILDER_CODE];
	const declaredA = declared?.info?.a;
	if (!declaredA) return paymentPayload;
	const existing = paymentPayload.extensions || {};
	const existingBlock = existing[BUILDER_CODE] || {};
	const echo = { ...existingBlock, a: declaredA };
	if (env.X402_BUILDER_CODE_WALLET && !echo.w) {
		echo.w = env.X402_BUILDER_CODE_WALLET;
	}
	paymentPayload.extensions = { ...existing, [BUILDER_CODE]: echo };
	return paymentPayload;
}

function bodyToInit(method, body, headers = {}) {
	if (body == null) return { method, headers };
	if (typeof body === 'string' || body instanceof ArrayBuffer || body instanceof Uint8Array) {
		return { method, headers, body };
	}
	return {
		method,
		headers: { 'content-type': 'application/json', ...headers },
		body: JSON.stringify(body),
	};
}

function b64encode(obj) {
	return Buffer.from(JSON.stringify(obj), 'utf8').toString('base64');
}

function b64decode(s) {
	if (!s) return null;
	try {
		return JSON.parse(Buffer.from(s, 'base64').toString('utf8'));
	} catch {
		return null;
	}
}

// One-shot paid request. Returns:
//   { ok: true,  result, response, payment, settled }
//   { ok: false, abort: true, reason }      — cap rejected; no network call
//   { ok: false, status, error }            — server returned non-2xx
//
// The same call pays either protocol a 402 can speak. An x402 `accepts` list is
// preferred; when a server offers only an MPP `WWW-Authenticate: Payment`
// Solana charge (or `preferProtocol: 'mpp'` is set and one is on offer), the
// charge is expressed as the equivalent `exact` requirement, so the spending
// caps, `signPayment` and the guard layers see one shape, and the signed
// transaction goes back as `Authorization: Payment`. `dryRun: true` stops after
// the cap check and returns the quote, signing and paying nothing.
export async function buyerFetch(url, opts = {}) {
	const {
		method = 'GET',
		body,
		headers,
		caps,
		signPayment,
		preferNetwork,
		preferScheme,
		preferProtocol,
		dryRun = false,
		fetchImpl = globalThis.fetch,
	} = opts;

	if (typeof signPayment !== 'function') {
		throw new Error('buyerFetch: signPayment({ requirement }) callback is required');
	}

	const init = bodyToInit(method, body, headers);
	const probe = await fetchImpl(url, init);
	if (probe.status !== 402) {
		const text = await probe.text();
		const parsed = safeJson(text);
		return {
			ok: probe.ok,
			status: probe.status,
			result: parsed ?? text,
			response: probe,
		};
	}

	const challenge =
		safeJson(await probe.text()) ||
		(() => {
			// Some servers only emit the body on the PAYMENT-REQUIRED header.
			const header = probe.headers.get('payment-required');
			return header ? b64decode(header) : null;
		})();
	const mppOffers = readSolanaChargeChallenges(probe.headers).filter((o) => !o.expired);
	const hasX402 = Boolean(challenge) && Array.isArray(challenge.accepts);
	if (!hasX402 && !mppOffers.length) {
		return { ok: false, status: 402, error: 'invalid_402_body' };
	}

	let protocol = 'x402';
	let mppOffer = null;
	let requirement = null;
	if (hasX402 && preferProtocol !== 'mpp') requirement = selectRequirement(challenge, preferNetwork, preferScheme);
	if (!requirement && mppOffers.length) {
		mppOffer = mppOffers.find((o) => o.requirement.network === preferNetwork) || mppOffers[0];
		requirement = mppOffer.requirement;
		protocol = 'mpp';
	}
	if (!requirement && hasX402) requirement = selectRequirement(challenge, preferNetwork, preferScheme);
	if (!requirement) {
		return { ok: false, status: 402, error: 'no_acceptable_requirement' };
	}

	let reservation = null;
	if (caps) {
		const verdict = await enforceCap({ requirement, opts: caps });
		if (verdict.abort) {
			return { ok: false, abort: true, reason: verdict.reason, protocol, ...(dryRun ? { dryRun: true } : {}) };
		}
		reservation = verdict.reservation;
	}

	if (dryRun) {
		if (reservation) await rollbackReservation(reservation);
		return {
			ok: true,
			dryRun: true,
			protocol,
			quote: requirement,
			offers: {
				x402: hasX402 ? challenge.accepts : [],
				mpp: mppOffers.map((o) => o.requirement),
			},
		};
	}

	try {
		let paymentPayload;
		try {
			paymentPayload = await signPayment({ requirement, challenge });
		} catch (err) {
			if (reservation) await rollbackReservation(reservation);
			throw err;
		}
		let paidHeaders;
		if (protocol === 'mpp') {
			const transaction = paymentPayload?.payload?.transaction;
			if (typeof transaction !== 'string' || !transaction) {
				throw new Error('buyerFetch: signPayment must return a Solana exact payload ({ payload: { transaction } }) to pay an MPP charge');
			}
			paidHeaders = {
				Authorization: solanaChargeAuthorization({
					challenge: mppOffer.challenge,
					transaction,
					...(typeof paymentPayload.payer === 'string' ? { source: paymentPayload.payer } : {}),
				}),
			};
		} else {
			ensureBuilderCodeEcho(challenge, paymentPayload);
			paidHeaders = { 'X-PAYMENT': b64encode(paymentPayload) };
		}
		const paid = await fetchImpl(url, {
			...init,
			headers: { ...(init.headers || {}), ...paidHeaders },
		});
		const paidText = await paid.text();
		const paidJson = safeJson(paidText) ?? paidText;
		if (!paid.ok) {
			if (reservation) await rollbackReservation(reservation);
			return {
				ok: false,
				status: paid.status,
				error: paidJson?.error || `HTTP ${paid.status}`,
				result: paidJson,
				response: paid,
			};
		}
		const receipt = protocol === 'mpp' ? readSolanaChargeReceipt(paid) : null;
		const settled = receipt
			? { success: true, transaction: receipt.reference, network: receipt.network ?? requirement.network, payer: receipt.payer }
			: b64decode(paid.headers.get('x-payment-response'));
		if (reservation && requirement.scheme === 'upto' && settled?.amount != null) {
			reservation = await releaseUnusedCap(reservation, requirement, settled.amount);
		}
		if (reservation) {
			await commit(reservation, {
				network: requirement.network,
				asset: requirement.asset,
				settlement: settled,
			});
		}
		return {
			ok: true,
			protocol,
			result: paidJson,
			response: paid,
			payment: paymentPayload,
			settled,
		};
	} catch (err) {
		if (reservation) {
			await rollbackReservation(reservation).catch(() => undefined);
		}
		throw err;
	}
}

function safeJson(text) {
	if (typeof text !== 'string' || !text) return null;
	try {
		return JSON.parse(text);
	} catch {
		return null;
	}
}

// ── BNB Chain (MPP / b402) buyer ────────────────────────────────────────────
// Re-exported from the same surface so an agent that already imports the x402
// buyer can also pay MPP-protected endpoints on BNB Chain (eip155:56/97) with
// the same 402 → pay → retry ergonomics. MPP is x402 v2, so the only real
// difference is the network + an EIP-3009 credential signed by @bnb-chain/mpp.
//
//   import { buyerFetch, mppFetch } from './x402-buyer-fetch.js';
//   // Solana/Base:  await buyerFetch(url, { signPayment, caps });
//   // BNB Chain:    await mppFetch(url, { method: 'GET' }, { account, maxSpend: '20000' });
export { mppFetch, MPP_BUYER_NETWORKS, MppBuyerError } from './bnb/mpp-buyer.js';