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(vanity): give bounties an escrow activation and void lifecycle

nirholas67eebb4b4de4
diff --git a/api/_lib/vanity-bounty-store.js b/api/_lib/vanity-bounty-store.js
index b2b8e56d0..f84b34c9b 100644
--- a/api/_lib/vanity-bounty-store.js
+++ b/api/_lib/vanity-bounty-store.js
@@ -15,6 +15,14 @@
* strips the sealed envelope from the public board view so only the requester
* (via the authenticated reveal path) ever receives it.
*
+ * ── Escrow lands before the bounty does ──────────────────────────────────────
+ * A bounty is born `escrow_pending`: recorded, but in NO index, so it is invisible
+ * to the board and to `listClaimable`, and every compare-and-set below refuses it.
+ * Only `activateBounty` (called after the x402 escrow actually settled on-chain)
+ * flips it to `open` and indexes it. A settle that fails is voided instead. That
+ * ordering is what stops the platform paying a winner — or refunding a requester —
+ * out of a bounty whose escrow was never collected.
+ *
* ── Atomic single-winner settlement ──────────────────────────────────────────
* `claimBounty` runs a Lua compare-and-set: it flips status open→settled, records
* the winner + claim digest, and returns "won" ONLY to the first caller. Every
@@ -28,7 +36,6 @@
* ZSET vanity:bounty:open member=id score=expiresAt(ms) (live board)
* ZSET vanity:bounty:by-recency member=id score=createdAt(ms)
* ZSET vanity:bounty:leaderboard member=workerId score=earnedAtomics (top grinders)
- * STR vanity:bounty:lease:<id>:<wid> short-TTL work-lease (advisory de-dup)
*/
import { getRedis } from './redis.js';
@@ -39,11 +46,19 @@ const K = {
open: `${NS}:open`,
byRecency: `${NS}:by-recency`,
leaderboard: `${NS}:leaderboard`,
- lease: (id, wid) => `${NS}:lease:${id}:${wid}`,
};
const MAX_SCAN = 500;
+// Statuses a bounty holds before (or instead of) going live. Neither is a real
+// bounty: they never reach the board, the claim queue, or the stats totals.
+const TRANSIENT_STATUSES = Object.freeze(['escrow_pending', 'void']);
+
+/** True for a record that has not (or will never) go live on the board. */
+function isTransient(rec) {
+ return !!rec && TRANSIENT_STATUSES.includes(rec.status);
+}
+
// Public board projection — the sealed envelope + escrow proof stay private.
// SECURITY: this is the privacy boundary for the board. The sealed envelope is
// only ever returned to the requester through the dedicated reveal path, never here.
@@ -66,14 +81,22 @@ export function toPublicBounty(rec) {
}
/**
- * Create a bounty in `open` status with its escrow record attached. The escrow
- * proof (x402 settlement tx + payer) is stored on the record but never exposed
- * publicly — it is the audit trail proving the requester actually funded it.
+ * Record a bounty. The escrow proof (x402 settlement tx + payer) is stored on the
+ * record but never exposed publicly — it is the audit trail proving the requester
+ * actually funded it.
+ *
+ * Pass `status: 'escrow_pending'` (what api/vanity/bounties.js does) to record the
+ * bounty WITHOUT indexing it: it stays off the board and out of the claim queue
+ * until `activateBounty` confirms the escrow settled. A record created straight
+ * into `open` is indexed immediately, which is only correct when the caller has
+ * already collected the escrow.
+ *
* @param {object} rec - fully-formed bounty record (see api/vanity/bounties.js).
* @returns {Promise<object>} the stored record.
*/
export async function createBounty(rec) {
- const record = { ...rec, status: 'open' };
+ const record = { ...rec, status: rec.status || 'open' };
+ const indexed = record.status === 'open';
const redis = getRedis();
if (redis) {
// Claim the id atomically FIRST (hsetnx) so a (astronomically unlikely)
@@ -83,10 +106,12 @@ export async function createBounty(rec) {
if (created === 0 || created === false) {
throw Object.assign(new Error('bounty id collision'), { status: 409, code: 'duplicate_bounty' });
}
- const pipe = redis.multi();
- pipe.zadd(K.open, { score: record.expiresAt, member: record.id });
- pipe.zadd(K.byRecency, { score: record.createdAt, member: record.id });
- await pipe.exec();
+ if (indexed) {
+ const pipe = redis.multi();
+ pipe.zadd(K.open, { score: record.expiresAt, member: record.id });
+ pipe.zadd(K.byRecency, { score: record.createdAt, member: record.id });
+ await pipe.exec();
+ }
} else {
if (mem.has(record.id)) {
throw Object.assign(new Error('bounty id collision'), { status: 409, code: 'duplicate_bounty' });
@@ -96,6 +121,107 @@ export async function createBounty(rec) {
return record;
}
+// Atomic escrow_pending→open compare-and-set, run only once the x402 escrow has
+// really settled on-chain. Indexes the bounty in the same call, so it becomes
+// board-visible and claimable at the instant it becomes funded — never before.
+// Idempotent: re-activating an already-open bounty returns 1.
+// Returns 1=live, 0=wrong-status, -2=missing.
+const ACTIVATE_LUA = `
+local raw = redis.call('HGET', KEYS[1], ARGV[1])
+if not raw then return -2 end
+local rec = cjson.decode(raw)
+if rec.status == 'open' then return 1 end
+if rec.status ~= 'escrow_pending' then return 0 end
+rec.status = 'open'
+rec.escrowSettledAt = tonumber(ARGV[2])
+rec.escrowTx = ARGV[3]
+rec.escrowNetwork = ARGV[4]
+redis.call('HSET', KEYS[1], ARGV[1], cjson.encode(rec))
+redis.call('ZADD', KEYS[2], tonumber(rec.expiresAt), ARGV[1])
+redis.call('ZADD', KEYS[3], tonumber(rec.createdAt), ARGV[1])
+return 1
+`;
+
+/**
+ * Flip a pending bounty live now that its escrow settled on-chain, recording the
+ * settlement tx as the audit trail. Idempotent.
+ *
+ * @param {object} p
+ * @param {string} p.id
+ * @param {string} [p.escrowTx] - the x402 settlement transaction.
+ * @param {string} [p.escrowNetwork] - the network the escrow settled on.
+ * @returns {Promise<'live'|'ineligible'|'missing'>}
+ */
+export async function activateBounty({ id, escrowTx, escrowNetwork }) {
+ const now = Date.now();
+ const redis = getRedis();
+ if (redis) {
+ const r = Number(await redis.eval(
+ ACTIVATE_LUA,
+ [K.rec, K.open, K.byRecency],
+ [String(id), String(now), String(escrowTx || ''), String(escrowNetwork || '')],
+ ));
+ if (r === 1) return 'live';
+ if (r === -2) return 'missing';
+ return 'ineligible';
+ }
+ const rec = mem.get(String(id));
+ if (!rec) return 'missing';
+ if (rec.status === 'open') return 'live';
+ if (rec.status !== 'escrow_pending') return 'ineligible';
+ rec.status = 'open';
+ rec.escrowSettledAt = now;
+ rec.escrowTx = escrowTx || '';
+ rec.escrowNetwork = escrowNetwork || '';
+ mem.set(String(id), rec);
+ return 'live';
+}
+
+// Atomic escrow_pending→void compare-and-set for a bounty whose escrow never
+// settled. A void bounty was never indexed, so voiding is purely a status +
+// reason write: it can never be claimed, refunded, or listed. Idempotent.
+const VOID_LUA = `
+local raw = redis.call('HGET', KEYS[1], ARGV[1])
+if not raw then return -2 end
+local rec = cjson.decode(raw)
+if rec.status == 'void' then return 1 end
+if rec.status ~= 'escrow_pending' then return 0 end
+rec.status = 'void'
+rec.voidedAt = tonumber(ARGV[2])
+rec.voidReason = ARGV[3]
+redis.call('HSET', KEYS[1], ARGV[1], cjson.encode(rec))
+return 1
+`;
+
+/**
+ * Void a pending bounty whose escrow failed to settle, so the unfunded record can
+ * never be claimed or refunded. Idempotent.
+ *
+ * @param {object} p
+ * @param {string} p.id
+ * @param {string} [p.reason] - why the escrow never landed (audit trail).
+ * @returns {Promise<'void'|'ineligible'|'missing'>}
+ */
+export async function voidBounty({ id, reason }) {
+ const now = Date.now();
+ const redis = getRedis();
+ if (redis) {
+ const r = Number(await redis.eval(VOID_LUA, [K.rec], [String(id), String(now), String(reason || '')]));
+ if (r === 1) return 'void';
+ if (r === -2) return 'missing';
+ return 'ineligible';
+ }
+ const rec = mem.get(String(id));
+ if (!rec) return 'missing';
+ if (rec.status === 'void') return 'void';
+ if (rec.status !== 'escrow_pending') return 'ineligible';
+ rec.status = 'void';
+ rec.voidedAt = now;
+ rec.voidReason = reason || '';
+ mem.set(String(id), rec);
+ return 'void';
+}
+
/** Fetch the full internal record by id (includes sealed envelope when settled). */
export async function getBountyRecord(id) {
const key = String(id || '');
@@ -262,21 +388,6 @@ export async function recordRefund({ id, refundTx }) {
return rec;
}
-/**
- * Claim a short-lived advisory work-lease so workers don't all redo the same
- * bounty. Best-effort coordination only (NOT a security control — the atomic
- * claim is the real winner gate). Returns true if this worker got/holds the lease.
- * @param {string} id
- * @param {string} workerId
- * @param {number} [ttlSeconds=45]
- */
-export async function acquireLease(id, workerId, ttlSeconds = 45) {
- const redis = getRedis();
- if (!redis) return true; // single-process dev: no contention to coordinate.
- const ok = await redis.set(K.lease(id, workerId), Date.now(), { nx: true, ex: ttlSeconds });
- return ok === 'OK' || ok === true;
-}
-
/**
* Query the board.
* @param {object} [q]
@@ -307,9 +418,11 @@ export async function queryBounties(q = {}) {
recs = [...mem.values()];
}
- let filtered = recs;
- if (status === 'open') filtered = recs.filter((r) => r.status === 'open' && r.expiresAt > now);
- else if (status === 'settled') filtered = recs.filter((r) => r.status === 'settled');
+ // A pending/void record has no escrow behind it, so it never appears on the
+ // board — not even under status=all, which reads the whole recency index.
+ let filtered = recs.filter((r) => !isTransient(r));
+ if (status === 'open') filtered = filtered.filter((r) => r.status === 'open' && r.expiresAt > now);
+ else if (status === 'settled') filtered = filtered.filter((r) => r.status === 'settled');
filtered.sort((a, b) => {
if (sort === 'reward') return (b.amountAtomics || 0) - (a.amountAtomics || 0);
@@ -353,12 +466,15 @@ export async function bountyStats() {
recs = [...mem.values()];
}
const now = Date.now();
+ // Pending/void records never became bounties, so they count toward nothing —
+ // including `total`, which is the number of bounties the market actually took.
+ const real = recs.filter((r) => !isTransient(r));
let open = 0, openEscrow = 0, settled = 0, paidOut = 0;
- for (const r of recs) {
+ for (const r of real) {
if (r.status === 'open' && r.expiresAt > now) { open++; openEscrow += r.amountAtomics || 0; }
if (r.status === 'settled') { settled++; paidOut += r.amountAtomics || 0; }
}
- return { open, openEscrowAtomics: openEscrow, settled, paidOutAtomics: paidOut, total: recs.length };
+ return { open, openEscrowAtomics: openEscrow, settled, paidOutAtomics: paidOut, total: real.length };
}
/** Top grinders by total USDC earned (the leaderboard). */
diff --git a/api/vanity/bounties.js b/api/vanity/bounties.js
index 567e74586..ed3af9f06 100644
--- a/api/vanity/bounties.js
+++ b/api/vanity/bounties.js
@@ -81,6 +81,8 @@ import {
} from '../../src/solana/vanity/bounty-protocol.js';
import {
createBounty,
+ activateBounty,
+ voidBounty,
getBounty,
getBountyRecord,
claimBounty,
@@ -89,7 +91,6 @@ import {
listClaimable,
bountyStats,
topGrinders,
- acquireLease,
} from '../_lib/vanity-bounty-store.js';
import { payWinner, refundRequester, payoutConfigured } from '../_lib/vanity-bounty-payout.js';
import { randomSeed } from '../../src/solana/vanity/verifiable-grind.js';
@@ -422,7 +423,12 @@ async function handleCreate(req, res, url) {
}
// Build + persist the bounty record AFTER verify but BEFORE settle, so a store
- // failure throws before the requester is charged.
+ // failure throws before the requester is charged. It is persisted as
+ // `escrow_pending`: recorded and id-reserved, but in no index, invisible to the
+ // board and to workers, and refused by both the claim and the refund
+ // compare-and-set. Only a settled escrow promotes it (activateBounty). Without
+ // that gate a settle failure would leave a live bounty backed by nothing, and
+ // the platform would pay its winner — or its expiry refund — out of pocket.
const nonce = bytesToHex(randomSeed());
const id = deriveBountyId({ recipient: parsed.recipient, pattern: parsed.pattern, amountAtomics: parsed.amountAtomics, nonce });
const now = Date.now();
@@ -440,25 +446,43 @@ async function handleCreate(req, res, url) {
nonce,
createdAt: now,
expiresAt: now + parsed.expiryHours * 3600_000,
+ status: 'escrow_pending',
// Escrow audit trail — proves the requester funded it. Not exposed publicly.
escrowPayer: verified.payer || null,
};
- let stored;
try {
- stored = await createBounty(record);
+ await createBounty(record);
} catch (err) {
return error(res, err.status || 500, err.code || 'store_failed', err.message);
}
- // Settle the escrow payment on-chain. If settle fails we still hold the bounty
- // record but mark escrow unfunded — the requester can retry the same payment
- // (idempotent). We surface the settle error so they know to retry.
+ // Settle the escrow on-chain. A failure here means we never collected the
+ // money, so the pending bounty is voided rather than left behind: an unfunded
+ // record must never reach a worker or a refund. The requester is told to retry.
let settled;
try {
settled = await settlePayment({ verified });
} catch (err) {
- return error(res, err.status || 502, err.code || 'settle_failed', err.message);
+ await voidBounty({ id, reason: `escrow settle failed: ${err.message}` }).catch(() => {});
+ return error(res, err.status || 502, err.code || 'settle_failed', `${err.message} — no bounty was posted; retry with a fresh payment`);
+ }
+
+ // Escrow collected: promote the bounty to live + indexed in one atomic step.
+ // If the store is unreachable at exactly this moment the money HAS landed, so
+ // we retry once and then hand back the settlement tx: the record stays pending
+ // with its escrow proof, recoverable, never silently dropped.
+ let activation;
+ try {
+ activation = await activateBounty({ id, escrowTx: settled.transaction, escrowNetwork: settled.network });
+ } catch {
+ activation = await activateBounty({ id, escrowTx: settled.transaction, escrowNetwork: settled.network }).catch(() => 'error');
+ }
+ if (activation !== 'live') {
+ return error(res, 502, 'activation_failed', `your escrow settled (tx ${settled.transaction || 'unknown'}) but the bounty could not be published; contact support with bounty id ${id}`, {
+ bountyId: id,
+ escrowTx: settled.transaction || null,
+ });
}
const paymentResponseHeader = encodePaymentResponseHeader(settled);