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
feat: holder-pass pricing + balances refinements, pricing test
nirholas3cf7454a9023
diff --git a/api/_lib/balances.js b/api/_lib/balances.jsindex 1a76dccd3..c08dacd01 100644--- a/api/_lib/balances.js+++ b/api/_lib/balances.js@@ -20,6 +20,7 @@ import { getMetadataForMints } from './token-metadata.js';const BALANCES_TTL_S = 60;const PUBLIC_SOL_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+const PUMP_FRONTEND_BASE = process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';function heliusRpc() {const key = process.env.HELIUS_API_KEY;return key ? `https://mainnet.helius-rpc.com/?api-key=${key}` : null;@@ -92,6 +93,67 @@ async function solNativePrice() {}}+/**+ * Pick a token's USD price, preferring a positive on-chain price (Helius+ * `price_info`) and otherwise falling back to Jupiter.+ *+ * A Helius price of exactly 0 means "Helius couldn't price this", NOT "free" —+ * so it must never suppress the Jupiter fallback. The previous `helius ?? jup`+ * did exactly that: `0 ?? jup` is `0` (nullish coalescing keeps the 0), which+ * zeroed out every coin Helius returned a 0 for (common for low-liquidity+ * pump.fun coins that Jupiter prices fine). That silently mis-valued holdings+ * to $0 — and broke the /play holder gate, which reads these USD values.+ */+export function pickTokenPrice(heliusPrice, jupiterPrice) {+ const helius = Number(heliusPrice) || 0;+ if (helius > 0) return helius;+ return Number(jupiterPrice) || 0;+}++/**+ * USD price for one pump.fun coin straight from its bonding curve / market cap.+ * price = usd_market_cap / circulating supply. Covers coins Jupiter can't route+ * yet (pre-graduation, very fresh) — exactly the long tail the holder gate must+ * price correctly. Returns 0 when pump.fun has no data for the mint (not a pump+ * coin, or no price yet).+ */+async function pumpFunMintUsd(mint) {+ const c = await fetchJson(new URL(`/coins/${mint}`, PUMP_FRONTEND_BASE).toString(), {+ headers: { accept: 'application/json' },+ });+ const mcap = Number(c?.usd_market_cap) || 0;+ const decimals = Number(c?.base_decimals ?? 6);+ const supply = Number(c?.total_supply_str || c?.total_supply) || 0;+ if (mcap > 0 && supply > 0) {+ const circulating = supply / Math.pow(10, decimals);+ if (circulating > 0) return mcap / circulating;+ }+ return 0;+}++/**+ * Authoritative USD price for a single Solana mint, independent of any wallet.+ * Jupiter Lite first (routable tokens, incl. graduated pump.fun coins), then the+ * pump.fun bonding curve (pre-graduation coins Jupiter doesn't price yet).+ * Returns 0 only when neither source can price the mint.+ */+export async function solanaMintUsdPrice(mint) {+ try {+ const data = await fetchJson(`https://lite-api.jup.ag/price/v3?ids=${mint}`);+ const p = Number(data?.[mint]?.usdPrice ?? data?.[mint]?.price) || 0;+ if (p > 0) return p;+ } catch (err) {+ console.warn('[balances] jupiter single-mint price failed:', err?.message);+ }+ try {+ const p = await pumpFunMintUsd(mint);+ if (p > 0) return p;+ } catch (err) {+ console.warn('[balances] pump.fun price fallback failed:', err?.message);+ }+ return 0;+}+// -- Solana balance path: Helius DAS getAssetsByOwner --async function getSolanaBalancesViaDas(address) {@@ -197,10 +259,10 @@ async function getSolanaBalancesViaDas(address) {const tokens = fungible.map((t) => {- const price =- t.priceFromHelius ??- Number(jupPrices?.[t.mint]?.usdPrice ?? jupPrices?.[t.mint]?.price ?? 0) ??- 0;+ const price = pickTokenPrice(+ t.priceFromHelius,+ jupPrices?.[t.mint]?.usdPrice ?? jupPrices?.[t.mint]?.price,+ );return {symbol: t.symbol,name: t.name,diff --git a/api/community/holder-pass.js b/api/community/holder-pass.jsindex 7efe6dde1..8cebb97cd 100644--- a/api/community/holder-pass.js+++ b/api/community/holder-pass.js@@ -20,11 +20,16 @@import { cors, error, json, method, wrap } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { cc, userAuthHeaders, isValidToken, UnconfiguredError } from '../_lib/coin-communities.js';-import { getBalances } from '../_lib/balances.js';+import { getBalances, solanaMintUsdPrice } from '../_lib/balances.js';import { HOLDER_MIN_USD, signHolderPass } from '../_lib/holder-pass.js';const SOL_MINT = 'So11111111111111111111111111111111111111112';+// A user may have linked more than one Solana wallet over time and hold the coin+// in any of them. Read each (bounded) and gate on the combined holding so we+// never reject a real holder for linking a second, empty wallet first.+const MAX_WALLETS_CHECKED = 5;+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;@@ -53,7 +58,7 @@ export default wrap(async (req, res) => {throw err;}- // The wallet is taken from the authenticated session — never the request body.+ // The wallets are taken from the authenticated session — never the request body.const w = await api.getWallets({ headers });if (w.error) {if (w.error.statusCode === 401) {@@ -61,26 +66,59 @@ export default wrap(async (req, res) => {}return error(res, 502, 'upstream_error', w.error.message || 'failed to read wallets');}- const wallet = (w.data?.wallets ?? []).find((x) => x.chainType === 'svm')?.address || null;- if (!wallet) {+ const svmWallets = (w.data?.wallets ?? [])+ .filter((x) => x.chainType === 'svm')+ .map((x) => x.address)+ .filter(Boolean);+ if (svmWallets.length === 0) {return error(res, 403, 'wallet_required', 'link a Solana wallet to verify your holdings');}- // Price the wallet's on-chain holding of this exact coin.- let balances;- try {- balances = await getBalances({ chain: 'solana', address: wallet });- } catch (err) {- const status = err?.status === 503 ? 503 : 502;- return error(res, status, 'balance_unavailable', err?.message || 'could not read on-chain balance');+ // Sum this exact coin's holding across the user's linked Solana wallets, and+ // keep the best on-chain price any of them resolved. We report the wallet+ // holding the most of the coin.+ let amount = 0;+ let priceFromBalances = 0;+ let primaryWallet = svmWallets[0];+ let largestHolding = -1;+ let balanceError = null;+ for (const address of svmWallets.slice(0, MAX_WALLETS_CHECKED)) {+ let balances;+ try {+ balances = await getBalances({ chain: 'solana', address });+ } catch (err) {+ balanceError = err;+ continue;+ }+ const holding =+ token === SOL_MINT+ ? balances?.native+ : (balances?.tokens ?? []).find((t) => t.mint === token);+ const held = holding?.amount || 0;+ amount += held;+ if (holding?.price > 0) priceFromBalances = holding.price;+ if (held > largestHolding) {+ largestHolding = held;+ primaryWallet = address;+ }+ }+ // Only surface an upstream error if we couldn't read *any* wallet — a partial+ // failure still gates correctly on whatever we did read.+ if (amount === 0 && balanceError) {+ const status = balanceError?.status === 503 ? 503 : 502;+ return error(res, status, 'balance_unavailable', balanceError?.message || 'could not read on-chain balance');}- const holding =- token === SOL_MINT- ? balances?.native- : (balances?.tokens ?? []).find((t) => t.mint === token);- const usd = Math.round((holding?.usd || 0) * 100) / 100;- const amount = holding?.amount || 0;+ // Price the holding. The generic balance read prices via Helius/Jupiter, which+ // leaves a 0 for coins neither source routes yet (fresh bonding-curve pump.fun+ // coins). When we hold some but it came back unpriced, fetch a real price+ // (Jupiter → pump.fun curve) so a genuine holder is never gated at $0.+ let price = priceFromBalances;+ if (amount > 0 && price <= 0 && token !== SOL_MINT) {+ price = await solanaMintUsdPrice(token);+ }+ const usd = Math.round(amount * price * 100) / 100;+ const wallet = primaryWallet;const minUsd = HOLDER_MIN_USD;if (usd >= minUsd) {diff --git a/public/features.json b/public/features.jsonindex bcb206c72..e581c0706 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-01T17:25:28.156Z",+ "generated_at": "2026-06-02T16:04:52.686Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/holder-pass-pricing.test.js b/tests/holder-pass-pricing.test.jsnew file mode 100644index 000000000..df48e144f--- /dev/null+++ b/tests/holder-pass-pricing.test.js@@ -0,0 +1,80 @@+// Unit tests for the coin-pricing fix behind the /play holder gate.+//+// Regression target: a wallet holding $8+ of a coin was gated at $0 because the+// balance read discarded the Jupiter price whenever Helius reported a 0+// (`helius ?? jup` → `0 ?? jup` → 0). pickTokenPrice encodes the corrected+// precedence; solanaMintUsdPrice is the gate's authoritative re-price path+// (Jupiter → pump.fun bonding curve) for coins the generic read leaves at $0.++import { describe, it, expect, afterEach, vi } from 'vitest';+import { pickTokenPrice, solanaMintUsdPrice } from '../api/_lib/balances.js';++describe('pickTokenPrice', () => {+ it('uses the Jupiter price when Helius reports 0 (the gate-at-$0 regression)', () => {+ expect(pickTokenPrice(0, 0.0003946784630814265)).toBe(0.0003946784630814265);+ });++ it('prefers a positive Helius price over Jupiter', () => {+ expect(pickTokenPrice(72.32003, 72.0)).toBe(72.32003);+ });++ it('falls back to Jupiter when Helius is null/undefined', () => {+ expect(pickTokenPrice(null, 0.5)).toBe(0.5);+ expect(pickTokenPrice(undefined, 0.5)).toBe(0.5);+ });++ it('treats a non-numeric or negative Helius price as missing', () => {+ expect(pickTokenPrice(NaN, 0.7)).toBe(0.7);+ expect(pickTokenPrice(-5, 0.7)).toBe(0.7);+ });++ it('returns 0 only when neither source has a price', () => {+ expect(pickTokenPrice(0, 0)).toBe(0);+ expect(pickTokenPrice(null, null)).toBe(0);+ });+});++describe('solanaMintUsdPrice', () => {+ const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ const ok = (body) => ({ ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body) });++ it('returns the Jupiter price and never touches pump.fun when Jupiter prices it', async () => {+ const fetchMock = vi.fn(async (url) => {+ if (String(url).includes('lite-api.jup.ag')) return ok({ [MINT]: { usdPrice: 0.0034 } });+ throw new Error('pump.fun should not be called when Jupiter has a price');+ });+ vi.stubGlobal('fetch', fetchMock);+ expect(await solanaMintUsdPrice(MINT)).toBe(0.0034);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('falls back to the pump.fun bonding curve when Jupiter has no price', async () => {+ const fetchMock = vi.fn(async (url) => {+ const u = String(url);+ if (u.includes('lite-api.jup.ag')) return ok({}); // Jupiter can't route it+ if (u.includes('/coins/')) {+ return ok({ usd_market_cap: 11185.5, total_supply_str: '1000000000000000', base_decimals: 6 });+ }+ throw new Error('unexpected url ' + u);+ });+ vi.stubGlobal('fetch', fetchMock);+ // 11185.5 / (1e15 / 1e6) = 11185.5 / 1e9 = 0.0000111855+ expect(await solanaMintUsdPrice(MINT)).toBeCloseTo(0.0000111855, 12);+ });++ it('returns 0 when neither Jupiter nor pump.fun can price the mint', async () => {+ const fetchMock = vi.fn(async (url) => {+ const u = String(url);+ if (u.includes('lite-api.jup.ag')) return ok({});+ if (u.includes('/coins/')) return ok({}); // no market cap / supply+ throw new Error('unexpected url ' + u);+ });+ vi.stubGlobal('fetch', fetchMock);+ expect(await solanaMintUsdPrice(MINT)).toBe(0);+ });+});