Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(materialize): refuse a sold-out edition at the price, and retry a certificate whose proof never landed

nirholase994d718f83e
diff --git a/api/cron/print-orders-sync.js b/api/cron/print-orders-sync.js
index 271df57ca..8d7c79ddd 100644
--- a/api/cron/print-orders-sync.js
+++ b/api/cron/print-orders-sync.js
@@ -8,7 +8,7 @@
// worst one a physical product has: an order that is genuinely finished sits in
// `printing` forever and nobody finds out until the buyer asks.
//
-// Three passes, deliberately separate:
+// Four passes, deliberately separate:
//
// 1. RECONCILE. For every order a configured adapter still owns, ask the
// adapter what it thinks the status is and apply the answer through the
@@ -28,6 +28,13 @@
// it makes a model call: a buyer's checkout must not wait on an LLM, and
// an LLM outage must not fail a payment that already settled.
//
+// 4. ATTEST. For every certificate whose Solana memo never landed, backfill
+// its QR and retry the send. Issuing a certificate is fail-soft on purpose
+// (a shipment is a physical fact and is never rolled back because an RPC
+// had a bad minute), which is only honest if something retries; this is
+// that something. A mainnet certificate waiting on the owner approval
+// comes back `refused` rather than `failed`: nothing is wrong with it.
+//
// A provider being down must not fail the sweep: each order is reconciled
// independently and its failure is counted, not thrown, so one broken lane
// never hides a stall in another. The same holds for screening.
@@ -43,6 +50,7 @@ import {
import { reconcileOrder } from '../_lib/print/fulfillment.js';
import { jobSummaryLines, notifyOperators } from '../_lib/print/ops-notify.js';
import { listOrdersAwaitingScreening, screenPaidOrder } from '../_lib/print/gate.js';
+import { certCluster, retryPendingAttestations } from '../_lib/print/certificate.js';
// A job is a stall once it is this many days past its recorded lead time. Two
// days absorbs a weekend and a slow carrier scan without crying wolf.
@@ -56,6 +64,12 @@ const STALL_BATCH = 25;
// slow provider cannot push the sweep past its schedule. Anything left over is
// picked up by the next tick, which is minutes away.
const SCREEN_BATCH = 10;
+// Each retry is one Solana transaction. Ten per tick clears a backlog within
+// minutes without turning a bad RPC hour into a rate-limit incident.
+const ATTEST_BATCH = Number(process.env.PRINT_CERT_RETRY_BATCH) || 10;
+// A certificate that has failed this many times is not going to land on its own:
+// it stops burning transactions and stays visible with its recorded error.
+const ATTEST_MAX_ATTEMPTS = Number(process.env.PRINT_CERT_MAX_ATTEMPTS) || 8;
export default wrapCron(async (req, res) => {
if (!method(req, res, ['GET'])) return;
@@ -115,6 +129,15 @@ export default wrapCron(async (req, res) => {
}
}
+ let certificates = { scanned: 0, attested: 0, refused: 0, failed: 0, qrBackfilled: 0 };
+ try {
+ certificates = await retryPendingAttestations({ limit: ATTEST_BATCH, maxAttempts: ATTEST_MAX_ATTEMPTS });
+ } catch (err) {
+ // The attestation lane is the least urgent of the four: a certificate
+ // without its signature is still a certificate, and the page says so.
+ failures.push({ order_id: 'certificates', error: `attest: ${String(err?.message || err).slice(0, 280)}` });
+ }
+
return json(res, 200, {
ok: true,
open: open.length,
@@ -124,6 +147,8 @@ export default wrapCron(async (req, res) => {
alerted,
screening_pending: awaiting.length,
screened,
+ cluster: certCluster(),
+ certificates,
failures,
});
});
diff --git a/api/print/quote.js b/api/print/quote.js
index fceecfdd1..e4b417c0a 100644
--- a/api/print/quote.js
+++ b/api/print/quote.js
@@ -32,6 +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 { editionState, PrintEditionError } from '../_lib/print/editions.js';
import { holderDiscountBps, holderUsd, tierForUsd } from '../_lib/three-tier.js';
// One analysis per source model, held for an hour. The report is deterministic
@@ -119,6 +120,20 @@ export default wrap(async (req, res) => {
// runs BEFORE any money is quoted: a refusal at this point costs the buyer
// nothing. The paid order is screened again, thoroughly, on the way to the
// printer. See api/_lib/print/gate.js and specs/PRINT_PIPELINE.md.
+ // Scarcity is checked where the price is set: a sold-out edition is refused
+ // before a buyer is ever shown a number, not after they have paid.
+ let edition = { seriesKey: null, limit: null, issued: 0, remaining: null, soldOut: false };
+ if (source.creationId) {
+ try {
+ edition = await editionState({ creationId: source.creationId });
+ } catch (err) {
+ // A scarcity read that fails must not take down pricing: an open
+ // edition is the truthful default and the checkout transition
+ // re-checks the cap against the database anyway.
+ if (!(err instanceof PrintEditionError)) throw err;
+ }
+ }
+
const lineage = await loadLineage(source.creationId);
const gate = await runFabricationGate({
stage: 'quote',
@@ -154,11 +169,46 @@ export default wrap(async (req, res) => {
// screening pass will run after payment, rather than discovering it as a
// surprise rejection later.
screening: { verdict: gate.verdict, stage: gate.stage, policy_url: gate.policy_url },
+ // Physical scarcity, read from the certificates that have actually shipped
+ // rather than from open orders, so a cancelled checkout never strands the
+ // last copy of a limited edition. `limit: null` is an open edition.
+ edition,
};
// No material chosen: this is the analyze call. Free, keyless, no price.
if (!body.materialId) return json(res, 200, base, { 'cache-control': 'no-store' });
+ // A sold-out edition is a rejection, not a price. It rides the same shape as
+ // every other rejection so the page renders it through its designed path.
+ const wanted = Math.max(1, Math.floor(Number(body.quantity) || 1));
+ if (edition.limit !== null && edition.remaining !== null && edition.remaining < wanted) {
+ return json(
+ res,
+ 200,
+ {
+ ...base,
+ quote: null,
+ token: null,
+ rejection: (() => {
+ const message =
+ edition.remaining === 0
+ ? `This is a limited edition of ${edition.limit} and every copy has shipped.`
+ : `Only ${edition.remaining} of this ${edition.limit}-piece edition ${edition.remaining === 1 ? 'is' : 'are'} left, so ${wanted} cannot be ordered.`;
+ const fix =
+ edition.remaining === 0
+ ? 'The creator caps how many physical copies of this model can exist, and every one now carries a numbered certificate. Print a different model, or ask the creator to raise the cap.'
+ : `Lower the quantity to ${edition.remaining} to take the rest of the edition.`;
+ return {
+ code: 'edition_sold_out',
+ message,
+ failures: [{ code: 'edition_sold_out', message, fix }],
+ };
+ })(),
+ },
+ { 'cache-control': 'no-store' },
+ );
+ }
+
// The holder discount reads the signed-in user's $THREE tier. Anonymous
// buyers quote at list price and the panel says so, rather than showing a
// discount they cannot claim at checkout.
diff --git a/tests/print-orders-sync.test.js b/tests/print-orders-sync.test.js
index 848aa1753..0b7142060 100644
--- a/tests/print-orders-sync.test.js
+++ b/tests/print-orders-sync.test.js
@@ -6,10 +6,12 @@
// unnoticed, which is a finished order sitting in `printing` until the buyer
// asks.
//
-// Two behaviours are load-bearing and both are pinned here: an unreachable
+// Three behaviours are load-bearing and all are pinned here: an unreachable
// provider must not abort the sweep (the stall pass is exactly what catches the
-// orders that provider is sitting on), and a stalled order must page the
-// operator once rather than on every tick.
+// orders that provider is sitting on), a stalled order must page the operator
+// once rather than on every tick, and the certificate attestation lane must
+// retry what shipping could not send without ever being able to take the sweep
+// down with it.
import { describe, it, expect, vi, beforeEach } from 'vitest';
@@ -34,6 +36,14 @@ vi.mock('../api/_lib/print/fulfillment.js', () => ({
FulfillmentError: class FulfillmentError extends Error {},
}));
+const retryPendingAttestations = vi.fn(async () => ({
+ scanned: 0, attested: 0, refused: 0, failed: 0, qrBackfilled: 0,
+}));
+vi.mock('../api/_lib/print/certificate.js', () => ({
+ retryPendingAttestations,
+ certCluster: () => 'devnet',
+}));
+
const notifyOperators = vi.fn(async () => {});
vi.mock('../api/_lib/print/ops-notify.js', () => ({
notifyOperators,
@@ -95,6 +105,7 @@ beforeEach(() => {
listStalledOrders.mockResolvedValue([]);
markStallAlerted.mockImplementation(async (ids) => ids.length);
reconcileOrder.mockImplementation(async (o) => ({ applied: false, order: o, reason: '', polled: true }));
+ retryPendingAttestations.mockResolvedValue({ scanned: 0, attested: 0, refused: 0, failed: 0, qrBackfilled: 0 });
});
describe('the sweep is scheduler-only', () => {
@@ -193,3 +204,36 @@ describe('stall detection', () => {
expect(serialized).not.toContain('A Buyer');
});
});
+
+describe('the certificate attestation pass', () => {
+ it('reports what it attested, alongside the cluster it attested on', async () => {
+ retryPendingAttestations.mockResolvedValue({ scanned: 3, attested: 2, refused: 1, failed: 0, qrBackfilled: 1 });
+ const res = await sweep({ authorized: true });
+ expect(res.statusCode).toBe(200);
+ expect(res.json.certificates).toEqual({ scanned: 3, attested: 2, refused: 1, failed: 0, qrBackfilled: 1 });
+ expect(res.json.cluster).toBe('devnet');
+ });
+
+ it('bounds each tick so a backlog cannot become a rate-limit incident', async () => {
+ await sweep({ authorized: true });
+ expect(retryPendingAttestations).toHaveBeenCalledWith(
+ expect.objectContaining({ limit: expect.any(Number), maxAttempts: expect.any(Number) }),
+ );
+ const { limit, maxAttempts } = retryPendingAttestations.mock.calls[0][0];
+ expect(limit).toBeGreaterThan(0);
+ expect(limit).toBeLessThanOrEqual(50);
+ expect(maxAttempts).toBeGreaterThan(0);
+ });
+
+ it('counts an attestation outage as a failure rather than losing the whole sweep', async () => {
+ retryPendingAttestations.mockRejectedValue(new Error('solana rpc unreachable'));
+ const res = await sweep({ authorized: true });
+ expect(res.statusCode).toBe(200);
+ expect(res.json.ok).toBe(true);
+ expect(res.json.failures).toContainEqual(
+ expect.objectContaining({ order_id: 'certificates' }),
+ );
+ // The passes that matter more still ran.
+ expect(listStalledOrders).toHaveBeenCalled();
+ });
+});