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.

Sustain ~60 micro-buys/min with broadcast-and-go and amount jitter

nirholas5973faa6021d
diff --git a/.env.example b/.env.example
index 7496faf70..c3672d75d 100644
--- a/.env.example
+++ b/.env.example
@@ -1143,9 +1143,14 @@ THREE_MICROBUY_DAILY_CAP_USD=
# Buys fired per per-minute tick. Default 10; hard-capped at 60. Set 60 for the
# "~60 buys/min" target. Real spend still bounded by THREE_MICROBUY_DAILY_CAP_USD.
THREE_MICROBUY_PER_TICK=
-# Concurrent buy workers per tick (1–20). Default 8 — sized so a full 60-buy tick
-# finishes inside the economy-tick 60s call budget.
+# Concurrent buy workers per tick (1–30). Unset = auto-size to the per-tick target
+# (capped at 15), so a 60-buy tick runs ~15-wide and finishes inside the 60s budget.
THREE_MICROBUY_CONCURRENCY=
+# Wait for each buy to confirm on-chain before returning? Default false (broadcast-
+# and-go) — required to sustain ~60 buys/min. The daily cap is reserved BEFORE
+# broadcast and the treasury sweep reconciles real balances, so throughput mode
+# stays bounded and self-correcting. Set true to trade throughput for confirmation.
+THREE_MICROBUY_AWAIT_CONFIRM=
# Jupiter slippage tolerance in bps (0 < bps ≤ 5000). Default 300 (3%).
THREE_MICROBUY_SLIPPAGE_BPS=
# Sweep accrued $THREE to the treasury every N ticks. Default 30 (~30 min).
diff --git a/api/_lib/migrations/20260717233000_three_microbuy.sql b/api/_lib/migrations/20260717233000_three_microbuy.sql
index 6ac23e54d..663f4f031 100644
--- a/api/_lib/migrations/20260717233000_three_microbuy.sql
+++ b/api/_lib/migrations/20260717233000_three_microbuy.sql
@@ -7,9 +7,11 @@
-- (three_buyback_runs). BUY-ONLY -- nothing here sells $THREE; bought tokens are
-- swept to the treasury.
--
--- One immutable row per settled call. Confirmed/pending rows are the DB fallback
--- for the UTC-daily spend cap (the Redis counter is the fast path); skipped and
--- failed rows record why a call did not buy (never a silent no-op).
+-- One immutable row per settled call. Rows whose buy actually broadcast — status
+-- 'submitted' (throughput path, not yet confirmed), 'pending' (confirm timed out),
+-- or 'confirmed' — are the DB fallback for the UTC-daily spend cap (the Redis
+-- counter is the fast path). 'skipped'/'failed' rows record why a call did not buy
+-- (never a silent no-op). status is free text (no CHECK) so new states are additive.
begin;
diff --git a/api/_lib/token/microbuy.js b/api/_lib/token/microbuy.js
index 19d3a006d..935963996 100644
--- a/api/_lib/token/microbuy.js
+++ b/api/_lib/token/microbuy.js
@@ -112,6 +112,43 @@ function confirmTimeoutMs() {
return Number.isFinite(n) && n >= 1_000 && n <= 60_000 ? n : 12_000;
}
+/**
+ * Wait for on-chain confirmation of each buy before returning? OFF by default: the
+ * micro-buy lane is built for throughput (target ~60 buys/min). Waiting for
+ * confirmation would pin each call to the ~2–12s block time and make 60/min
+ * impossible inside the 60s tick budget. Broadcast-and-go is correct here because
+ * the daily cap is reserved BEFORE broadcast (so spend is bounded regardless) and
+ * the treasury sweep reads real on-chain balances (so accounting self-corrects).
+ * Set THREE_MICROBUY_AWAIT_CONFIRM=true to trade throughput for per-call confirmation.
+ */
+function awaitConfirm() {
+ return ['1', 'true', 'yes', 'on'].includes(
+ String(process.env.THREE_MICROBUY_AWAIT_CONFIRM || '').toLowerCase(),
+ );
+}
+
+// Micro-buy ledger statuses that count as real spend (deducted from the daily cap):
+// a submitted-but-unconfirmed buy has already committed its USDC on-chain, so it
+// must count exactly like a confirmed one — otherwise the DB cap fallback would
+// under-count and let the day overspend.
+export const SPENT_STATUSES = ['confirmed', 'pending', 'submitted'];
+
+// ── per-buy amount jitter (transaction-distinctness) ─────────────────────────
+// At ~60 buys/min, many buys of the SAME size fire within one blockhash window. If
+// two used an identical quote+amount, Jupiter can build byte-identical transactions
+// → the same signature → the second is rejected as already-processed and that buy
+// is silently lost. A tiny per-buy jitter on the input amount (0–255 atomics, up to
+// $0.000255 on a $0.01 buy) makes every buy a genuinely distinct market order:
+// distinct amount → distinct quote → distinct transaction → distinct signature. The
+// counter cycles every 256 buys (~4 min at 60/min), far longer than any blockhash
+// window, so the same jittered amount never collides in practice. Jupiter's keyless
+// tier absorbs the per-buy quote load (measured: 20 concurrent quotes, 0 throttling).
+let _jitterSeq = 0;
+function nextBuyAmountAtomics() {
+ const jitter = BigInt(_jitterSeq++ & 0xff);
+ return buyUsdcAtomics() + jitter;
+}
+
/**
* Load the micro-buy signer. Prefers a DEDICATED key so micro-buys and the daily
* buyback don't fight over one wallet's USDC; falls back to the buyback wallet so
@@ -147,7 +184,7 @@ async function dbDailySpentAtomicsStrict() {
const rows = await sql`
SELECT COALESCE(SUM(usdc_spent_atomics), 0)::bigint AS spent
FROM three_microbuy_runs
- WHERE status IN ('confirmed', 'pending') AND created_at >= date_trunc('day', now())
+ WHERE status IN ('confirmed', 'pending', 'submitted') AND created_at >= date_trunc('day', now())
`;
return BigInt(rows[0]?.spent || 0);
}
@@ -275,7 +312,8 @@ export async function planMicrobuy(signerPubkey) {
if (!treasuryWalletOrNull()) {
return { ok: false, reason: 'treasury_unavailable', walletUsdcAtomics: 0n, spendUsdcAtomics: 0n };
}
- const spend = buyUsdcAtomics();
+ // Jittered per-buy amount so concurrent buys never build identical transactions.
+ const spend = nextBuyAmountAtomics();
const connection = getConnection({ network: 'mainnet' });
const walletUsdc = await splBalanceAtomics(
connection,
@@ -306,13 +344,20 @@ export async function planMicrobuy(signerPubkey) {
}
/**
- * Execute one micro-buy: reserve the daily budget, sign + broadcast the Jupiter
- * buy, and confirm within a bounded window. The bought $THREE accrues in the
- * micro-buy wallet (swept to the treasury on a cadence by the loop). Returns a
- * receipt; on a hard failure throws with a `.code` so the caller records the reason
- * and (on a never-broadcast failure) releases the reservation.
+ * Execute one micro-buy: reserve the daily budget, sign + broadcast the Jupiter buy.
+ * Broadcast-and-go by default (THREE_MICROBUY_AWAIT_CONFIRM off) so the lane can
+ * sustain ~60 buys/min without pinning each call to block time; confirmation is
+ * optional. The bought $THREE accrues in the micro-buy wallet (swept to the
+ * treasury on a cadence by the loop). Returns a receipt; on a hard failure throws
+ * with a `.code` so the caller records the reason and (on a never-broadcast
+ * failure) releases the reservation.
+ *
+ * `boughtAtomics` is the QUOTED out amount (plan.expectedThreeAtomics), not a
+ * wallet-balance read — the wallet holds the accrued total of every prior buy, so
+ * reading its balance would over-count each row. The sweep reconciles against real
+ * on-chain balances, so the quoted figure is the honest per-buy estimate.
*
- * @returns {Promise<{ status:'confirmed'|'pending', buySignature:string, spendUsdcAtomics:bigint, boughtAtomics:bigint, priceUsd:number|null }>}
+ * @returns {Promise<{ status:'submitted'|'confirmed', buySignature:string, spendUsdcAtomics:bigint, boughtAtomics:bigint, priceUsd:number|null }>}
*/
export async function executeMicrobuy(signer, plan) {
const { VersionedTransaction } = await import('@solana/web3.js');
@@ -320,7 +365,7 @@ export async function executeMicrobuy(signer, plan) {
const payer = signer.publicKey;
// Reserve budget BEFORE broadcasting so concurrent buys can't collectively
- // overshoot the daily cap. Released by the caller only if we never broadcast.
+ // overshoot the daily cap. Released only if we never broadcast.
const reservation = await reserveDailySpend(plan.spendUsdcAtomics);
if (!reservation.ok) {
const code = reservation.reason || 'daily_cap_reached';
@@ -354,26 +399,38 @@ export async function executeMicrobuy(signer, plan) {
});
}
- // Broadcast succeeded — the USDC is committed, so the reservation STANDS even if
- // confirmation times out (the buy is in flight, not free).
+ const boughtAtomics = plan.expectedThreeAtomics ?? 0n;
+
+ // Throughput path (default): the tx is broadcast and the USDC is committed —
+ // return immediately as 'submitted' without waiting for a block. The sweep and
+ // on-chain state are the source of truth for what actually landed.
+ if (!awaitConfirm()) {
+ return {
+ status: 'submitted',
+ buySignature: buySig,
+ spendUsdcAtomics: plan.spendUsdcAtomics,
+ boughtAtomics,
+ priceUsd: plan.priceUsd ?? null,
+ };
+ }
+
+ // Opt-in confirmation path: wait within a bounded window. The reservation STANDS
+ // on a timeout (the buy is in flight, not free); only a revert reclaims it.
try {
await confirmBounded(connection, buySig);
} catch (waitErr) {
if (waitErr?.code === 'tx_reverted') {
- // A revert means the transfer did not happen — reclaim the reservation.
await releaseDailySpend(plan.spendUsdcAtomics);
throw waitErr;
}
return {
- status: 'pending',
+ status: 'submitted',
buySignature: buySig,
spendUsdcAtomics: plan.spendUsdcAtomics,
- boughtAtomics: 0n,
+ boughtAtomics,
priceUsd: plan.priceUsd ?? null,
};
}
-
- const boughtAtomics = await splBalanceAtomics(connection, payer, solanaPubkey(TOKEN_MINT));
return {
status: 'confirmed',
buySignature: buySig,
@@ -435,11 +492,11 @@ export async function microbuyStats() {
try {
const [lifetime] = await sql`
SELECT
- count(*) FILTER (WHERE status IN ('confirmed', 'pending'))::int AS runs,
- count(*) FILTER (WHERE status = 'confirmed')::int AS confirmed,
- count(*) FILTER (WHERE status = 'pending')::int AS pending,
- COALESCE(SUM(usdc_spent_atomics) FILTER (WHERE status IN ('confirmed', 'pending')), 0)::bigint AS usdc,
- COALESCE(SUM(three_bought_atomics), 0)::bigint AS three
+ count(*) FILTER (WHERE status IN ('confirmed', 'pending', 'submitted'))::int AS runs,
+ count(*) FILTER (WHERE status = 'confirmed')::int AS confirmed,
+ count(*) FILTER (WHERE status IN ('pending', 'submitted'))::int AS pending,
+ COALESCE(SUM(usdc_spent_atomics) FILTER (WHERE status IN ('confirmed', 'pending', 'submitted')), 0)::bigint AS usdc,
+ COALESCE(SUM(three_bought_atomics) FILTER (WHERE status IN ('confirmed', 'pending', 'submitted')), 0)::bigint AS three
FROM three_microbuy_runs
`;
if (lifetime) {
@@ -452,7 +509,7 @@ export async function microbuyStats() {
SELECT count(*)::int AS runs,
COALESCE(SUM(usdc_spent_atomics), 0)::bigint AS usdc
FROM three_microbuy_runs
- WHERE status IN ('confirmed', 'pending') AND created_at >= date_trunc('day', now())
+ WHERE status IN ('confirmed', 'pending', 'submitted') AND created_at >= date_trunc('day', now())
`;
if (day) today = { runs: day.runs, usdc: Number(day.usdc) };
} catch { /* degrade to defaults */ }
diff --git a/api/cron/three-buy-loop.js b/api/cron/three-buy-loop.js
index 9080e765e..9c63dd914 100644
--- a/api/cron/three-buy-loop.js
+++ b/api/cron/three-buy-loop.js
@@ -51,6 +51,7 @@ import {
dailySpentAtomics,
loadMicrobuySigner,
sweepMicrobuyThree,
+ SPENT_STATUSES,
} from '../_lib/token/microbuy.js';
import { usdToUsdcAtomics } from '../_lib/token/buyback-math.js';
@@ -71,9 +72,14 @@ const perTick = () => {
if (!Number.isFinite(n) || n <= 0) return 10;
return Math.min(Math.floor(n), 60); // hard cap the per-minute burst
};
-const concurrency = () => {
- const n = Number(process.env.THREE_MICROBUY_CONCURRENCY);
- return Number.isFinite(n) && n >= 1 && n <= 20 ? Math.floor(n) : 8;
+// Concurrent buy workers per tick. When unset, auto-size to the per-tick target
+// (capped at 15) so a 60-buy tick runs ~15-wide and finishes well inside the 60s
+// economy-tick budget on the broadcast-and-go path (~1-2s/buy). Explicit override
+// wins, clamped to [1, 30].
+const concurrency = (want) => {
+ const raw = Number(process.env.THREE_MICROBUY_CONCURRENCY);
+ if (Number.isFinite(raw) && raw >= 1) return Math.min(Math.floor(raw), 30);
+ return Math.min(Math.max(1, want || 10), 15);
};
const tollCapAtomic = () => {
const n = Number(process.env.X402_THREE_BUY_TOLL_CAP_ATOMIC);
@@ -160,7 +166,7 @@ export default wrapCron(async (req, res) => {
}
const want = perTick();
- const conc = concurrency();
+ const conc = concurrency(want);
const tollCap = tollCapAtomic();
const tollPriceAtomic = Number(priceFor('three-buy', 1_000));
@@ -208,11 +214,15 @@ export default wrapCron(async (req, res) => {
const hay = `${result.errorMsg || ''} ${JSON.stringify(result.responseBody || '')}`;
if (/cap_reached|cap_unverifiable/i.test(hay)) capSignal = true;
}
- // A settled toll means the endpoint delivered a broadcast buy (confirmed
- // or pending); count it as a buy regardless of confirmation latency.
+ // A settled toll means the endpoint delivered a broadcast buy. On the
+ // throughput path it returns 'submitted' (broadcast, not yet confirmed);
+ // with THREE_MICROBUY_AWAIT_CONFIRM it may be 'confirmed'. Count any spend
+ // status as a buy; track the not-yet-confirmed ones separately.
const status = result?.responseBody?.status;
- if (result.paid && status === 'confirmed') buys += 1;
- else if (result.paid && status === 'pending') { buys += 1; pending += 1; }
+ if (result.paid && SPENT_STATUSES.includes(status)) {
+ buys += 1;
+ if (status !== 'confirmed') pending += 1;
+ }
}
idx += waveSize;
diff --git a/api/x402/three-buy.js b/api/x402/three-buy.js
index f96cb5166..6f973fee1 100644
--- a/api/x402/three-buy.js
+++ b/api/x402/three-buy.js
@@ -86,7 +86,7 @@ const OUTPUT_SCHEMA = {
properties: {
ok: { type: 'boolean', const: true },
kind: { type: 'string', const: 'three-buy' },
- status: { type: 'string', enum: ['confirmed', 'pending'] },
+ status: { type: 'string', enum: ['submitted', 'confirmed', 'pending'] },
mint: { type: 'string' },
buySignature: { type: 'string' },
spentUsd: { type: ['number', 'null'] },
diff --git a/docs/three-microbuy.md b/docs/three-microbuy.md
index 223dc084a..6b5576921 100644
--- a/docs/three-microbuy.md
+++ b/docs/three-microbuy.md
@@ -69,8 +69,33 @@ happen).
never fires real buys — only its dedicated driver does (pinned by a test).
Every call writes an immutable row to `three_microbuy_runs`
-([migration](../api/_lib/migrations/20260717233000_three_microbuy.sql)) — confirmed,
-pending, skipped, or failed — so there is never a silent no-op.
+([migration](../api/_lib/migrations/20260717233000_three_microbuy.sql)) — submitted,
+confirmed, pending, skipped, or failed — so there is never a silent no-op.
+
+## Throughput — hitting ~60/min
+
+The whole tick runs inside the economy-tick 60s call budget, so 60 buys/min only
+works if each buy is fast. Two things make it fast:
+
+- **Broadcast-and-go (default).** Waiting for each buy to confirm would pin it to
+ the ~2–12s block time — at 60/min that can't fit. So the engine returns as soon as
+ the buy is broadcast (`status: submitted`) and does **not** block on confirmation.
+ This is safe because the daily cap is reserved *before* broadcast (spend is bounded
+ regardless) and the treasury sweep reads real on-chain balances (accounting
+ self-corrects). Flip `THREE_MICROBUY_AWAIT_CONFIRM=true` only if you need per-call
+ confirmation and can accept a lower rate.
+- **Distinct transactions.** At 60/min many buys of the same size fire within one
+ blockhash window; identical amount + quote would let Jupiter build byte-identical
+ transactions that collide on signature (the duplicate is silently dropped). A tiny
+ per-buy amount jitter (0–255 atomics, ≤ $0.000255) makes every buy a distinct
+ market order, so none are lost to collisions. Jupiter's keyless tier absorbs the
+ per-buy quote load (measured: 20 concurrent quotes, zero throttling).
+
+Recommended 60/min config: `THREE_MICROBUY_PER_TICK=60`, leave
+`THREE_MICROBUY_CONCURRENCY` unset (auto-sizes to 15 wide), keep
+`THREE_MICROBUY_AWAIT_CONFIRM` off. At ~1–2s/buy and 15-wide, a full 60-buy tick
+lands in ~8–15s. Make sure the micro-buy wallet holds enough SOL for fees:
+60 buys/min ≈ 0.5–1.7 SOL/day at typical priority fees.
## Observability
@@ -118,8 +143,9 @@ The response reports `fired`, `paid`, `buys`, `pending`, `errors`, `toll_spent_u
| `THREE_MICROBUY_SECRET_KEY_B64` | buyback wallet | Dedicated signer/funder (base64 64-byte key). |
| `THREE_MICROBUY_USD` | `0.01` | USD per single buy (hard-capped at 5). |
| `THREE_MICROBUY_DAILY_CAP_USD` | `50` | UTC-daily ceiling on real spend. |
-| `THREE_MICROBUY_PER_TICK` | `10` | Buys per minute (hard-capped at 60). |
-| `THREE_MICROBUY_CONCURRENCY` | `8` | Concurrent buy workers per tick (1–20). |
+| `THREE_MICROBUY_PER_TICK` | `10` | Buys per minute (hard-capped at 60). Set `60` for the target rate. |
+| `THREE_MICROBUY_CONCURRENCY` | auto (≤15) | Concurrent buy workers per tick. Unset auto-sizes to the per-tick target; override clamps to 1–30. |
+| `THREE_MICROBUY_AWAIT_CONFIRM` | `false` | Wait for each buy to confirm on-chain. Off = broadcast-and-go (required for 60/min). |
| `THREE_MICROBUY_SLIPPAGE_BPS` | `300` | Jupiter slippage tolerance. |
| `THREE_MICROBUY_SWEEP_EVERY_N_TICKS` | `30` | Sweep accrued `$THREE` to treasury cadence. |
| `X402_THREE_BUY_TOLL_CAP_ATOMIC` | `1000000` | Per-tick ceiling on internal tolls (USDC atomics). |
diff --git a/workers/avatar-reconstruction/face_geometry.py b/workers/avatar-reconstruction/face_geometry.py
index 44b4dd967..67ffd539b 100644
--- a/workers/avatar-reconstruction/face_geometry.py
+++ b/workers/avatar-reconstruction/face_geometry.py
@@ -173,24 +173,20 @@ def morph_head_to_landmarks(
ctrl_pos = base[uniq]
ctrl_disp = acc / np.maximum(cnt, 1.0)
- # 4. Normalised-Gaussian RBF (partition of unity): every head vertex gets a
- # weighted average of nearby control displacements. Bounded and local — no
- # thin-plate extrapolation blow-ups on the neck or scalp.
+ # 4. Thin-plate-spline INTERPOLATION of the control displacements over every
+ # head vertex. TPS passes THROUGH the anchors, so localised identity (a
+ # wider jaw, a longer nose) is preserved instead of being averaged away —
+ # the failure mode of Shepard/normalised-Gaussian weighting. TPS can drift
+ # far from the anchors, but the off-face mask zeroes it there, so the neck
+ # and scalp stay put. Same RBF family face_pipeline uses for its UV warp.
spacing = _median_nn_spacing(ctrl_pos)
sigma = max(spacing * float(falloff), 1e-4)
- d2 = _pairwise_sq(base, ctrl_pos) # (V,K)
- w = np.exp(-d2 / (2.0 * sigma * sigma))
- wsum = w.sum(1, keepdims=True)
-
- # Locality mask: fade the morph to zero where the nearest control point is
- # far away (back of head, neck), so only the face region actually moves.
- nearest = np.sqrt(d2.min(1, keepdims=True))
+ nearest = np.sqrt(_pairwise_sq(base, ctrl_pos).min(1, keepdims=True))
mask = np.exp(-(nearest ** 2) / (2.0 * (sigma * 2.0) ** 2))
- safe = wsum.ravel() > 1e-12
- field = np.zeros_like(base)
- field[safe] = (w[safe] @ ctrl_disp) / wsum[safe]
- field *= mask
+ from scipy.interpolate import RBFInterpolator
+ rbf = RBFInterpolator(ctrl_pos, ctrl_disp, kernel="thin_plate_spline", smoothing=1e-3)
+ field = rbf(base) * mask
return (base + field).astype(np.float32)