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(print): let an agent pay to have a physical object manufactured
nirholase8edd4be76d7
diff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.jsindex 740af7286..ecdca4e01 100644--- a/api/_lib/notify-prefs.js+++ b/api/_lib/notify-prefs.js@@ -102,6 +102,9 @@ const TYPE_CATEGORY = {asset_purchase_confirmed: 'purchases',skill_gift_received: 'purchases',skill_gift_sent: 'purchases',+ // Materialize: one type carries the whole print lifecycle, quoted through+ // delivered. It is the buyer's own order, so it belongs with purchases.+ print_update: 'purchases',remix: 'social',reply: 'social',diff --git a/api/_lib/service-catalog/services/index.js b/api/_lib/service-catalog/services/index.jsindex 88152e4c8..551c5244f 100644--- a/api/_lib/service-catalog/services/index.js+++ b/api/_lib/service-catalog/services/index.js@@ -69,6 +69,7 @@ import spendSession from './spend-session.js';import telegramHealth from './telegram-health.js';import walletConnect from './wallet-connect.js';import robinhoodPortfolio from './robinhood-portfolio.js';+import printOrder from './print-order.js';export const PAID_SERVICES = Object.freeze([modelCheck,@@ -130,4 +131,5 @@ export const PAID_SERVICES = Object.freeze([telegramHealth,walletConnect,robinhoodPortfolio,+ printOrder,]);diff --git a/api/_lib/service-catalog/services/print-order.js b/api/_lib/service-catalog/services/print-order.jsnew file mode 100644index 000000000..cf67aa975--- /dev/null+++ b/api/_lib/service-catalog/services/print-order.js@@ -0,0 +1,66 @@+// Service-catalog descriptor - the single written-once listing for this+// service. api/wk.js derives its /.well-known/x402.json resource entry from+// this file via api/_lib/service-catalog/index.js (toBazaarDiscovery), and+// the OKX storefront projection reads the same record (toOkxCatalog).+// Do not re-add a hand-written mirror for this route in api/wk.js - edit this+// descriptor instead.+//+// Pricing note: a print is priced per object, per size, per destination, so+// there is no single list price to advertise. priceAtomics is the catalog FLOOR+// (data/print-catalog.json pricing.minOrderUsdc), which is exactly what the+// route's probe challenge quotes to a crawler. A real order quotes its own+// signed quote token instead.++export default {+ slug: 'print-order',+ title: 'Materialize: Physical 3D Printing',+ category: '3d',+ useCase: 'Physical Manufacturing - pay in USDC to have a 3D model printed in resin, nylon or full-color sandstone and shipped to a street address.',+ path: '/api/x402/print-order',+ method: 'POST',+ free: false,+ status: 'live',+ priceAtomics: '12000000',+ acceptsBuilder: 'standard',+ serviceName: 'three.ws Materialize',+ tags: ['3d-printing', 'manufacturing', 'physical', 'commerce', 'fulfillment'],+ description:+ 'Order a real, physical 3D print of any model and have it manufactured and shipped to a street address, paying in USDC. Quote first at POST /api/print/quote (free, keyless) with a creationId or a glbUrl, a materialId from GET /api/print/catalog, a target height in millimetres and an ISO country code; that returns a printability report, an itemized price and a signed quote token. Post the token plus a shipping address here and the 402 challenge quotes that quote\'s exact total, so the price shown is the price of that object at that size to that country. Settling it opens a real manufacturing job: safety screening, production, tracked shipping, and a certificate of authenticity attested on Solana. Track it at GET /api/print/orders/{id}. The 12 USDC listed here is the catalog floor, not a list price.',+ input: {+ token: 'pq1.<signed quote from POST /api/print/quote>',+ shipping: {+ name: 'Ada Lovelace',+ line1: '12 Analytical Way',+ city: 'London',+ postal_code: 'EC1A 1AA',+ country: 'GB',+ },+ },+ inputSchema: {+ type: 'object',+ required: ['token', 'shipping'],+ properties: {+ token: {+ type: 'string',+ description: 'The signed quote token from POST /api/print/quote. Carries the material, size, quantity, destination and total, so the price cannot be altered in transit. Valid for 24 hours.',+ },+ shipping: {+ type: 'object',+ required: ['name', 'line1', 'city', 'postal_code', 'country'],+ description: 'Delivery address. Minimum fields only; never logged, never in an analytics event.',+ properties: {+ name: { type: 'string', maxLength: 120 },+ line1: { type: 'string', maxLength: 120 },+ line2: { type: 'string', maxLength: 120 },+ city: { type: 'string', maxLength: 120 },+ region: { type: 'string', maxLength: 120 },+ postal_code: { type: 'string', maxLength: 120 },+ country: { type: 'string', maxLength: 2, description: 'ISO 3166-1 alpha-2. Must match the country the quote was priced for.' },+ phone: { type: 'string', maxLength: 120 },+ },+ },+ note: { type: 'string', maxLength: 500, description: 'Optional note for the operator, kept on the order timeline.' },+ },+ },+ storefronts: ['x402scan'],+};diff --git a/api/_lib/x402/ring-catalog.js b/api/_lib/x402/ring-catalog.jsindex 3d3212eff..39cd07587 100644--- a/api/_lib/x402/ring-catalog.js+++ b/api/_lib/x402/ring-catalog.js@@ -821,6 +821,43 @@ export const RING_CATALOG = [businessEffect: 'Full-text search over the 662k-article crypto-news archive (Sept 2017 →) with sentiment/ticker/date filters.',note: 'autobuy:false — freemium rail: 60 searches/day per IP are free, so a ring call usually gets a free 200, not a 402; the paid twin only engages over quota.',},+ {+ slug: 'print-order',+ sourceFile: 'api/x402/print-order.js',+ path: '/api/x402/print-order',+ method: 'POST',+ // The catalog floor price, which is also what the probe challenge quotes.+ // A real call is priced by its own signed quote token, so no single number+ // here can be the price of an order.+ body: () => ({ token: null, shipping: null }),+ priceAtomicDefault: 12_000_000,+ priceSlug: 'print-order',+ tier: 'commerce',+ kind: 'commerce',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Each settled call opens a REAL manufacturing job: a physical 3D print is produced and shipped to the street address in the request, and an on-chain certificate is issued when it ships.',+ note: 'autobuy:false - a settled call manufactures and ships a physical object to a real address, which cannot be canaried. It is also unbuyable by a loop by construction: the price comes from an HMAC-signed quote token the ring has no way to mint, so a rotation call would be refused pre-settle with a 422.',+ },+ {+ slug: 'knock',+ sourceFile: 'api/x402/knock.js',+ path: '/api/x402/knock',+ method: 'POST',+ body: () => ({ from: 'ring canary', message: 'ring coverage probe' }),+ // The representative probe price the handler quotes when no door is named.+ // A real knock is priced by the recipient's own door row.+ priceAtomicDefault: 50_000,+ priceSlug: 'knock',+ tier: 'commerce',+ kind: 'commerce',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Each settled call delivers one paid message to a real person, settling USDC directly to that recipient\'s own wallet rather than to the platform.',+ note: 'autobuy:false - a settled call interrupts a real human being and pays them, and the payout wallet is theirs, not ours. There is also nothing to buy without a ?to= handle: a rotation call with no door gets the probe challenge and can never settle.',+ },{slug: 'three-buy',sourceFile: 'api/x402/three-buy.js',diff --git a/api/print/quote.js b/api/print/quote.jsindex 74656a36a..fceecfdd1 100644--- a/api/print/quote.js+++ b/api/print/quote.js@@ -32,7 +32,7 @@ import { analyzeMesh } from '../_lib/print/analyze.js';import { loadCatalog, materialFits, quotePrint, signQuote } from '../_lib/print/quote.js';import { getPublicCreation } from '../_lib/forge-store.js';import { loadLineage, runFabricationGate } from '../_lib/print/gate.js';-import { holderDiscountBps } from '../_lib/three-tier.js';+import { holderDiscountBps, holderUsd, tierForUsd } from '../_lib/three-tier.js';// One analysis per source model, held for an hour. The report is deterministic// for given bytes, so a cache hit is the same answer the analysis would produce,@@ -41,6 +41,8 @@ const reports = createCache({ max: 256, ttlMs: 60 * 60 * 1000 });// MeshIoError codes carry their own correct HTTP status: a mesh that is too big// is the caller's input, not our failure, and a fetch that died upstream is a 502.+const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const MESH_ERROR_STATUS = {invalid_model: 422,no_geometry: 422,@@ -161,7 +163,24 @@ export default wrap(async (req, res) => {// buyers quote at list price and the panel says so, rather than showing a// discount they cannot claim at checkout.const user = await getSessionUser(req).catch(() => null);- const discountBps = user ? await holderDiscountBps(user) : 0;+ // An agent has no session, so it names the wallet it will pay from and the+ // tier is read from that wallet's own $THREE holdings. Without this the+ // x402 lane could only ever quote list price, which would make the holder+ // discount a humans-only perk on a platform whose buyers are half machines.+ // Self-declared and harmless: the discount is derived from an on-chain+ // balance we read ourselves, so naming someone else's wallet buys nothing+ // except that wallet's own tier.+ const payerWallet =+ !user && typeof body.payerWallet === 'string' && SOLANA_ADDRESS_RE.test(body.payerWallet.trim())+ ? body.payerWallet.trim()+ : null;+ let discountBps = 0;+ if (user) {+ discountBps = await holderDiscountBps(user);+ } else if (payerWallet) {+ const held = await holderUsd(payerWallet);+ discountBps = tierForUsd(held.usd).discountBps;+ }const priced = quotePrint({report,@@ -200,6 +219,7 @@ export default wrap(async (req, res) => {rejection: null,token,holderTierApplied: discountBps > 0,+ holderTierSource: user ? 'session' : payerWallet ? 'payer_wallet' : null,expiresInSeconds: token ? catalog.pricing.quoteTtlSeconds : null,},{ 'cache-control': 'no-store' },diff --git a/api/x402/print-order.js b/api/x402/print-order.jsnew file mode 100644index 000000000..ee7868b2f--- /dev/null+++ b/api/x402/print-order.js@@ -0,0 +1,317 @@+// POST /api/x402/print-order+//+// An AI agent pays, and a physical object gets manufactured and shipped to a+// real address. As far as we know this is the first API where that is the whole+// transaction: no account, no card, no human in the loop on the buying side.+// The agent quotes the job for free at POST /api/print/quote, gets back an+// HMAC-signed quote token, and settles that token's exact total here in USDC on+// Solana.+//+// The order of operations is the product:+//+// 1. the quote token is verified and the shipping address validated BEFORE+// any 402 is issued, so a malformed order is refused for free (422) and a+// caller never pays for something that was going to be rejected;+// 2. the 402 quotes the token's own total, not a list price. Every order is+// its own amount, because a print is its own object;+// 3. the handler opens the order and moves it to `quoted`;+// 4. settlement happens in the wrapper, and only once it succeeds does the+// post-settlement hook move the order paid -> screening. An order that+// never settled therefore never reaches the production floor.+//+// A probe with no body (x402 catalogs do this constantly) gets a well-formed+// challenge at the catalog's floor price with a description that says where the+// real price comes from. Nothing can settle against it: a paid retry still has+// to carry a token this server signed.+//+// The buyer keeps a receipt they can read without an account: the response+// carries the order id, and GET /api/print/orders/:id serves its timeline.++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema, paymentRequirements, send402 } from '../_lib/x402-spec.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { cors, error, readBody } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { loadCatalog, verifyQuote } from '../_lib/print/quote.js';+import {+ PrintStoreError,+ createOrder,+ normalizeShipping,+ transition,+} from '../_lib/print-store.js';++const ROUTE = '/api/x402/print-order';+const SERVICE_NAME = 'three.ws Materialize';+const TAGS = ['3d-printing', 'manufacturing', 'physical', 'commerce', 'fulfillment'];++const DESCRIPTION =+ 'Order a real, physical 3D print of any model and have it manufactured and ' ++ 'shipped to a street address, paying in USDC. Quote first at ' ++ 'POST /api/print/quote (free, keyless) with a creationId or a glbUrl, a ' ++ 'materialId from GET /api/print/catalog, a target height in millimetres and ' ++ 'an ISO country code; that returns a printability report, an itemized price ' ++ 'and a signed quote token. Post the token plus a shipping address here and ' ++ 'the 402 challenge quotes that quote\'s exact total. Settling it opens a real ' ++ 'manufacturing job: safety screening, production, tracked shipping, and a ' ++ 'certificate of authenticity attested on Solana. Track it at ' ++ 'GET /api/print/orders/{id}. Materials, constraints and lead times are all ' ++ 'in the catalog; a mesh that cannot be printed is refused before payment.';++const INPUT_EXAMPLE = {+ token: 'pq1.eyJ2IjoxLCJtIjoicmVzaW4tc3RhbmRhcmQifQ.T0tFTg',+ shipping: {+ name: 'Ada Lovelace',+ line1: '12 Analytical Way',+ city: 'London',+ postal_code: 'EC1A 1AA',+ country: 'GB',+ },+};++const SHIPPING_SCHEMA = {+ type: 'object',+ required: ['name', 'line1', 'city', 'postal_code', 'country'],+ description:+ 'The delivery address. Minimum fields only: this is the sole personal data the ' ++ 'platform stores, it is never logged and never enters an analytics event.',+ properties: {+ name: { type: 'string', maxLength: 120 },+ line1: { type: 'string', maxLength: 120 },+ line2: { type: 'string', maxLength: 120 },+ city: { type: 'string', maxLength: 120 },+ region: { type: 'string', maxLength: 120, description: 'State, province or region.' },+ postal_code: { type: 'string', maxLength: 120 },+ country: { type: 'string', maxLength: 2, description: 'ISO 3166-1 alpha-2. Must match the country the quote was priced for.' },+ phone: { type: 'string', maxLength: 120, description: 'Optional. Couriers ask for one on international parcels.' },+ },+};++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['token', 'shipping'],+ properties: {+ token: {+ type: 'string',+ description: 'The signed quote token from POST /api/print/quote. It carries the material, size, quantity, destination and total, so the price cannot be altered in transit. Valid for 24 hours.',+ },+ shipping: SHIPPING_SCHEMA,+ note: { type: 'string', maxLength: 500, description: 'Optional note for the operator, kept on the order timeline.' },+ },+};++const OUTPUT_EXAMPLE = {+ ok: true,+ order_id: 'c1b0a2d4-7e33-4f01-9a55-2b7c1d0e9f4a',+ status: 'screening',+ paid_usdc: '48.20',+ material: 'resin-standard',+ quantity: 1,+ target_height_mm: 140,+ lead_time_days: 12,+ track_url: 'https://three.ws/api/print/orders/c1b0a2d4-7e33-4f01-9a55-2b7c1d0e9f4a',+};++const BAZAAR = {+ description: DESCRIPTION,+ useCases: [+ 'Turn a generated 3D model into a physical object delivered to a customer',+ 'Let an autonomous agent fulfil a merchandise order end to end',+ 'Prototype a part in resin, nylon or full-color sandstone without an account',+ ],+ input: { type: 'json', example: INPUT_EXAMPLE, schema: INPUT_SCHEMA },+ output: { type: 'json', example: OUTPUT_EXAMPLE },+ schema: buildBazaarSchema({ method: 'POST', bodySchema: INPUT_SCHEMA, outputSchema: { type: 'object' } }),+};++export const BAZAAR_SCHEMA = BAZAAR;++/**+ * The cheapest order this catalog can produce, in USDC atomics. Directories and+ * probe challenges quote it as the from-price; a real order always quotes its+ * own signed total instead.+ */+export function floorPriceAtomics(catalog = loadCatalog()) {+ return String(Math.round(Number(catalog.pricing.minOrderUsdc) * 1_000_000));+}++function usdcAtomics(total) {+ return String(Math.round(Number(total) * 1_000_000));+}++async function readJsonBody(req) {+ if (req.body && typeof req.body === 'object') return req.body;+ try {+ const raw = (await readBody(req, 20_000)).toString('utf8').trim();+ return raw ? JSON.parse(raw) : {};+ } catch {+ return {};+ }+}++/** The catalog-floor challenge, for a probe that named no order. */+function probeChallenge(res, errText) {+ const resourceUrl = `${env.APP_ORIGIN}${ROUTE}`;+ return send402(res, {+ resourceUrl,+ accepts: paymentRequirements(resourceUrl, { amount: floorPriceAtomics() }),+ description: DESCRIPTION,+ bazaar: BAZAAR,+ error: errText,+ serviceName: SERVICE_NAME,+ tags: TAGS,+ });+}++export default async function handler(req, res) {+ // CORS first: this file answers the probe challenge and its own pre-settle+ // 4xx bodies before delegating, so a browser client must be able to read them.+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;++ const paymentPresent = Boolean(req.headers['x-payment'] || req.headers['payment-signature']);+ const body = await readJsonBody(req);+ req.body = body;++ const hasOrder = Boolean(body && (body.token || body.shipping));+ if (!hasOrder) {+ if (paymentPresent) {+ return error(res, 400, 'token_required', 'a signed quote token from POST /api/print/quote is required');+ }+ return probeChallenge(+ res,+ 'Quote the job first at POST /api/print/quote, then retry here with that token and a shipping address for its exact price.',+ );+ }++ // ── Pre-settle validation ────────────────────────────────────────────────+ // Everything that can refuse this order runs here, before a 402 is issued+ // and long before a settle. A caller is never charged for an order we were+ // always going to reject.+ const quote = verifyQuote(typeof body.token === 'string' ? body.token : '');+ if (!quote) {+ return error(res, 422, 'quote_invalid', 'that quote is expired or was not issued by this server. Request a fresh one from POST /api/print/quote.');+ }+ if (!quote.sourceUrl) {+ return error(res, 422, 'quote_invalid', 'that quote does not name a model to print');+ }++ let shipping;+ try {+ shipping = normalizeShipping(body.shipping);+ } catch (err) {+ if (err instanceof PrintStoreError) {+ return error(res, 422, err.code, err.message, err.field ? { field: err.field } : {});+ }+ throw err;+ }+ if (quote.country && shipping.country !== quote.country) {+ return error(res, 422, 'destination_mismatch', `this quote was priced for shipping to ${quote.country}. Re-quote for ${shipping.country}.`, {+ quoted_country: quote.country,+ shipping_country: shipping.country,+ });+ }++ const priceAtomics = usdcAtomics(quote.total);+ const note = typeof body.note === 'string' ? body.note.slice(0, 500) : null;++ const inner = paidEndpoint({+ route: ROUTE,+ method: 'POST',+ // This order's own total, from the token this server signed. Not a list+ // price: a print is priced per object, per size, per destination.+ priceAtomics,+ // Solana leads and is the rail we settle ourselves. Base follows so an+ // EVM-native agent can still buy a print.+ networks: ['solana', 'base'],+ description: `${DESCRIPTION} Currently quoting: ${quote.quantity} x ${quote.materialId} at ${quote.targetHeightMm} mm to ${quote.country}, ${Number(quote.total).toFixed(2)} USDC.`,+ bazaar: BAZAAR,+ service: withService({ serviceName: SERVICE_NAME, tags: TAGS }),+ // A duplicate call ships a second physical object to someone's house, which+ // is the exact case this rail's idempotency key exists for. Required, and+ // the 402 advertises it so a caller learns the contract before paying.+ paymentIdentifier: { required: true },+ async handler({ payer }) {+ // The order is opened and quoted here, NOT paid. Settlement happens in+ // the wrapper after this returns; promoting to paid before it settled+ // would be how an unpaid job reaches the production floor.+ const order = await createOrder({+ payerWallet: payer || null,+ quote,+ itemization: {+ token: body.token,+ total: quote.total,+ materialId: quote.materialId,+ finishId: quote.finishId,+ targetHeightMm: quote.targetHeightMm,+ quantity: quote.quantity,+ hollow: quote.hollow,+ country: quote.country,+ volumeCm3: quote.volumeCm3,+ leadTimeDays: quote.leadTimeDays,+ reportHash: quote.reportHash,+ expiresAt: quote.expiresAt,+ lane: 'x402',+ },+ report: { report_hash: quote.reportHash, volume_cm3: quote.volumeCm3 },+ sourceGlbUrl: quote.sourceUrl,+ creationId: quote.creationId || null,+ shipping,+ paymentChain: 'solana',+ });+ await transition({+ orderId: order.id,+ to: 'quoted',+ note: note ? `Agent order over x402. ${note}` : 'Agent order over x402, awaiting settlement.',+ actor: 'system',+ });+ return {+ ok: true,+ order_id: order.id,+ // Overwritten by the post-settlement hook below once the money is+ // actually on chain. If that hook ever fails, the honest value is+ // this one, and the operator console reconciles it.+ status: 'quoted',+ paid_usdc: Number(quote.total).toFixed(2),+ material: quote.materialId,+ finish: quote.finishId,+ quantity: quote.quantity,+ target_height_mm: quote.targetHeightMm,+ lead_time_days: quote.leadTimeDays,+ ship_to: { city: shipping.city, country: shipping.country },+ track_url: `${env.APP_ORIGIN}/api/print/orders/${order.id}`,+ };+ },+ // Runs after settlement succeeds and before the response is flushed, so+ // the status the buyer reads is the status the order is actually in.+ async metered({ result, settled, payer }) {+ const orderId = result?.order_id;+ if (!orderId) return null;+ const signature = settled?.transaction || null;+ await transition({+ orderId,+ to: 'paid',+ note: signature ? `x402 settlement confirmed: ${signature}` : 'x402 settlement confirmed.',+ actor: 'system',+ patch: {+ payment_signature: signature,+ payment_chain: settled?.network?.startsWith('eip155') ? 'base' : 'solana',+ payment_amount_atomics: priceAtomics,+ },+ });+ await transition({+ orderId,+ to: 'screening',+ note: 'Queued for the fabrication safety screen.',+ actor: 'system',+ });+ return {+ status: 'screening',+ paid: true,+ payer: payer || null,+ settlement_signature: signature,+ };+ },+ });++ return inner(req, res);+}diff --git a/src/notifications-page.js b/src/notifications-page.jsindex 0b84a3e93..8af1ae653 100644--- a/src/notifications-page.js+++ b/src/notifications-page.js@@ -18,6 +18,7 @@ const TYPE_CATEGORY = {pump_launch_filled: 'sales', royalty_paid: 'sales',skill_purchase_confirmed: 'purchases', asset_purchase_confirmed: 'purchases',skill_gift_received: 'purchases', skill_gift_sent: 'purchases',+ print_update: 'purchases',remix: 'social', reply: 'social', comment: 'social', embed: 'social', mention: 'social',fork: 'social', follow: 'social', dm_received: 'social', agent_review: 'social',quest_complete: 'social',diff --git a/src/notifications.js b/src/notifications.jsindex 77d114ff1..2d58fcfc5 100644--- a/src/notifications.js+++ b/src/notifications.js@@ -91,6 +91,7 @@ export const TYPE_ICON = {quest_complete: '🏆',royalty_paid: '💰',companion_delivery: '👋',+ print_update: '📦',};export function notifLabel(n) {@@ -168,6 +169,10 @@ export function notifLabel(n) {// point of the delivery, so the inbox reads exactly like the avatar// sounds. Falls back to the subject when a line never got written.return p.line || (p.sender ? `${p.sender}: ${p.title || 'has something for you'}` : p.title || 'Something needs you');+ case 'print_update':+ // The store already wrote the line for this status, so the bell reads+ // exactly what the order timeline says rather than a second wording of it.+ return p.message || `Your print order was updated${p.status ? `: ${String(p.status).replace(/_/g, ' ')}` : ''}`;case 'royalty_paid':return p.usd? `${p.actor || 'A fork of your avatar'} paid you $${Number(p.usd).toFixed(3)} in royalties`diff --git a/tests/print-checkout-store.test.js b/tests/print-checkout-store.test.jsnew file mode 100644index 000000000..9bd6328ee--- /dev/null+++ b/tests/print-checkout-store.test.js@@ -0,0 +1,254 @@+/**+ * Materialize checkout, at the store layer: opening an order and the address+ * we are willing to hold while doing it.+ *+ * Two things are load-bearing here and both are about trust rather than+ * mechanics. First, every priced field on the row comes out of the VERIFIED+ * quote token, never out of the request, so a caller who edits a total in+ * flight cannot make the database believe it. Second, a shipping address is the+ * first real personal data this platform stores, so the normalizer accepts the+ * minimum and drops everything else: a field that is never accepted is a field+ * that can never leak.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';++const db = { sql: null };++vi.mock('../api/_lib/db.js', () => ({+ get sql() {+ return db.sql;+ },+}));+vi.mock('../api/_lib/print/certificate.js', () => ({+ issueCertificateForOrder: async () => ({ certificate: null }),+}));+vi.mock('../api/_lib/print/editions.js', () => ({+ assertEditionAvailable: async () => true,+}));+vi.mock('../api/_lib/feed.js', () => ({+ publishUserEvent: () => {},+}));++const { createOrder, normalizeShipping, PrintStoreError } = await import('../api/_lib/print-store.js');++const USER = '00000000-0000-4000-8000-0000000000aa';+const WALLET = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';++const GOOD_ADDRESS = {+ name: 'Ada Lovelace',+ line1: '12 Analytical Way',+ city: 'London',+ postal_code: 'EC1A 1AA',+ country: 'gb',+};++const QUOTE = {+ materialId: 'resin-standard',+ finishId: 'as-printed',+ targetHeightMm: 140,+ quantity: 1,+ country: 'GB',+ total: 48.2,+ volumeCm3: 38.4,+ leadTimeDays: 14,+ reportHash: 'abc123',+ sourceUrl: 'https://cdn.example.test/model.glb',+ creationId: null,+ expiresAt: Date.parse('2026-09-03T12:00:00Z'),+};++/** Captures the INSERT so a test can assert what actually reached the table. */+function makeSql() {+ const inserted = { order: null, events: [] };+ const sql = async (strings, ...values) => {+ const text = strings.join(' ? ').replace(/\s+/g, ' ').trim();+ if (text.startsWith('insert into print_orders')) {+ inserted.order = {+ user_id: values[0],+ payer_wallet: values[1],+ creation_id: values[2],+ source_glb_url: values[3],+ analysis: values[4],+ material_id: values[5],+ target_height_mm: values[6],+ quantity: values[7],+ quote: values[8],+ price_usdc: values[9],+ shipping: values[10],+ payment_reference: values[11],+ payment_chain: values[12],+ quote_expires_at: values[13],+ };+ return [{ id: 'order-1', status: 'created', ...inserted.order }];+ }+ if (text.startsWith('insert into print_order_events')) {+ inserted.events.push({ order_id: values[0], status: values[1], note: values[2], actor: values[3] });+ return [{ id: 'event-1', status: values[1] }];+ }+ throw new Error(`unexpected query: ${text}`);+ };+ return { sql, inserted };+}++beforeEach(() => {+ const made = makeSql();+ db.sql = made.sql;+ db.inserted = made.inserted;+});++describe('normalizeShipping', () => {+ it('keeps the minimum fields and normalizes the country', () => {+ const out = normalizeShipping({ ...GOOD_ADDRESS, phone: '+44 20 7946 0000' });+ expect(out).toEqual({+ name: 'Ada Lovelace',+ line1: '12 Analytical Way',+ line2: null,+ city: 'London',+ region: null,+ postal_code: 'EC1A 1AA',+ country: 'GB',+ phone: '+44 20 7946 0000',+ });+ });++ it('drops every field it was not asked to hold', () => {+ const out = normalizeShipping({+ ...GOOD_ADDRESS,+ email: '[email protected]',+ date_of_birth: '1815-12-10',+ tax_id: 'GB123456789',+ notes: 'leave with the neighbour',+ });+ for (const leaked of ['email', 'date_of_birth', 'tax_id', 'notes']) {+ expect(Object.hasOwn(out, leaked), `${leaked} must never be stored`).toBe(false);+ }+ });++ it('names the field that is missing rather than failing generically', () => {+ for (const field of ['name', 'line1', 'city', 'postal_code', 'country']) {+ const partial = { ...GOOD_ADDRESS };+ delete partial[field];+ let thrown = null;+ try {+ normalizeShipping(partial);+ } catch (err) {+ thrown = err;+ }+ expect(thrown, `${field} must be required`).toBeInstanceOf(PrintStoreError);+ expect(thrown.code).toBe('shipping_incomplete');+ expect(thrown.field).toBe(field);+ }+ });++ it('refuses a country that is not an ISO alpha-2 code', () => {+ // "United Kingdom" would have shipped at the rest-of-world rate while the+ // quote was priced for Europe, and we would have eaten the difference.+ expect(() => normalizeShipping({ ...GOOD_ADDRESS, country: 'United Kingdom' })).toThrow(PrintStoreError);+ });++ it('truncates rather than rejecting an over-long line', () => {+ const out = normalizeShipping({ ...GOOD_ADDRESS, line1: 'x'.repeat(500) });+ expect(out.line1).toHaveLength(120);+ });++ it('refuses a missing address outright', () => {+ expect(() => normalizeShipping(null)).toThrow(PrintStoreError);+ });+});++describe('createOrder', () => {+ it('writes every priced field from the quote token, not from the caller', async () => {+ const shipping = normalizeShipping(GOOD_ADDRESS);+ await createOrder({+ userId: USER,+ quote: QUOTE,+ itemization: { total: QUOTE.total, token: 'pq1.x.y' },+ report: { report_hash: QUOTE.reportHash },+ sourceGlbUrl: QUOTE.sourceUrl,+ shipping,+ paymentReference: 'ref-1',+ paymentChain: 'solana',+ });+ const row = db.inserted.order;+ expect(row.material_id).toBe('resin-standard');+ expect(row.target_height_mm).toBe(140);+ expect(row.quantity).toBe(1);+ expect(row.price_usdc).toBe(48.2);+ expect(row.user_id).toBe(USER);+ expect(row.payer_wallet).toBeNull();+ expect(JSON.parse(row.shipping).country).toBe('GB');+ expect(row.quote_expires_at).toBe('2026-09-03T12:00:00.000Z');+ });++ it('opens the timeline with a created event naming what was ordered', async () => {+ await createOrder({+ userId: USER,+ quote: QUOTE,+ itemization: {},+ report: {},+ sourceGlbUrl: QUOTE.sourceUrl,+ shipping: normalizeShipping(GOOD_ADDRESS),+ });+ expect(db.inserted.events).toHaveLength(1);+ expect(db.inserted.events[0].status).toBe('created');+ expect(db.inserted.events[0].note).toContain('resin-standard');+ expect(db.inserted.events[0].actor).toBe('buyer');+ });++ it('records an agent order against its payer wallet and no user', async () => {+ await createOrder({+ payerWallet: WALLET,+ quote: QUOTE,+ itemization: {},+ report: {},+ sourceGlbUrl: QUOTE.sourceUrl,+ shipping: normalizeShipping(GOOD_ADDRESS),+ });+ expect(db.inserted.order.user_id).toBeNull();+ expect(db.inserted.order.payer_wallet).toBe(WALLET);+ // No signed-in human to attribute it to, so the timeline says system.+ expect(db.inserted.events[0].actor).toBe('system');+ });++ it('refuses an order that belongs to nobody', async () => {+ await expect(+ createOrder({+ quote: QUOTE,+ itemization: {},+ report: {},+ sourceGlbUrl: QUOTE.sourceUrl,+ shipping: normalizeShipping(GOOD_ADDRESS),+ }),+ ).rejects.toThrow(PrintStoreError);+ expect(db.inserted.order).toBeNull();+ });++ it('refuses to open an order with no verified quote behind it', async () => {+ for (const quote of [null, {}, { materialId: 'resin-standard', total: 0 }]) {+ await expect(+ createOrder({+ userId: USER,+ quote,+ itemization: {},+ report: {},+ sourceGlbUrl: QUOTE.sourceUrl,+ shipping: normalizeShipping(GOOD_ADDRESS),+ }),+ ).rejects.toThrow(PrintStoreError);+ }+ expect(db.inserted.order).toBeNull();+ });++ it('refuses an order with no model to print', async () => {+ await expect(+ createOrder({+ userId: USER,+ quote: QUOTE,+ itemization: {},+ report: {},+ sourceGlbUrl: '',+ shipping: normalizeShipping(GOOD_ADDRESS),+ }),+ ).rejects.toThrow(PrintStoreError);+ });+});