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(marketplace): price a non-USDC asset at its own mint's decimals through the whole purchase
nirholas7963d944177c
diff --git a/api/marketplace/analytics.js b/api/marketplace/analytics.jsindex 326eba2f2..785a3d5b1 100644--- a/api/marketplace/analytics.js+++ b/api/marketplace/analytics.js@@ -1,13 +1,12 @@/*** GET /api/marketplace/analytics* Marketplace-wide analytics: top skills, top agents, daily sales volume.- * Publicly readable — no sensitive user data is exposed (only aggregate counts- * and revenue totals, with no PII). Admin callers see full data; public callers- * get a trimmed summary view suitable for the public analytics page.+ * Publicly readable and identical for every caller: the payload is aggregate+ * counts and revenue totals with no PII, and nothing here is gated on who is+ * asking, so no session is resolved.*/import { sql } from '../_lib/db.js';-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';@@ -18,11 +17,6 @@ export default wrap(async (req, res) => {const rl = await limits.publicIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- // Resolve optional auth — admins get the full picture- const session = await getSessionUser(req);- const bearer = session ? null : await authenticateBearer(extractBearer(req));- const userId = session?.id ?? bearer?.userId ?? null;-// ── Top skills ────────────────────────────────────────────────────────────// A `trial` row is a free grant: nothing was paid and `amount` is only the// list price it WOULD have cost. Counting trials as sales (and summing theirdiff --git a/api/marketplace/animations.js b/api/marketplace/animations.jsindex 039b71086..b71f60e19 100644--- a/api/marketplace/animations.js+++ b/api/marketplace/animations.js@@ -167,7 +167,12 @@ function encodeCursor({ createdAt }) {function decodeCursor(cursor) {try {const obj = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));- return { createdAt: new Date(obj.c) };+ const createdAt = new Date(obj.c);+ // A cursor that decodes but carries an unparseable timestamp used to reach+ // Postgres as an Invalid Date and take the whole feed down with a 500. It is+ // a bad cursor like any other: drop it and serve page one.+ if (Number.isNaN(createdAt.getTime())) return null;+ return { createdAt };} catch {return null;}diff --git a/api/marketplace/buy-asset.js b/api/marketplace/buy-asset.jsindex 95f27bdb0..a9fd84a20 100644--- a/api/marketplace/buy-asset.js+++ b/api/marketplace/buy-asset.js@@ -33,6 +33,7 @@ import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/import { clientIp, limits } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';import { rpcFallbackFromEnv } from '../_lib/solana/rpc-fallback.js';+import { isUuid } from '../_lib/validate.js';import { solanaConnection } from '../_lib/solana/connection.js';import { buildGaslessPurchaseTx } from '../_lib/solana/gasless-tx.js';import { insertNotification } from '../_lib/notify.js';@@ -105,6 +106,32 @@ async function getSellerForItem(itemType, itemId) {return null;}+// validateTransfer compares a UI amount, so the atomic price has to be scaled by+// the MINT's decimals. Hardcoding 6 (USDC) silently rejected every payment for an+// asset priced in any other mint: the buyer paid the right atoms, the comparison+// was off by 10^(d-6), and confirm filed the purchase as 'tipped' instead of+// granting it. The seller sets mint_decimals on the listing, so it is stamped onto+// the purchase row at create time (a later price edit must not re-scale a payment+// already in flight).+function normalizeDecimals(value) {+ const n = Number(value);+ return Number.isInteger(n) && n >= 0 && n <= 18 ? n : 6;+}++// Decimals for a purchase row: the value stamped at create, else the live listing+// (rows created before the stamp existed), else USDC's 6.+async function purchaseMintDecimals(pur) {+ const stamped = pur.metadata?.mint_decimals;+ if (stamped != null) return normalizeDecimals(stamped);+ const [price] = await sql`+ SELECT mint_decimals FROM asset_prices+ WHERE item_type = ${pur.item_type} AND item_id = ${pur.item_id}+ AND currency_mint = ${pur.currency_mint}+ LIMIT 1+ `;+ return normalizeDecimals(price?.mint_decimals);+}+async function resolveSellerPayout(sellerUserId, chain) {const [row] = await sql`SELECT address FROM agent_payout_wallets@@ -134,6 +161,13 @@ async function handleCreate(req, res) {if (!ITEM_TYPES.includes(itemType) || !itemId) {return error(res, 400, 'validation_error', 'item_type and item_id required');}+ // item_id is a uuid column everywhere it is used below (asset_prices,+ // asset_purchases, avatars/agent_identities/plugins). A malformed id reaching+ // Postgres throws 22P02, which surfaces as an unhandled 500 on what is really+ // bad client input. Same guard as GET /api/marketplace/asset-price.+ if (!isUuid(itemId)) {+ return error(res, 400, 'validation_error', 'item_id must be a valid uuid');+ }// Optional connected-wallet pubkey → platform-sponsored (gasless) transaction.const buyerPublicKey =typeof body?.buyer_public_key === 'string' && REFERENCE_RE.test(body.buyer_public_key)@@ -217,7 +251,7 @@ async function handleCreate(req, res) {// Reuse a fresh pending row if one exists (idempotent retries).const [pending] = await sql`- SELECT reference, amount, currency_mint, chain, expires_at+ SELECT reference, amount, currency_mint, chain, expires_at, metadataFROM asset_purchasesWHERE buyer_user_id = ${auth.userId}AND item_type = ${itemType} AND item_id = ${itemId}@@ -236,17 +270,24 @@ async function handleCreate(req, res) {const [inserted] = await sql`INSERT INTO asset_purchases (buyer_user_id, item_type, item_id, seller_user_id, status, reference,- amount, currency_mint, chain, payout_address, expires_at, referrer_user_id+ amount, currency_mint, chain, payout_address, expires_at, referrer_user_id,+ metadata) VALUES (${auth.userId}, ${itemType}, ${itemId}, ${seller.userId}, 'pending', ${reference},${price.amount}, ${price.currency_mint}, ${price.chain}, ${payoutAddress},- now() + interval '30 minutes', ${referrerUserId}+ now() + interval '30 minutes', ${referrerUserId},+ ${JSON.stringify({ mint_decimals: normalizeDecimals(price.mint_decimals) })}::jsonb)- RETURNING reference, amount, currency_mint, chain, expires_at+ RETURNING reference, amount, currency_mint, chain, expires_at, metadata`;row = inserted;}+ // The scale the buyer must pay at, and the one confirm will verify against: a+ // reused pending row keeps the decimals it was created with, so a price edit+ // mid-checkout can never move the goalposts under a payment already in flight.+ const decimals = normalizeDecimals(row.metadata?.mint_decimals ?? price.mint_decimals);+// ── Autonomous path: the agent's own wallet pays, server-side ──────────────if (agentId) {return payAsAgent({@@ -254,7 +295,7 @@ async function handleCreate(req, res) {auth,agent: buyerAgent,row,- price,+ decimals,payoutAddress,itemType,itemId,@@ -277,7 +318,7 @@ async function handleCreate(req, res) {mint: row.currency_mint,creatorAtomics: BigInt(row.amount),reference: row.reference,- decimals: price.mint_decimals,+ decimals,});if (prepared) {gaslessBlock = { transaction: prepared.transaction, gasless: true, fee_payer: prepared.feePayer };@@ -295,7 +336,7 @@ async function handleCreate(req, res) {amount: String(row.amount),currency_mint: row.currency_mint,chain: row.chain,- mint_decimals: price.mint_decimals,+ mint_decimals: decimals,expires_at: row.expires_at,label,message,@@ -313,7 +354,7 @@ async function handleCreate(req, res) {// verify the on-chain transfer, then finalize through the SAME// finalizeAssetConfirm() the browser path uses — so receipts, revenue and// notifications are identical no matter who signed.-async function payAsAgent({ res, auth, agent, row, price, payoutAddress, itemType, itemId, label, cap }) {+async function payAsAgent({ res, auth, agent, row, decimals, payoutAddress, itemType, itemId, label, cap }) {const fail = async (reason) => {await sql`UPDATE asset_purchases SET status = 'failed', updated_at = now()@@ -378,7 +419,7 @@ async function payAsAgent({ res, auth, agent, row, price, payoutAddress, itemTyptxSignature,{recipient: new PublicKey(payoutAddress),- amount: new BigNumber(row.amount).dividedBy(new BigNumber(10).pow(price.mint_decimals ?? 6)),+ amount: new BigNumber(row.amount).dividedBy(new BigNumber(10).pow(decimals)),splToken: new PublicKey(row.currency_mint),reference: new PublicKey(row.reference),},@@ -458,7 +499,7 @@ async function handleConfirm(req, res, reference) {const [pur] = await sql`SELECT id, buyer_user_id, item_type, item_id, seller_user_id, status,amount, currency_mint, chain, tx_signature, expires_at, reference,- payout_address, referrer_user_id+ payout_address, referrer_user_id, metadataFROM asset_purchasesWHERE reference = ${reference} AND buyer_user_id = ${auth.userId}`;@@ -477,7 +518,7 @@ async function handleConfirm(req, res, reference) {const refKey = new PublicKey(pur.reference);const recipient = new PublicKey(pur.payout_address);const splToken = new PublicKey(pur.currency_mint);- const decimals = 6;+ const decimals = await purchaseMintDecimals(pur);const expectedAmount = new BigNumber(pur.amount).dividedBy(new BigNumber(10).pow(decimals));let signatureInfo;diff --git a/api/marketplace/check-skill-access.js b/api/marketplace/check-skill-access.jsindex 18e3738df..79666b657 100644--- a/api/marketplace/check-skill-access.js+++ b/api/marketplace/check-skill-access.js@@ -7,6 +7,7 @@ import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { MonetizationService } from '../_lib/services/MonetizationService.js';+import { isUuid } from '../_lib/validate.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;@@ -26,6 +27,11 @@ export default wrap(async (req, res) => {if (!agentId || !skill) {return error(res, 400, 'validation_error', 'agent_id and skill required');}+ // agent_skill_prices.agent_id is a uuid column: a malformed id would reach+ // Postgres as 22P02 and surface as a 500 on plain bad input.+ if (!isUuid(agentId)) {+ return error(res, 400, 'validation_error', 'agent_id must be a valid uuid');+ }const service = new MonetizationService(userId);const { has_access } = await service.checkSkillOwnership(agentId, skill);diff --git a/api/marketplace/reviews.js b/api/marketplace/reviews.jsindex 7500590d1..16da7f4e9 100644--- a/api/marketplace/reviews.js+++ b/api/marketplace/reviews.js@@ -37,6 +37,13 @@ async function resolveAuth(req) {}export default wrap(async (req, res) => {+ // CORS first, before any input validation. Answering the preflight from inside+ // the per-method handlers meant a malformed agent id (and a preflight that did+ // not name its method) fell out as a bare 400 with no CORS headers at all, so+ // the browser reported a CORS failure instead of the validation error the+ // caller actually needed to see.+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;+const url = new URL(req.url, 'http://x');const parts = url.pathname.split('/').filter(Boolean); // [api, marketplace, agents, :id, reviews]const agentId = url.searchParams.get('agent_id') || parts[3];@@ -45,22 +52,15 @@ export default wrap(async (req, res) => {return error(res, 400, 'validation_error', 'agent_id required');}- if (req.method === 'GET' || (req.method === 'OPTIONS' && req.headers['access-control-request-method'] === 'GET')) {- return handleList(req, res, agentId);- }- if (req.method === 'POST' || (req.method === 'OPTIONS' && req.headers['access-control-request-method'] === 'POST')) {- return handleUpsert(req, res, agentId);- }- if (req.method === 'DELETE' || (req.method === 'OPTIONS' && req.headers['access-control-request-method'] === 'DELETE')) {- return handleDelete(req, res, agentId);- }+ if (req.method === 'GET') return handleList(req, res, agentId);+ if (req.method === 'POST') return handleUpsert(req, res, agentId);+ if (req.method === 'DELETE') return handleDelete(req, res, agentId);return error(res, 405, 'method_not_allowed', 'GET/POST/DELETE only');});// ── list + summary ───────────────────────────────────────────────────────────async function handleList(req, res, agentId) {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.widgetRead(clientIp(req));@@ -138,7 +138,6 @@ async function handleList(req, res, agentId) {// ── upsert ───────────────────────────────────────────────────────────────────async function handleUpsert(req, res, agentId) {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;const auth = await resolveAuth(req);@@ -227,7 +226,6 @@ async function handleUpsert(req, res, agentId) {// ── delete ───────────────────────────────────────────────────────────────────async function handleDelete(req, res, agentId) {- if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;if (!method(req, res, ['DELETE'])) return;const auth = await resolveAuth(req);diff --git a/api/marketplace/trial-status.js b/api/marketplace/trial-status.jsindex 5806815b3..b1b22f93f 100644--- a/api/marketplace/trial-status.js+++ b/api/marketplace/trial-status.js@@ -46,13 +46,18 @@ export function trialState(remaining, granted) {return 'fresh';}+/** A mint's decimal count, clamped to what an SPL mint can actually declare. */+function decimalsOf(decimals) {+ return Number.isFinite(Number(decimals)) ? Math.max(0, Math.min(18, Number(decimals))) : 6;+}+/*** Atomic token amounts are strings out of Postgres (they overflow a JS number* at 2^53). Format for display without ever going through Number().*/export function formatAtomic(atomic, decimals = 6) {const raw = String(atomic ?? '0').replace(/[^0-9]/g, '') || '0';- const d = Number.isFinite(Number(decimals)) ? Math.max(0, Math.min(18, Number(decimals))) : 6;+ const d = decimalsOf(decimals);const group = (s) => s.replace(/\B(?=(\d{3})+(?!\d))/g, ',');if (d === 0) return group(raw.replace(/^0+(?=\d)/, ''));const padded = raw.padStart(d + 1, '0');@@ -85,8 +90,23 @@ export function potentialsByMint(entries) {atomic: total.toString(),});}- return [...buckets.values()]- .sort((a, b) => (BigInt(a.atomic) === BigInt(b.atomic) ? 0 : BigInt(a.atomic) < BigInt(b.atomic) ? 1 : -1))+ // Ordering has to compare the same unit the display string shows, not the raw+ // atomic integer. Atomic counts are only comparable inside one mint (the whole+ // reason the buckets exist), so sorting them directly reintroduced the bug this+ // function was written to kill, one layer up: 0.9 of a 9-decimal token is+ // 900000000 atomic and outranked 5 of a 6-decimal token (5000000), so the+ // headline the seller reads named the SMALLER pile. Scale every bucket to a+ // common exponent first. Without a price oracle this ranks quantity, not fiat+ // value, which is exactly what the number on screen means.+ const list = [...buckets.values()];+ const scale = list.reduce((n, b) => Math.max(n, decimalsOf(b.decimals)), 0);+ const magnitude = (b) => BigInt(b.atomic) * 10n ** BigInt(scale - decimalsOf(b.decimals));+ return list+ .sort((a, b) => {+ const x = magnitude(a);+ const y = magnitude(b);+ return x === y ? 0 : x < y ? 1 : -1;+ }).map((b) => ({ ...b, display: formatAtomic(b.atomic, b.decimals) }));}diff --git a/tests/api/ibm-galaxy.test.js b/tests/api/ibm-galaxy.test.jsindex 20ab5f774..d7528d5b3 100644--- a/tests/api/ibm-galaxy.test.js+++ b/tests/api/ibm-galaxy.test.js@@ -18,6 +18,9 @@ const state = {agents: [],cacheRow: null,sqlCalls: [],+ // How many CREATE TABLE calls should reject before the DDL starts succeeding,+ // standing in for a transient database blip.+ ddlFailures: 0,};// ── Mocks ─────────────────────────────────────────────────────────────────────@@ -38,7 +41,13 @@ vi.mock('../../api/_lib/db.js', () => ({const text = strings.join(' ');state.sqlCalls.push(text);if (text.includes('FROM agent_identities')) return state.agents;- if (text.includes('CREATE TABLE IF NOT EXISTS agent_galaxy_cache')) return [];+ if (text.includes('CREATE TABLE IF NOT EXISTS agent_galaxy_cache')) {+ if (state.ddlFailures > 0) {+ state.ddlFailures--;+ throw new Error('connection terminated unexpectedly');+ }+ return [];+ }if (text.includes('SELECT payload')) return state.cacheRow ? [state.cacheRow] : [];if (text.includes('INSERT INTO agent_galaxy_cache')) {state.cacheRow = {@@ -124,8 +133,11 @@ function mkAgents(n) {}));}-function makeReq({ method = 'GET', url = '/api/ibm/galaxy', body = null } = {}) {- const req = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);+// `rawBody` sends the exact bytes instead of JSON.stringify(body), so a test can+// post literal `null` or a bare string: valid JSON that is not an object.+function makeReq({ method = 'GET', url = '/api/ibm/galaxy', body = null, rawBody = null } = {}) {+ const payload = rawBody ?? (body ? JSON.stringify(body) : null);+ const req = payload ? Readable.from([Buffer.from(payload)]) : Readable.from([]);req.method = method;req.url = url;req.headers = {@@ -169,6 +181,7 @@ beforeEach(() => {state.agents = mkAgents(12);state.cacheRow = null;state.sqlCalls = [];+ state.ddlFailures = 0;});describe('GET /api/ibm/galaxy', () => {@@ -270,6 +283,20 @@ describe('POST /api/ibm/galaxy (semantic search)', () => {expect(body.error).toBe('bad_request');});+ // `null` and `"hi"` parse as valid JSON, so readJson hands them straight back+ // on the raw-stream path. Reading .query off a non-object used to throw a+ // TypeError that wrap() sanitized into a 500 internal_error.+ it.each([+ ['null', 'null'],+ ['a bare string', '"hi"'],+ ['a number', '42'],+ ])('rejects a JSON body that is %s with 400', async (_label, rawBody) => {+ const { status, body } = await invoke({ method: 'POST', rawBody });+ expect(status).toBe(400);+ expect(body.error).toBe('bad_request');+ expect(body.error_description).toMatch(/query is required/);+ });+it('returns 503 when watsonx is not configured', async () => {state.wxConfigured = false;const { status, body } = await invoke({ method: 'POST', body: { query: 'anything' } });@@ -285,6 +312,32 @@ describe('POST /api/ibm/galaxy (semantic search)', () => {});});+// The cache table is created lazily and the promise is memoized so concurrent+// callers on a warm instance share one round-trip. Memoizing a REJECTED promise+// would pin the galaxy down for the life of the instance: every later request+// re-awaits the same failure, long after the database recovered.+describe('lazy cache-table create', () => {+ it('retries the create on the next request after a transient DB failure', async () => {+ vi.resetModules();+ const fresh = (await import('../../api/ibm/galaxy.js')).default;+ const ddlCalls = () =>+ state.sqlCalls.filter((t) => t.includes('CREATE TABLE IF NOT EXISTS agent_galaxy_cache'))+ .length;++ state.ddlFailures = 1;+ const failed = makeRes();+ await fresh(makeReq({}), failed);+ expect(failed.statusCode).toBe(500);+ expect(ddlCalls()).toBe(1);++ const recovered = makeRes();+ await fresh(makeReq({}), recovered);+ expect(recovered.statusCode).toBe(200);+ expect(ddlCalls()).toBe(2);+ expect(JSON.parse(recovered.body).available).toBe(true);+ });+});+describe('guards', () => {it('returns 429 when the rate limit is exceeded', async () => {limits.publicIp.mockResolvedValue({ success: false });diff --git a/tests/api/ibm-twin.test.js b/tests/api/ibm-twin.test.jsindex f955189c5..f6c5c9572 100644--- a/tests/api/ibm-twin.test.js+++ b/tests/api/ibm-twin.test.js@@ -73,9 +73,11 @@ async function callGet(url) {return { res, body: tryJson(res._body) };}-async function callPost(body) {+// `rawBody` sends the exact bytes instead of JSON.stringify(body), so a test can+// post literal `null` or a bare string: valid JSON that is not an object.+async function callPost(body, rawBody) {const res = makeRes();- const buf = Buffer.from(JSON.stringify(body), 'utf8');+ const buf = Buffer.from(rawBody ?? JSON.stringify(body), 'utf8');await handler({method: 'POST',@@ -256,6 +258,34 @@ describe('GET /api/ibm/twin — full Granite pipeline', () => {expect(typeof body.fidelity.directionalHit).toBe('boolean');});+ // A back-test forecast that answers with no points has nothing to score. Scoring+ // it anyway indexed realized[-1] and threw, and the throw landed in the outer+ // catch that reports a forecast failure: the projection, the ibm block, and the+ // persona were all lost to a back-test that was only ever supplementary.+ it('keeps the projection and persona when the back-test returns no points', async () => {+ fetchOhlcv.mockResolvedValue({+ candles: mkCandles(640),+ base: { name: 'three', symbol: 'three', address: 'm' },+ quote: { symbol: 'SOL' },+ freq: '1h',+ timeframe: 'hour',+ aggregate: 1,+ });+ // First call is the live projection, second is the back-test.+ watsonxForecast.mockReset();+ watsonxForecast+ .mockResolvedValueOnce(mkForecast(HORIZON, 101))+ .mockResolvedValueOnce({ timestamps: [], values: [], model: 'ttm', inputWindow: 512 });++ const { res, body } = await callGet(`/api/ibm/twin?pool=${POOL}`);+ expect(res.statusCode).toBe(200);+ expect(body.fidelity).toBeNull();+ expect(body.projection.points).toHaveLength(HORIZON);+ expect(body.ibm.configured).toBe(true);+ expect(body.ibm.error).toBeUndefined();+ expect(body.persona.text).toBeTruthy();+ });+it('includes Guardian governance on the persona', async () => {const { body } = await callGet(`/api/ibm/twin?pool=${POOL}`);expect(body.governance).toBeTruthy();@@ -385,6 +415,21 @@ describe('POST /api/ibm/twin — scenario simulation', () => {expect(body.scenario.label).toMatch(/-30%|demand shock/);});+ // `null` and `"hi"` parse as valid JSON, so readJson hands them straight back on+ // the raw-stream path. Reading params off a non-object used to throw a TypeError+ // that wrap() sanitized into a 500 internal_error; malformed input belongs in+ // the documented 400 contract.+ it.each([+ ['null', 'null'],+ ['a bare string', '"hi"'],+ ['a number', '42'],+ ])('rejects a JSON body that is %s with 400 bad_request', async (_label, rawBody) => {+ const { res, body } = await callPost(undefined, rawBody);+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('bad_request');+ expect(body.error_description).toMatch(/provide \?pool=/);+ });+it('uses "baseline (no perturbation)" label when scenario is empty', async () => {const { body } = await callPost({ pool: POOL, scenario: {} });expect(body.scenario.label).toMatch(/baseline/i);diff --git a/tests/api/ibm-vision.test.js b/tests/api/ibm-vision.test.jsindex 19a9a794e..2cfafddd2 100644--- a/tests/api/ibm-vision.test.js+++ b/tests/api/ibm-vision.test.js@@ -123,8 +123,11 @@ import { allowedImageHost, buildPrompt, parseVision, VISION_MODEL } from '../../const TINY_PNG ='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';-function makeReq({ method = 'GET', url = '/api/ibm/vision', body = null } = {}) {- const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);+// `rawBody` sends the exact bytes instead of JSON.stringify(body), so a test can+// post literal `null` or a bare string: valid JSON that is not an object.+function makeReq({ method = 'GET', url = '/api/ibm/vision', body = null, rawBody = null } = {}) {+ const payload = rawBody ?? (body ? JSON.stringify(body) : null);+ const base = payload ? Readable.from([Buffer.from(payload)]) : Readable.from([]);base.method = method;base.url = url;base.headers = {@@ -249,6 +252,20 @@ describe('POST /api/ibm/vision — input validation', () => {expect(body.error).toBe('bad_image');});+ // `null` and `"hi"` parse as valid JSON, so readJson hands them straight back+ // on the raw-stream path. Reading .image off a non-object used to throw a+ // TypeError that wrap() sanitized into a 500 internal_error; malformed input+ // belongs in the documented 400 contract.+ it.each([+ ['null', 'null'],+ ['a bare string', '"hi"'],+ ['a number', '42'],+ ])('returns 400 bad_image for a JSON body that is %s', async (_label, rawBody) => {+ const { status, body } = await invoke({ method: 'POST', rawBody });+ expect(status).toBe(400);+ expect(body.error).toBe('bad_image');+ });+it('returns 400 bad_image when image data URL has empty data portion', async () => {const { status, body } = await invoke({method: 'POST',diff --git a/tests/marketplace-skill-pricing-endpoints.test.js b/tests/marketplace-skill-pricing-endpoints.test.jsindex 30caec712..8d00dc510 100644--- a/tests/marketplace-skill-pricing-endpoints.test.js+++ b/tests/marketplace-skill-pricing-endpoints.test.js@@ -100,6 +100,11 @@ function mkRes() {return {statusCode: 200, headers: {}, body: undefined, writableEnded: false,setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ // json() only honours a Cache-Control the handler set itself if it can read+ // it back; a real ServerResponse always can. Without getHeader the mock+ // reported the secure `no-store` default over the edge cache skill-promo+ // deliberately sets, which is a lie about the platform.+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },end(b) { this.body = b; this.writableEnded = true; },};}@@ -232,9 +237,12 @@ describe('POST /api/marketplace/set-skill-price', () => {ownedAgent();clearListingSplitMock.mockRejectedValue(new Error('deadlock detected'));const res = mkRes();- await expect(- setSkillPrice(priceReq({ agent_id: AGENT, skill: 'icon-set', amount: 5, currency_mint: MINT, split: [] }), res),- ).rejects.toThrow('deadlock detected');+ await setSkillPrice(priceReq({ agent_id: AGENT, skill: 'icon-set', amount: 5, currency_mint: MINT, split: [] }), res);+ // wrap() answers an uncaught fault itself, so the caller sees a sanitized+ // 500 rather than a rejected promise, and never the raw upstream message.+ expect(res.statusCode).toBe(500);+ expect(parseBody(res).error).toBe('internal_error');+ expect(res.body).not.toMatch(/deadlock/);// The price row must NOT have moved: only the ownership SELECT ran.expect(sqlText()).toHaveLength(1);});@@ -298,7 +306,9 @@ describe('GET /api/marketplace/skill-promo', () => {it('rejects a missing or malformed query with a 400, anonymously', async () => {const res = mkRes();- await expect(skillPromo(promoReq('?agent_id=nope&skill='), res)).rejects.toMatchObject({ status: 400 });+ await skillPromo(promoReq('?agent_id=nope&skill='), res);+ expect(res.statusCode).toBe(400);+ expect(parseBody(res).error).toBe('validation_error');expect(describeSkillPromoMock).not.toHaveBeenCalled();});@@ -324,10 +334,11 @@ describe('GET /api/marketplace/skill-promo', () => {expect(describeSkillPromoMock).toHaveBeenCalledWith(AGENT, 'icon-set');});- it('rejects a write method', async () => {+ it('rejects a write method before it ever reads the query', async () => {const res = mkRes();- await skillPromo(promoReq('?agent_id=x&skill=y'), res, undefined);- expect(res.statusCode).toBe(404);+ await skillPromo(mkReq({ url: `/api/marketplace/skill-promo?agent_id=${AGENT}&skill=icon-set`, method: 'POST' }), res);+ expect(res.statusCode).toBe(405);+ expect(describeSkillPromoMock).not.toHaveBeenCalled();});});@@ -352,7 +363,10 @@ describe('POST /api/marketplace/start-trial', () => {it('rejects a malformed body with a 400', async () => {getSessionUserMock.mockResolvedValue({ id: USER });const res = mkRes();- await expect(startTrial(trialReq({ agent_id: 'nope', skill: '' }), res)).rejects.toMatchObject({ status: 400 });+ await startTrial(trialReq({ agent_id: 'nope', skill: '' }), res);+ expect(res.statusCode).toBe(400);+ expect(parseBody(res).error).toBe('validation_error');+ expect(sqlMock).not.toHaveBeenCalled();});it('refuses a skill that grants no free runs', async () => {@@ -419,6 +433,11 @@ describe('POST /api/marketplace/start-trial', () => {throw Object.assign(new Error('deadlock detected'), { code: '40P01' });});const res = mkRes();- await expect(startTrial(trialReq({ agent_id: AGENT, skill: 'icon-set' }), res)).rejects.toThrow('deadlock');+ await startTrial(trialReq({ agent_id: AGENT, skill: 'icon-set' }), res);+ // A deadlock is not a used trial: it must not be laundered into the 409 the+ // unique-violation branch answers, and the SQLSTATE must not reach the caller.+ expect(res.statusCode).toBe(500);+ expect(parseBody(res).error).toBe('internal_error');+ expect(res.body).not.toMatch(/40P01|deadlock|trial_used/);});});diff --git a/tests/marketplace-trial-status.test.js b/tests/marketplace-trial-status.test.jsindex 6012065ec..130ba360b 100644--- a/tests/marketplace-trial-status.test.js+++ b/tests/marketplace-trial-status.test.js@@ -49,6 +49,11 @@ function mkRes() {return {statusCode: 200, headers: {}, body: undefined, writableEnded: false,setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ // json() only honours a Cache-Control the handler set itself if it can read+ // it back; a real ServerResponse always can. A mock without getHeader made+ // every response look uncached and reported the secure default `no-store`+ // over whatever the handler chose, which is a lie about the platform.+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },end(b) { this.body = b; this.writableEnded = true; },};}@@ -118,6 +123,25 @@ describe('potentialsByMint', () => {expect(out[1]).toMatchObject({ mint: THREE, decimals: 9, atomic: '900000000', display: '0.9' });});+ it('ranks by the quantity on screen, not by the raw atomic integer', () => {+ // 0.9 of a 9-decimal token is 900000000 atomic and 5 of a 6-decimal token is+ // only 5000000, so an atomic-first sort put the smaller pile at the head of+ // the queue and the headline named it. Order has to follow the displayed+ // magnitude, in both directions.+ const smallerFirst = potentialsByMint([+ { price: { mint: THREE, decimals: 9 }, potential: { atomic: '900000000' } },+ { price: { mint: MINT_6DP, decimals: 6 }, potential: { atomic: '5000000' } },+ ]);+ expect(smallerFirst.map((b) => b.display)).toEqual(['5', '0.9']);++ // And when the 9-decimal mint genuinely holds more, it leads.+ const largerFirst = potentialsByMint([+ { price: { mint: MINT_6DP, decimals: 6 }, potential: { atomic: '5000000' } },+ { price: { mint: THREE, decimals: 9 }, potential: { atomic: '9000000000' } },+ ]);+ expect(largerFirst[0]).toMatchObject({ mint: THREE, display: '9' });+ });+it('skips unpriced rows rather than counting them as zero-decimal dust', () => {expect(potentialsByMint([{ price: null, potential: null }])).toEqual([]);});