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
fix(purchase): tell a scanning wallet it is short instead of handing it a doomed transfer
nirholas90a1439f241c
diff --git a/api/purchase/skill.js b/api/purchase/skill.jsindex deb781edd..e78cf9ac0 100644--- a/api/purchase/skill.js+++ b/api/purchase/skill.js@@ -28,20 +28,22 @@*/import { PublicKey, Transaction } from '@solana/web3.js';import {+ getAccount,getAssociatedTokenAddressSync,createAssociatedTokenAccountIdempotentInstruction,createTransferCheckedInstruction,+ TokenAccountNotFoundError,+ TokenInvalidAccountOwnerError,} from '@solana/spl-token';import { sql } from '../_lib/db.js';import { env } from '../_lib/env.js';-import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';+import { cors, error, json, method, readBody, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { logEvent, resolvePayoutAddress } from '../_lib/purchase-confirm.js';import { solanaConnection } from '../_lib/solana/connection.js';import { resolveMarketplacePayer } from '../_lib/solana/gasless-tx.js';-const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';const REFERENCE_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/; // base58 Pubkey// Solana Pay wallets surface `message` on a failed request; the rest of the@@ -50,6 +52,51 @@ function payError(res, status, code, message) {return error(res, status, code, message, { message });}+// Atomic units are meaningless to a buyer reading a wallet toast, so shortfalls+// are rendered in whole tokens ("0.35"), trailing zeros trimmed.+function formatAtomics(atomics, decimals) {+ const negative = atomics < 0n;+ const digits = (negative ? -atomics : atomics).toString().padStart(decimals + 1, '0');+ const whole = digits.slice(0, digits.length - decimals);+ const fraction = decimals ? digits.slice(digits.length - decimals).replace(/0+$/, '') : '';+ return `${negative ? '-' : ''}${whole}${fraction ? `.${fraction}` : ''}`;+}++// The Solana Pay spec has the wallet POST JSON, but the header it arrives with is+// outside our control: in-app browsers and proxies routinely rewrite or drop+// `content-type`, and readJson() rejects those outright. The body is the only+// thing that matters here, so parse the raw bytes and let the account validation+// below decide, rather than answering a well-formed request with a header+// complaint the buyer cannot act on.+async function readAccount(req) {+ const raw = await readBody(req, 8_192).catch(() => null);+ if (!raw?.length) return '';+ try {+ const parsed = JSON.parse(raw.toString('utf8'));+ return typeof parsed?.account === 'string' ? parsed.account.trim() : '';+ } catch {+ return '';+ }+}++// The buyer signs a transferChecked out of their own token account, so a wallet+// that has never held this mint, or holds less than the price, produces an opaque+// simulation failure inside the wallet. Ask the chain first and turn that into a+// message the buyer can act on. Returns the balance in atomic units, or null when+// the RPC could not answer: an unreachable node must never reject a purchase the+// chain would have accepted.+async function readBuyerBalance(connection, buyerAta) {+ try {+ const account = await getAccount(connection, buyerAta, 'confirmed');+ return account.amount;+ } catch (err) {+ if (err instanceof TokenAccountNotFoundError || err instanceof TokenInvalidAccountOwnerError) {+ return 0n;+ }+ return null;+ }+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET', 'POST'])) return;@@ -103,8 +150,7 @@ export default wrap(async (req, res) => {return payError(res, 400, 'unsupported_chain', 'only solana purchases settle through this endpoint');}- const body = await readJson(req).catch(() => null);- const account = typeof body?.account === 'string' ? body.account.trim() : '';+ const account = await readAccount(req);if (!REFERENCE_RE.test(account)) {return payError(res, 400, 'validation_error', 'account must be a base58 wallet address');}@@ -136,12 +182,29 @@ export default wrap(async (req, res) => {const decimals = Number(purchase.mint_decimals ?? 6);const referenceKey = new PublicKey(reference);- const connection = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });+ // No pinned URL: solanaRpcEndpoints() puts a pinned one AHEAD of the operator's+ // SOLANA_RPC_URL and every keyed provider, so pinning the public cluster as a+ // default would make the most-throttled endpoint the primary lane for a+ // checkout. Passing nothing keeps the platform's ordered failover chain intact.+ const connection = solanaConnection({ commitment: 'confirmed' });const payer = await resolveMarketplacePayer();const feePayer = payer ? payer.publicKey : buyer;const buyerAta = getAssociatedTokenAddressSync(mintKey, buyer);const creatorAta = getAssociatedTokenAddressSync(mintKey, creatorKey);++ const required = creatorAtomics + (feeKey ? feeAtomics : 0n);+ const buyerBalance = await readBuyerBalance(connection, buyerAta);+ if (buyerBalance !== null && buyerBalance < required) {+ const short = formatAtomics(required - buyerBalance, decimals);+ return payError(+ res,+ 409,+ 'insufficient_funds',+ `this wallet is ${short} short of the ${skillLabel} price; top it up and scan again`,+ );+ }+const instructions = [];// A creator (or treasury) who has never held this mint has no token accountdiff --git a/docs/marketplace.md b/docs/marketplace.mdindex ad37956c6..1c106be1c 100644--- a/docs/marketplace.md+++ b/docs/marketplace.md@@ -101,6 +101,13 @@ purchase from an unauthenticated wallet. The seller leg is always the **last**instruction and carries the reference, because `validateTransfer` in step 3inspects only the last instruction; a fee leg is placed before it.+Before composing anything, the POST reads the buyer's token account for the+purchase mint. A wallet that has never held the mint, or holds less than the+price plus fee, gets a `409 insufficient_funds` naming the shortfall+(`"this wallet is 0.35 short of …"`) instead of a transaction that can only fail+in-wallet. If the RPC cannot answer, the transaction is built anyway and the+chain decides, so a throttled node never blocks a payable purchase.+The payment modal shows the sponsored QR first and offers a one-click swap to thedirect-transfer QR for wallets that do not implement transaction requests.diff --git a/prompts/swarm-100/api-purchase-01.md b/prompts/swarm-100/api-purchase-01.mddeleted file mode 100644index 69066d14e..000000000--- a/prompts/swarm-100/api-purchase-01.md+++ /dev/null@@ -1,101 +0,0 @@-# API audit: api/purchase batch 01 (1 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/purchase/skill.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-purchase-01.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/tests/api/purchase-skill-tx-request.test.js b/tests/api/purchase-skill-tx-request.test.jsindex 66e8b9277..f4525bc17 100644--- a/tests/api/purchase-skill-tx-request.test.js+++ b/tests/api/purchase-skill-tx-request.test.js@@ -11,7 +11,12 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { Readable } from 'node:stream';import { Keypair, PublicKey, Transaction } from '@solana/web3.js';-import { getAssociatedTokenAddressSync } from '@solana/spl-token';+import {+ ACCOUNT_SIZE,+ AccountLayout,+ TOKEN_PROGRAM_ID,+ getAssociatedTokenAddressSync,+} from '@solana/spl-token';const PAYER = Keypair.generate();const BUYER = Keypair.generate();@@ -44,9 +49,43 @@ vi.mock('../../api/_lib/purchase-confirm.js', () => ({resolvePayoutAddress: async () => payoutAddress,}));+// The buyer's SPL token account, as the chain would return it. `buyerBalance` is+// the atomic amount it holds; null means the account does not exist, and+// `rpcAnswers = false` makes the node unreachable so the "cannot answer" path+// (build the transaction anyway) is exercised.+let buyerBalance = 5_000_000n;+let rpcAnswers = true;++function tokenAccountInfo(owner, mint, amount) {+ const data = Buffer.alloc(ACCOUNT_SIZE);+ AccountLayout.encode(+ {+ mint,+ owner,+ amount,+ delegateOption: 0,+ delegate: PublicKey.default,+ delegatedAmount: 0n,+ state: 1,+ isNativeOption: 0,+ isNative: 0n,+ closeAuthorityOption: 0,+ closeAuthority: PublicKey.default,+ },+ data,+ );+ return { data, owner: TOKEN_PROGRAM_ID, lamports: 2_039_280, executable: false, rentEpoch: 0 };+}+vi.mock('../../api/_lib/solana/connection.js', () => ({solanaConnection: () => ({getLatestBlockhash: async () => ({ blockhash: BLOCKHASH, lastValidBlockHeight: 1 }),+ getAccountInfo: async (address) => {+ if (!rpcAnswers) throw new Error('failed to get info about account: fetch failed');+ const buyerAta = getAssociatedTokenAddressSync(MINT.publicKey, BUYER.publicKey);+ if (!address.equals(buyerAta) || buyerBalance === null) return null;+ return tokenAccountInfo(BUYER.publicKey, MINT.publicKey, buyerBalance);+ },}),}));@@ -80,15 +119,18 @@ function basePurchase(overrides = {}) {};}-function makeReq({ method = 'GET', query = `?reference=${REFERENCE}`, body = null } = {}) {+function makeReq({+ method = 'GET',+ query = `?reference=${REFERENCE}`,+ body = null,+ contentType = 'application/json',+} = {}) {const buf = Buffer.from(body == null ? '' : JSON.stringify(body), 'utf8');const stream = Readable.from([buf]);stream.method = method;stream.url = `/api/purchase/skill${query}`;- stream.headers = {- 'content-type': 'application/json',- 'content-length': String(buf.length),- };+ stream.headers = { 'content-length': String(buf.length) };+ if (contentType) stream.headers['content-type'] = contentType;return stream;}@@ -114,6 +156,8 @@ beforeEach(() => {purchaseRow = basePurchase();payoutAddress = SELLER.publicKey.toBase58();payerConfigured = true;+ buyerBalance = 5_000_000n;+ rpcAnswers = true;sqlMock.mockClear();logEventMock.mockClear();});@@ -228,6 +272,49 @@ describe('POST /api/purchase/skill', () => {expect(body.error).toBe('creator_wallet_missing');});+ it('reads the account from a body an in-app browser sent without a JSON content-type', async () => {+ const { res, body } = await call({+ method: 'POST',+ body: { account: BUYER.publicKey.toBase58() },+ contentType: 'text/plain;charset=UTF-8',+ });+ expect(res.statusCode).toBe(200);+ expect(body.transaction).toBeTruthy();+ });++ it('tells a buyer how far short they are instead of handing over a doomed transfer', async () => {+ buyerBalance = 650_000n; // price is 1.000000+ const { res, body } = await call({ method: 'POST', body: { account: BUYER.publicKey.toBase58() } });+ expect(res.statusCode).toBe(409);+ expect(body.error).toBe('insufficient_funds');+ expect(body.message).toContain('0.35');+ });++ it('rejects a wallet that has never held the purchase mint', async () => {+ buyerBalance = null; // no associated token account at all+ const { res, body } = await call({ method: 'POST', body: { account: BUYER.publicKey.toBase58() } });+ expect(res.statusCode).toBe(409);+ expect(body.error).toBe('insufficient_funds');+ });++ it('counts the fee leg in what the buyer must hold', async () => {+ purchaseRow = basePurchase({+ platform_fee_amount: '100000',+ platform_fee_wallet: TREASURY.publicKey.toBase58(),+ });+ buyerBalance = 999_999n; // covers the 0.9 creator leg but not creator + fee+ const { res, body } = await call({ method: 'POST', body: { account: BUYER.publicKey.toBase58() } });+ expect(res.statusCode).toBe(409);+ expect(body.error).toBe('insufficient_funds');+ });++ it('builds the transaction anyway when the RPC cannot answer the balance', async () => {+ rpcAnswers = false;+ const { res, body } = await call({ method: 'POST', body: { account: BUYER.publicKey.toBase58() } });+ expect(res.statusCode).toBe(200);+ expect(body.transaction).toBeTruthy();+ });+it('never writes a purchase row of its own', async () => {await call({ method: 'POST', body: { account: BUYER.publicKey.toBase58() } });for (const callArgs of sqlMock.mock.calls) {