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.

fix(print): close out an order the quoted move refused instead of stranding it

nirholas5aac1bc70cad
diff --git a/api/print/orders.js b/api/print/orders.js
index ba2138cbe..373bafa80 100644
--- a/api/print/orders.js
+++ b/api/print/orders.js
@@ -30,6 +30,7 @@ import { env } from '../_lib/env.js';
import { solanaConnection } from '../_lib/solana/connection.js';
import { buildGaslessPurchaseTx } from '../_lib/solana/gasless-tx.js';
import { verifyQuote } from '../_lib/print/quote.js';
+import { PrintEditionError } from '../_lib/print/editions.js';
import {
PrintStoreError,
createOrder,
@@ -75,6 +76,29 @@ function solanaPayUrl({ payTo, mint, amount, reference, label, message }) {
return `solana:${payTo}?${params.toString()}`;
}
+/**
+ * Close out an order that was inserted but never reached `quoted`. Best effort
+ * on purpose: the caller is already returning an error, and a cancel that fails
+ * must not replace the real reason with a second, less useful one. Anything left
+ * behind is still a legal `created` row the operator console can close by hand.
+ *
+ * @param {{ id: string, status: string }|null} order
+ * @param {unknown} cause
+ */
+async function cancelStrandedOrder(order, cause) {
+ if (!order?.id || order.status !== 'created') return;
+ try {
+ await transition({
+ orderId: order.id,
+ to: 'canceled',
+ note: `Checkout could not be completed: ${String(cause?.message || cause).slice(0, 200)}`,
+ actor: 'system',
+ });
+ } catch (err) {
+ console.warn('[print] could not close stranded order', order.id, err?.message);
+ }
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'POST'])) return;
@@ -181,6 +205,18 @@ export default wrap(async (req, res) => {
});
order = moved.order;
} catch (err) {
+ // The row is inserted before the move to `quoted`, so a failure here (a
+ // sold-out edition, a lost race) would otherwise strand an order in
+ // `created` that nobody will ever pay for and nobody will ever close.
+ // Cancel it on the way out: the buyer sees the real reason, and the
+ // operator queue does not collect one orphan per failed checkout.
+ await cancelStrandedOrder(order, err);
+ // The scarcity check on the `quoted` move throws its own typed error, so
+ // a sold-out edition has to be caught here too or it would surface as a
+ // 500 on the one path where a buyer most needs to be told why.
+ if (err instanceof PrintEditionError) {
+ return error(res, 409, err.code, err.message);
+ }
if (err instanceof PrintStoreError) {
const status = err.code === 'edition_sold_out' ? 409 : 422;
return error(res, status, err.code, err.message);
diff --git a/api/x402/print-order.js b/api/x402/print-order.js
index da8550101..83922cc92 100644
--- a/api/x402/print-order.js
+++ b/api/x402/print-order.js
@@ -278,12 +278,29 @@ export default async function handler(req, res) {
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',
- });
+ try {
+ await transition({
+ orderId: order.id,
+ to: 'quoted',
+ note: note ? `Agent order over x402. ${note}` : 'Agent order over x402, awaiting settlement.',
+ actor: 'system',
+ });
+ } catch (err) {
+ // The row exists before the move, so a refusal here (a sold-out
+ // edition, a lost race) would otherwise strand an order in `created`
+ // that no settlement will ever reach. Close it out, then rethrow so
+ // the wrapper refuses the call BEFORE settling: the caller keeps
+ // their money and the queue keeps no orphan.
+ await transition({
+ orderId: order.id,
+ to: 'canceled',
+ note: `Checkout could not be completed: ${String(err?.message || err).slice(0, 200)}`,
+ actor: 'system',
+ }).catch((cleanupErr) => {
+ console.warn('[print] could not close stranded agent order', order.id, cleanupErr?.message);
+ });
+ throw err;
+ }
return {
ok: true,
order_id: order.id,
diff --git a/tests/api/print-checkout-endpoints.test.js b/tests/api/print-checkout-endpoints.test.js
index 984f975da..e47e367e1 100644
--- a/tests/api/print-checkout-endpoints.test.js
+++ b/tests/api/print-checkout-endpoints.test.js
@@ -29,7 +29,7 @@ const OTHER_USER = { id: '00000000-0000-4000-8000-0000000000bb' };
let sessionUser = USER;
let csrfOk = true;
-const store = { orders: new Map(), created: [], transitions: [] };
+const store = { orders: new Map(), created: [], transitions: [], failTransitionTo: null };
vi.mock('../../api/_lib/auth.js', () => ({
getSessionUser: vi.fn(async () => sessionUser),
@@ -83,6 +83,10 @@ vi.mock('../../api/_lib/print-store.js', async (importOriginal) => {
return row;
}),
transition: vi.fn(async ({ orderId, to }) => {
+ if (store.failTransitionTo === to) {
+ const err = new actual.PrintStoreError('edition_sold_out', 'This edition is sold out.');
+ throw err;
+ }
store.transitions.push({ orderId, to });
const row = store.orders.get(orderId);
if (row) row.status = to;
@@ -149,6 +153,7 @@ beforeEach(() => {
store.orders.clear();
store.created.length = 0;
store.transitions.length = 0;
+ store.failTransitionTo = null;
vi.clearAllMocks();
});
@@ -232,6 +237,18 @@ describe('POST /api/print/orders', () => {
expect(store.created).toHaveLength(0);
});
+ it('closes out an order the quoted move refused, rather than stranding it', async () => {
+ // The row is inserted before the move, so a refusal after the insert would
+ // otherwise leave a `created` order nobody will pay for and nobody will close.
+ store.failTransitionTo = 'quoted';
+ const res = await postOrder({ token: tokenFor(), shipping: SHIPPING });
+ expect(res.statusCode).toBe(409);
+ expect(parse(res).error).toBe('edition_sold_out');
+ expect(store.transitions).toEqual([
+ { orderId: '11111111-2222-4333-8444-555555555555', to: 'canceled' },
+ ]);
+ });
+
it('names the missing shipping field rather than failing generically', async () => {
const partial = { ...SHIPPING };
delete partial.postal_code;