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
chore: wire NFT-gated skills into dashboard and add room QA script
nirholasacb7d4d6755f
diff --git a/api/_lib/nft-gate.js b/api/_lib/nft-gate.jsnew file mode 100644index 000000000..ffd1bed6a--- /dev/null+++ b/api/_lib/nft-gate.js@@ -0,0 +1,159 @@+// NFT-gated skills — "does this wallet hold ≥1 NFT from a given collection?".+//+// Backs the `gate_type = 'nft'` access path in skill-access.js. A creator can+// restrict a skill to holders of a specific Solana NFT collection; access is the+// live, on-chain answer rather than a stored purchase. We resolve it with the+// Helius Digital Asset Standard (DAS) `searchAssets` RPC, which indexes both+// regular (Token Metadata / Metaplex Certified Collection) and compressed+// (Bubblegum) NFTs and lets us filter by `ownerAddress` + collection grouping in+// a single call — so checking "holds one of collection X" costs one request per+// (wallet, collection), with `limit: 1` since presence is all we need.+//+// Fail-closed by contract: every caller treats a thrown error as "no access".+// A gated skill must never be unlocked by an RPC hiccup, so this module throws+// loudly (it never returns a false "true") and the access layer denies on throw.+//+// Env: HELIUS_API_KEY (preferred) or a SOLANA_RPC_URL already pointed at a Helius+// DAS-capable endpoint. DAS is a Helius extension, not a standard Solana RPC+// method, so the generic failover pool in solana/connection.js can't serve it —+// we target Helius directly here.++import { sql } from './db.js';+import { normalizeRpcUrl } from './solana/connection.js';++const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++// DAS calls run inside serverless functions with a hard maxDuration; a hung+// socket must not pin the function open. 8s is generous for an indexed read.+const DAS_TIMEOUT_MS = 8_000;++/** True when `addr` is a syntactically valid base58 Solana address/mint. */+export function isValidSolanaAddress(addr) {+ return typeof addr === 'string' && SOLANA_ADDRESS_RE.test(addr.trim());+}++/**+ * Resolve a Helius DAS-capable RPC URL, or null when none is configured.+ * Prefers the dedicated HELIUS_API_KEY; falls back to SOLANA_RPC_URL only when+ * it already points at a Helius host (the sole provider in our stack exposing+ * the DAS `searchAssets` method).+ */+export function dasRpcUrl() {+ const key = process.env.HELIUS_API_KEY;+ if (key) return `https://mainnet.helius-rpc.com/?api-key=${key}`;+ const configured = normalizeRpcUrl(process.env.SOLANA_RPC_URL || '');+ if (configured && /helius-rpc\.com/i.test(configured)) return configured;+ return null;+}++/** True when NFT gating can be enforced (a DAS endpoint is configured). */+export function nftGateEnabled() {+ return Boolean(dasRpcUrl());+}++/**+ * Raw DAS `searchAssets` call. Exposed for tests via the `fetchImpl` override;+ * production callers use the default global fetch. Throws on transport error,+ * non-200, or a JSON-RPC error envelope so the fail-closed contract holds.+ */+export async function dasSearchAssets(params, { fetchImpl = fetch, rpcUrl = dasRpcUrl() } = {}) {+ if (!rpcUrl) throw new Error('NFT gating requires a Helius DAS RPC endpoint (set HELIUS_API_KEY)');+ const r = await fetchImpl(rpcUrl, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 'nft-gate', method: 'searchAssets', params }),+ signal: AbortSignal.timeout(DAS_TIMEOUT_MS),+ });+ if (!r.ok) throw new Error(`das searchAssets ${r.status}`);+ const body = await r.json();+ if (body?.error) throw new Error(`das error ${body.error.code}: ${body.error.message}`);+ return body?.result || { items: [], total: 0 };+}++/**+ * Does `wallet` currently hold at least one NFT grouped under `collectionMint`?+ * One indexed read; throws on any failure (fail-closed).+ *+ * @param {string} wallet owner base58 address+ * @param {string} collectionMint collection mint base58 address+ * @param {{ fetchImpl?: Function, rpcUrl?: string }} [opts]+ * @returns {Promise<boolean>}+ */+export async function walletHoldsCollectionNft(wallet, collectionMint, opts = {}) {+ if (!isValidSolanaAddress(wallet) || !isValidSolanaAddress(collectionMint)) return false;+ const result = await dasSearchAssets(+ {+ ownerAddress: wallet.trim(),+ grouping: ['collection', collectionMint.trim()],+ // Listed/escrowed assets and burns must not count as "held".+ burnt: false,+ page: 1,+ limit: 1,+ },+ opts,+ );+ const items = Array.isArray(result.items) ? result.items : [];+ return items.length > 0;+}++/**+ * Does ANY of `wallets` hold an NFT from `collectionMint`? Resolves to true on+ * the first holding wallet. Throws if every check throws (fail-closed: an+ * all-error result is indistinguishable from "couldn't verify").+ *+ * @param {string[]} wallets+ * @param {string} collectionMint+ * @param {{ fetchImpl?: Function, rpcUrl?: string }} [opts]+ * @returns {Promise<boolean>}+ */+export async function anyWalletHoldsCollection(wallets, collectionMint, opts = {}) {+ const unique = [...new Set((wallets || []).filter(isValidSolanaAddress))];+ if (unique.length === 0) return false;+ const results = await Promise.allSettled(+ unique.map((w) => walletHoldsCollectionNft(w, collectionMint, opts)),+ );+ if (results.some((r) => r.status === 'fulfilled' && r.value === true)) return true;+ // No wallet held it. If at least one check actually completed, that's a real+ // "false". If every check threw, we genuinely couldn't verify — rethrow so the+ // caller denies access rather than treating an outage as "not a holder".+ if (results.every((r) => r.status === 'rejected')) {+ throw results[0].reason || new Error('all NFT ownership checks failed');+ }+ return false;+}++/**+ * The Solana wallet addresses linked to a user, across both the canonical+ * `users.wallet_address` (their primary login wallet) and any additional+ * `user_wallets` rows of chain_type 'solana'. Deduped. Empty when none.+ *+ * @param {string} userId+ * @returns {Promise<string[]>}+ */+export async function getUserSolanaWallets(userId) {+ if (!userId) return [];+ const rows = await sql`+ SELECT address FROM user_wallets+ WHERE user_id = ${userId} AND chain_type = 'solana' AND address IS NOT NULL+ UNION+ SELECT wallet_address AS address FROM users+ WHERE id = ${userId} AND wallet_address IS NOT NULL+ `.catch(() => []);+ return [...new Set(rows.map((r) => r.address).filter(isValidSolanaAddress))];+}++/**+ * Does `userId` hold an NFT from `collectionMint` in any linked Solana wallet?+ * Throws on RPC failure (fail-closed). Returns false when the user has no linked+ * Solana wallet — there is nothing to check against.+ *+ * @param {string} userId+ * @param {string} collectionMint+ * @param {{ fetchImpl?: Function, rpcUrl?: string }} [opts]+ * @returns {Promise<boolean>}+ */+export async function userHoldsCollection(userId, collectionMint, opts = {}) {+ const wallets = await getUserSolanaWallets(userId);+ if (wallets.length === 0) return false;+ return anyWalletHoldsCollection(wallets, collectionMint, opts);+}diff --git a/api/irl/pins.js b/api/irl/pins.jsindex 12fafb255..65459e1fa 100644--- a/api/irl/pins.js+++ b/api/irl/pins.js@@ -1288,7 +1288,7 @@ export default wrap(async (req, res) => {// must carry a fuzz radius (clamped to the sane band); a missing/invalid// placement (or an old client that sends neither) defaults to 'precise' with// no radius, so behaviour is unchanged for every existing caller.- const rawKind = String(body.placementKind ?? body.placement_kind ?? '').toLowerCase();+ const rawKind = String(body.placement ?? body.placementKind ?? body.placement_kind ?? '').toLowerCase();const placementKind = PLACEMENT_KINDS.has(rawKind) ? rawKind : 'precise';const rawFuzz = Number(body.fuzzRadiusM ?? body.fuzz_radius_m);const fuzzRadiusM = placementKind === 'approximate' && Number.isFinite(rawFuzz)diff --git a/scripts/irl-room-qa.mjs b/scripts/irl-room-qa.mjsnew file mode 100644index 000000000..d2eb88e58--- /dev/null+++ b/scripts/irl-room-qa.mjs@@ -0,0 +1,254 @@+// R5 — IRL room-anchor QA preflight (the hardware-free half of the protocol).+//+// node scripts/irl-room-qa.mjs # offline invariants only+// node scripts/irl-room-qa.mjs --url https://three.ws # + probe deployed API+//+// What this is — and is NOT+// ─────────────────────────+// R5 (tasks/irl-room-anchor/R5-on-device-qa.md) is fundamentally an ON-DEVICE+// protocol: the 360° turn-to-see test, the cross-user check, and the permission+// gates can only be judged on a real phone with a camera, compass, and GPS. This+// sandbox has none of those, so they CANNOT be run here and this script does not+// pretend to. It locks down everything that IS verifiable without hardware so the+// human's on-device pass is the only step left — and so any regression in the+// shared-room math, the POST contract, or the device-capability gate is caught in+// CI before it ever reaches a phone. Run it before every on-device QA session.+//+// It imports the REAL production modules (room-anchor.js, floor-anchor.js,+// placement-capability.js) — no mocks of our own code. The capability matrix is+// exercised by stubbing only the browser ENVIRONMENT (navigator), which is how a+// capability detector is meant to be tested.+//+// Assertions print ✓/✗; a clean run prints "ROOM QA: PASS" and exits 0.++import {+ geoToLocal, localToGeo, bearingDistanceToLocal, localToBearingDistance,+ roomOriginWorld, agentWorldPosition, placeAround, calibrateRoomOrigin,+ pinAbsoluteFromOrigin, compassToYaw,+} from '../src/irl/room-anchor.js';+import { yawDegFromQuat, anchorPoseToPin } from '../src/irl/floor-anchor.js';++let failures = 0;+function check(name, cond) {+ if (cond) console.log(` ✓ ${name}`);+ else { console.error(` ✗ ${name}`); failures++; }+}+const near = (a, b, eps = 1e-6) => Math.abs(a - b) <= eps;++// ── 1) The canonical scenario, end to end through the REAL render math ────────+// Mirrors window.__irlSeedRoom + window.__irlRoomCheck (src/irl.js): viewer on the+// origin facing north, couch-agent 3 m RIGHT (+E), three agents BEHIND (−N), the+// left wall and the dead-ahead "cup" direction empty. This is the geometry that+// makes the user's 360° turn-to-see test land on the right bearings.+console.log('1) Canonical room scenario — world sides via room-anchor projection');+{+ const origin = { lat: 37.7749, lng: -122.4194 };+ // Viewer stands on the origin → room origin sits at world (0,0).+ const originWorld = roomOriginWorld(origin.lat, origin.lng, origin.lat, origin.lng);+ check('room origin lands at the viewer (world 0,0)', near(originWorld.x, 0) && near(originWorld.z, 0));++ const layout = [+ { tag: 'couch-right', relEast: 3, relNorth: 0 },+ { tag: 'behind-1', relEast: -0.5, relNorth: -2.5 },+ { tag: 'behind-2', relEast: 0.5, relNorth: -3 },+ { tag: 'behind-3', relEast: 1.5, relNorth: -3.5 },+ ];+ const placed = layout.map((l) => {+ const p = agentWorldPosition({ originWorld, relEast: l.relEast, relNorth: l.relNorth });+ const side = p.x > 0.5 ? 'right' : p.x < -0.5 ? 'left' : 'center';+ const depth = p.z > 0.5 ? 'behind' : p.z < -0.5 ? 'ahead' : 'level';+ return { ...l, x: +p.x.toFixed(2), z: +p.z.toFixed(2), side, depth };+ });++ const couch = placed.find((p) => p.tag === 'couch-right');+ check('couch agent renders to the RIGHT (+X)', couch.side === 'right');+ check('couch agent is NOT ahead or behind (level)', couch.depth === 'level');++ const behind = placed.filter((p) => p.tag.startsWith('behind'));+ check('all three behind-agents render BEHIND (+Z world, north = −Z)', behind.every((p) => p.depth === 'behind'));+ check('no behind-agent drifts onto the left wall', behind.every((p) => p.side !== 'left'));++ // Distinctness — the multi-place step requires three SEPARATE agents, none stacked.+ const xs = behind.map((p) => p.x), zs = behind.map((p) => p.z);+ const distinct = behind.every((a, i) => behind.every((b, j) => i === j || Math.hypot(a.x - b.x, a.z - b.z) > 0.3));+ check('three behind-agents are distinct (none stacked)', distinct);++ // The left wall (−X) and the dead-ahead cup direction (−Z) must stay empty.+ check('nothing renders on the left wall (−X)', !placed.some((p) => p.side === 'left'));+ check('nothing renders dead-ahead where the cup is (−Z)', !placed.some((p) => p.depth === 'ahead'));+ void xs; void zs;+}++// ── 2) placeAround → projection round-trip (authoring → render parity) ────────+// The placer need not stand on the origin. Drop an agent at a bearing+distance,+// then project it back from the shared origin: it must reappear at that bearing.+console.log('2) placeAround → render round-trip (the "place around me" path)');+{+ const origin = { lat: 37.7749, lng: -122.4194 };+ // Placer stands 1 m north of the origin, drops an agent 3 m due EAST (bearing 90).+ const viewer = localToGeo(origin.lat, origin.lng, 0, 1);+ const a = placeAround({+ originLat: origin.lat, originLng: origin.lng,+ viewerLat: viewer.lat, viewerLng: viewer.lng,+ bearingDeg: 90, distM: 3, faceViewer: true,+ });+ check('stored offset is exact east (relEast ≈ 3)', near(a.relEast, 3, 1e-3));+ check('stored offset folds in the placer position (relNorth ≈ 1)', near(a.relNorth, 1, 1e-3));+ check('agent faces back at the placer (relYawDeg = 270)', near(a.relYawDeg, 270, 1e-9));++ // A DIFFERENT viewer, standing on the origin, projects the stored pin:+ const ow = roomOriginWorld(origin.lat, origin.lng, origin.lat, origin.lng);+ const w = agentWorldPosition({ originWorld: ow, relEast: a.relEast, relNorth: a.relNorth });+ const { bearingDeg, distM } = localToBearingDistance(w.x, -w.z); // world→local: north = −Z+ check('second viewer sees it on the same bearing (~67° from origin, NE)', Math.abs(bearingDeg - 71.57) < 1.5);+ check('second viewer sees it at the right distance (~3.16 m)', near(distM, Math.hypot(3, 1), 1e-2));+ void bearingDistanceToLocal; void compassToYaw;+}++// ── 3) One-gesture calibrate moves the WHOLE cluster, never shears it (R2) ────+console.log('3) Room calibrate — cluster translates/rotates rigidly');+{+ const origin = { lat: 37.7749, lng: -122.4194, yaw: 0 };+ const agents = [{ relEast: 3, relNorth: 0 }, { relEast: -2, relNorth: 1 }];+ const before = agents.map((g) => pinAbsoluteFromOrigin({ originLat: origin.lat, originLng: origin.lng, ...g }));+ const beforeGap = geoToLocal(before[0].lat, before[0].lng, before[1].lat, before[1].lng);++ const moved = calibrateRoomOrigin({ originLat: origin.lat, originLng: origin.lng, dEastM: 5, dNorthM: -2 });+ const after = agents.map((g) => pinAbsoluteFromOrigin({ originLat: moved.originLat, originLng: moved.originLng, ...g }));+ const afterGap = geoToLocal(after[0].lat, after[0].lng, after[1].lat, after[1].lng);++ check('inter-agent geometry is preserved exactly after a translate',+ near(beforeGap.east, afterGap.east, 1e-6) && near(beforeGap.north, afterGap.north, 1e-6));+ const shift = geoToLocal(before[0].lat, before[0].lng, after[0].lat, after[0].lng);+ check('the whole cluster shifted by the calibrate offset (+5 E, −2 N)',+ near(shift.east, 5, 1e-3) && near(shift.north, -2, 1e-3));+}++// ── 4) WebXR floor-anchor pose → shareable GPS pin (R3 write path) ───────────+console.log('4) Floor-anchor pose → pin (WebXR write path math)');+{+ check('flat surface quaternion → 0° yaw', near(yawDegFromQuat(0, 0, 0, 1), 0, 1e-9));+ // 90° about Y: quat = (0, sin45, 0, cos45)+ const s = Math.SQRT1_2;+ check('90° yaw quaternion decodes to ~90°', Math.abs(yawDegFromQuat(0, s, 0, s) - 90) < 1e-6);+ // A hit-test 2 m ahead (local −Z) + 1 m right (+X), 0.4 m below eye level.+ const pin = anchorPoseToPin({ originLat: 37.7749, originLng: -122.4194, x: 1, y: -0.4, z: -2, quat: [0, 0, 0, 1] });+ const off = geoToLocal(37.7749, -122.4194, pin.lat, pin.lng);+ check('local +X persists as east (+1 m)', near(off.east, 1, 1e-3));+ check('local −Z persists as north (+2 m)', near(off.north, 2, 1e-3));+ check('height offset carried through', near(pin.heightM, -0.4, 1e-9));+ check('source tagged webxr', pin.source === 'webxr');+}++// ── 5) POST /api/irl/pins `room` contract — accept valid, degrade invalid ─────+// Re-encodes the validation in api/irl/pins.js (ROOM_ID_RE, REL_MAX_M, finite,+// null-island reject). The server side is also covered by+// tests/api/irl-pins-room.test.js; this guards the client against sending a block+// the server would silently drop to a standalone pin.+console.log('5) POST `room` block contract — validate/clamp/degrade');+{+ const ROOM_ID_RE = /^[a-z0-9-]{1,64}$/;+ const REL_MAX_M = 500;+ const roomOk = (room) =>+ ROOM_ID_RE.test(String(room.id || '')) &&+ Number.isFinite(room.originLat) && room.originLat >= -90 && room.originLat <= 90 &&+ Number.isFinite(room.originLng) && room.originLng >= -180 && room.originLng <= 180 &&+ !(room.originLat === 0 && room.originLng === 0) &&+ Number.isFinite(room.relEast) && Number.isFinite(room.relNorth);+ const clampRel = (v) => Math.max(-REL_MAX_M, Math.min(REL_MAX_M, v));++ const valid = { id: 'living-room-7', originLat: 37.7749, originLng: -122.4194, originYawDeg: 0, relEast: 3, relNorth: 0 };+ check('a well-formed room block validates', roomOk(valid) === true);+ check('uppercase / illegal room id is rejected', roomOk({ ...valid, id: 'Living_Room' }) === false);+ check('a 65-char id is rejected', roomOk({ ...valid, id: 'a'.repeat(65) }) === false);+ check('null-island origin (0,0) is rejected', roomOk({ ...valid, originLat: 0, originLng: 0 }) === false);+ check('out-of-range latitude is rejected', roomOk({ ...valid, originLat: 91 }) === false);+ check('non-finite relEast is rejected', roomOk({ ...valid, relEast: NaN }) === false);+ check('relEast beyond ±500 m clamps, not rejects', clampRel(99999) === 500 && clampRel(-99999) === -500);+ // The matching exact-offset the client computes for `valid` must round-trip.+ const w = agentWorldPosition({ originWorld: { x: 0, z: 0 }, relEast: clampRel(valid.relEast), relNorth: clampRel(valid.relNorth) });+ check('the validated offset projects to the right side (+X)', w.x > 0.5 && Math.abs(w.z) < 0.5);+}++// ── 6) Device-capability matrix — iOS must NOT show a dead WebXR button ───────+// Exercises the REAL resolvePlacementCapability against synthetic navigators. This+// is the matrix row "WebXR floor reticle absent on iOS, present on Android" made+// into a fast regression check (the felt on-device behaviour still needs a phone).+console.log('6) Placement-capability matrix (the WebXR-on-iOS gate)');+{+ const savedNav = globalThis.navigator;+ const savedDoc = globalThis.document;+ // quick-look.js only reads navigator.userAgent/platform/maxTouchPoints; the+ // resolver awaits navigator.xr?.isSessionSupported. Stub just those.+ const withNav = async (nav) => {+ Object.defineProperty(globalThis, 'navigator', { value: nav, configurable: true });+ const { resolvePlacementCapability } = await import('../src/ar/placement-capability.js?_=' + encodeURIComponent(nav.userAgent));+ return resolvePlacementCapability();+ };+ try {+ const android = await withNav({+ userAgent: 'Mozilla/5.0 (Linux; Android 14; Pixel 8) Chrome/126',+ platform: 'Linux armv8l', maxTouchPoints: 5,+ xr: { isSessionSupported: async (m) => m === 'immersive-ar' },+ });+ check('Android Chrome (WebXR) → "webxr" (live floor reticle)', android === 'webxr');++ const ios = await withNav({+ userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) Safari',+ platform: 'iPhone', maxTouchPoints: 5,+ // no navigator.xr → not webxr+ });+ check('iOS Safari (no WebXR) → "quicklook" — NOT a dead WebXR button', ios === 'quicklook');++ const desktop = await withNav({+ userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/126',+ platform: 'MacIntel', maxTouchPoints: 0,+ });+ check('Desktop Chrome (no AR surface) → "pin" (compass+GPS, no console noise)', desktop === 'pin');+ } finally {+ if (savedNav === undefined) delete globalThis.navigator;+ else Object.defineProperty(globalThis, 'navigator', { value: savedNav, configurable: true });+ if (savedDoc !== undefined) globalThis.document = savedDoc;+ }+}++// ── 7) Deployed API probe (optional, --url) — the GET/POST contract is LIVE ───+// Read-first: confirms GET /api/irl/pins carries the room columns in its shape.+// Does NOT place a pin (a write needs a device token + would litter prod). The+// real POST round-trip is the on-device step; this just proves the endpoint is up+// and the room fields survived the deploy (R4 §6 pre-condition).+const urlArg = process.argv.indexOf('--url');+if (urlArg !== -1 && process.argv[urlArg + 1]) {+ const base = process.argv[urlArg + 1].replace(/\/$/, '');+ console.log(`7) Deployed probe — ${base}/api/irl/pins`);+ const ROOM_KEYS = ['room_id', 'rel_east_m', 'rel_north_m', 'origin_lat', 'origin_lng', 'origin_yaw_deg'];+ try {+ // San Francisco sample coord; an empty result is fine — we assert the SHAPE.+ const res = await fetch(`${base}/api/irl/pins?lat=37.7749&lng=-122.4194&deviceToken=room-qa-probe`, {+ headers: { accept: 'application/json' },+ });+ check('GET returns a 2xx', res.ok);+ const data = await res.json().catch(() => null);+ check('response is JSON with a pins array', Array.isArray(data?.pins));+ if (Array.isArray(data?.pins) && data.pins.length) {+ const p = data.pins[0];+ check('a returned pin carries the room columns', ROOM_KEYS.every((k) => k in p));+ check('viewer rows expose is_mine boolean, never user_id/device_token',+ typeof p.is_mine === 'boolean' && !('user_id' in p) && !('device_token' in p));+ } else {+ console.log(' · no pins near the probe coord — shape check skipped (place one on-device to fully verify)');+ }+ } catch (err) {+ check(`GET /api/irl/pins reachable (${err?.message || err})`, false);+ }+} else {+ console.log('7) Deployed probe — skipped (pass --url https://three.ws to run it)');+}++console.log('');+if (failures) {+ console.error(`ROOM QA: FAIL — ${failures} assertion(s) failed`);+ process.exit(1);+}+console.log('ROOM QA: PASS — offline invariants hold. On-device protocol (360° turn-to-see,');+console.log('cross-user, permission gates) still required on real iOS Safari + Android Chrome.');diff --git a/src/dashboard-next/pages/irl-placements.js b/src/dashboard-next/pages/irl-placements.jsindex 022240587..b759e3a88 100644--- a/src/dashboard-next/pages/irl-placements.js+++ b/src/dashboard-next/pages/irl-placements.js@@ -28,6 +28,7 @@ import { skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles } frimport { loadInto } from '../../shared/async-state.js';import { loadLeaflet } from '../../shared/leaflet-loader.js';import { mountReputationPanel } from './irl-reputation.js';+import { openMyDataPanel } from '../../irl/privacy-center.js';// ── Services / x402 skill pricing ───────────────────────────────────────────// Canonical prices live in agent_skill_prices and feed the x402 manifest +@@ -547,6 +548,9 @@ async function mount(el) {<span aria-hidden="true">📥</span> Inbox<span class="irl-inbox-badge" id="irl-inbox-badge" hidden></span></button>+ <button class="irl-btn" id="irl-privacy-btn" type="button" aria-haspopup="dialog">+ <span aria-hidden="true">🔒</span> Privacy & my data+ </button><a class="irl-btn primary" href="/irl" id="irl-place-btn">+ Place new ↗</a></div></div>@@ -555,6 +559,12 @@ async function mount(el) {<div id="irl-list"></div></div>`;el.querySelector('#irl-inbox-btn')?.addEventListener('click', openInboxModal);+ // Privacy & my data — the full H5 right-to-be-forgotten surface (summary,+ // per-pin unpublish/delete, export, remove-all). A delete here must also drop+ // out of the placements list, so refresh it on change.+ el.querySelector('#irl-privacy-btn')?.addEventListener('click', () => {+ openMyDataPanel({ onChanged: () => { runLoad().catch(() => {}); } });+ });// Multiplayer AR explainer — shown once at the top so owners understand// that their placed agents are visible to ALL users who visit that location.@@ -570,6 +580,9 @@ async function mount(el) {// One network boundary for the four designed states: loading skeleton → list /// empty / error+retry. The retry button re-runs this same load. Signed-out is// handled earlier by requireUser()'s redirect to /login, so it never reaches here.+ await runLoad();++ async function runLoad() {await loadInto(list, {load: async () => {// Pins + interactions in parallel — interactions power both the banner anddiff --git a/src/dashboard-next/pages/monetize.js b/src/dashboard-next/pages/monetize.jsindex ebf1c0cd0..53b159b55 100644--- a/src/dashboard-next/pages/monetize.js+++ b/src/dashboard-next/pages/monetize.js@@ -265,7 +265,7 @@ function renderHero({ available, revenue, creatorPlans, subscribedTo, pendingRoywrap.appendChild(heroCard({title: 'Subscription income',- value: subIncomeUsd > 0 ? `$${subIncomeUsd.toFixed(2)}` : '$0.00',+ value: formatUsd(subIncomeUsd),sub: activeSubs > 0? `${activeSubs} active subscriber${activeSubs === 1 ? '' : 's'} · paid directly to your wallet (last 30 days)`: 'Recurring plan revenue, paid directly to your wallet.',@@ -851,6 +851,15 @@ function formatNetUsdc(amount) {return `$${n.toFixed(decimals)}`;}+// Format a USD-denominated amount (already in dollars, not atomics) with thousands+// separators — e.g. 1234.5 → "$1,234.56". Matches formatUsdc's output so subscription+// income and plan prices read consistently with the rest of the dashboard.+function formatUsd(amount) {+ const n = Number(amount);+ if (!Number.isFinite(n)) return '$0.00';+ return n.toLocaleString('en-US', { style: 'currency', currency: 'USD' });+}+function humanizeSkill(skill) {if (!skill) return 'Other';const map = {@@ -1596,7 +1605,7 @@ async function loadCosmeticEarnings(body, wallet) {}const t = data?.totals || {};- const usd = (n) => '$' + (Number(n) || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });+ const usd = formatUsd;if (!t.sales) {body.innerHTML = `@@ -1800,7 +1809,7 @@ function renderSubscriptionPlans({ creatorPlans, me }) {${p.description ? `<div style="font-size:12px;color:var(--nxt-ink-dim)">${esc(p.description.slice(0, 80))}</div>` : ''}</td><td style="text-align:right;font-variant-numeric:tabular-nums">- $${esc(Number(p.price_usd || 0).toFixed(2))}+ ${esc(formatUsd(p.price_usd))}</td><td style="color:var(--nxt-ink-dim)">${esc(p.interval || 'monthly')}</td><td>