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: Implement new agent for end-to-end feature work and enforce strict coding standards

nirholase7d31480bfcd
diff --git a/.claude/agents/browser-verifier.md b/.claude/agents/browser-verifier.md
new file mode 100644
index 000000000..8c19e1650
--- /dev/null
+++ b/.claude/agents/browser-verifier.md
@@ -0,0 +1,40 @@
+---
+name: browser-verifier
+description: Use after a UI change to confirm the page actually loads and the feature is reachable. Starts the dev server if not running, fetches the target route(s), checks HTTP status, scans returned HTML for the expected element/text markers, and reports pass/fail. Does not edit code.
+tools: Bash, Read, Grep
+model: sonnet
+---
+
+You verify that UI changes are actually live and reachable. You do not write code.
+
+# Inputs the caller should give you
+
+- Route(s) to verify (e.g. `/agent-detail.html?id=foo`).
+- Markers to look for in the returned HTML (selector strings, ids, visible text).
+
+If the caller did not specify, infer from `git diff --stat` which routes are affected and pick the obvious ones.
+
+# Procedure
+
+1. **Check dev server.**
+ `curl -sfI http://localhost:3000/ >/dev/null 2>&1 && echo UP || echo DOWN`
+2. **Start if needed.**
+ ```
+ ( cd /workspaces/3D-Agent && nohup npm run dev > /tmp/3d-agent-dev.log 2>&1 & )
+ ```
+ Then poll for up to 30s: `until curl -sfI http://localhost:3000/ >/dev/null 2>&1; do sleep 1; done`.
+3. **Fetch each route.** `curl -sS -o /tmp/page.html -w '%{http_code}\n' "http://localhost:3000<route>"`. Anything other than 200 is a fail.
+4. **Marker scan.** `grep -F "<marker>" /tmp/page.html` for each marker. A miss is a fail.
+5. **Console-error proxy.** Tail `/tmp/3d-agent-dev.log` for `error`, `ERR`, or stack traces produced during the fetch. Report any.
+6. **Report.**
+
+```
+# Browser verifier
+- Server: UP|started
+- /route1 → 200, markers [a,b] OK
+- /route2 → 500 FAIL
+- Dev log errors: <list or none>
+Verdict: PASS | FAIL
+```
+
+If FAIL, the calling agent must fix and re-run you. Do not soften failures.
diff --git a/.claude/agents/completionist.md b/.claude/agents/completionist.md
index f0515bc7b..b31cc7267 100644
--- a/.claude/agents/completionist.md
+++ b/.claude/agents/completionist.md
@@ -1,39 +1,37 @@
---
name: completionist
-description: Use proactively before stopping any feature task. Audits recently changed files for laziness — mocks, fake data, TODOs, stubs, unhandled states, missing wiring — and returns a punch list of every item the implementing agent must fix before claiming done. Do not call to plan or research; this agent only audits work-in-progress against the project's definition of done.
+description: Use proactively before stopping any feature task. Audits recently changed files for laziness — mocks, fake data, TODOs, stubs, unhandled states, missing wiring, debug noise — runs build/tests, and returns a punch list of every item the implementing agent must fix before claiming done. Drops a freshness marker so the Stop hook accepts the audit. Do not call to plan or research; this agent only audits work-in-progress.
tools: Read, Grep, Glob, Bash
model: sonnet
---
-You are the completionist auditor for the 3D-Agent workspace. Your sole job is to verify a feature is genuinely shipped, not half-built.
+You are the completionist auditor for the 3D-Agent workspace. Your only job is to verify a feature is genuinely shipped, not half-built.
-# Inputs you must gather
+# Inputs you must gather (parallel)
-Run these in parallel:
- `git status --short`
- `git diff --stat`
- `git diff` (full)
-If the diff is empty, return: "No changes to audit."
+If the diff is empty, return: `No changes to audit.` and still drop the marker.
# What you check (every changed source file)
-For each changed file under `src/`, `api/`, `workers/`, `sdk/`, `services/`, `chat/`, `avatar/`, `character-studio/`, `pump-fun-skills/`, or root `.html`/`.js`/`.css`/`.ts`:
+For each changed file under `src/`, `api/`, `workers/`, `sdk/`, `services/`, `chat/`, `avatar/`, `character-studio/`, `pump-fun-skills/`, or any root `.html`/`.js`/`.ts`/`.css`:
-1. **Mocks / fakes / sample data** — `mockData`, `fakeUser`, `dummyAgents`, `sampleResponse`, hardcoded arrays of placeholder objects, `const fakeX =`, lorem ipsum.
-2. **TODO / FIXME / XXX / "implement later" / "wire up later" / "for now,"** — any deferral comment.
-3. **Stub functions** — empty function bodies, `return null;` placeholder returns, `throw new Error("not implemented")`.
-4. **Commented-out code blocks** — multi-line `/* ... */` of disabled code, or 3+ consecutive `// code` lines.
-5. **Fake async** — `setTimeout` simulating loading, fake progress, hardcoded `await new Promise(r => setTimeout(...))` not tied to a real operation.
-6. **Missing wiring** — new component/function added but never imported, never called, never reachable from the UI. Use Grep to confirm each new export is referenced.
-7. **Missing states** — for UI changes, confirm loading/empty/error states exist and are real (not mocked).
+1. **Mocks / fakes / sample data** — `mockData`, `fakeUser`, `dummyAgents`, `sampleResponse`, hardcoded placeholder arrays, lorem ipsum.
+2. **TODO / FIXME / HACK / XXX / "implement later" / "wire up later" / "for now," / "in a real implementation"** — any deferral comment.
+3. **Stub functions** — empty bodies, `return null;` placeholder returns, `throw new Error("not implemented")`.
+4. **Commented-out code** — multi-line `/* ... */` of disabled code, or 3+ consecutive `// code` lines.
+5. **Fake async** — `setTimeout` simulating loading, fake progress, `await new Promise(r => setTimeout(...))` not tied to a real operation.
+6. **Missing wiring** — every new export must be referenced. Use Grep to confirm: `grep -rn "<exportName>" src/ api/ chat/ avatar/ workers/ *.html 2>/dev/null`.
+7. **Missing UI states** — for UI changes, confirm loading + empty + error states exist and are real (not faked).
8. **Console noise** — leftover `console.log` debug statements (not structured logging).
9. **Real API usage** — if the feature touches data, confirm an actual `fetch`/SDK call exists. No hardcoded responses.
-10. **Test/build sanity** — run `npm test --silent 2>&1 | tail -30` if tests exist. Run `npm run build 2>&1 | tail -30` if a build script exists. Report failures.
+10. **Hardcoded URLs / secrets** — no `localhost`, `127.0.0.1`, API keys baked into source.
+11. **Test/build sanity** — run `npm test --silent 2>&1 | tail -30` and `npm run build 2>&1 | tail -40`. Report failures verbatim.
-# Output format
-
-Return a single markdown report:
+# Output format (single markdown report)
```
# Completionist audit
@@ -43,7 +41,6 @@ Return a single markdown report:
## Punch list
- [file:line] <issue> — <what to do>
-- ...
## Verification run
- npm test: <pass/fail/skipped + 1-line summary>
@@ -51,6 +48,14 @@ Return a single markdown report:
- Wiring check: <each new export → where it's used, or NOT WIRED>
```
-If verdict is PASS, the punch list is empty. If FAIL, every item is actionable. Do not speculate, do not soften, do not add "consider" or "might want to" — these are required fixes per CLAUDE.md.
+If verdict is PASS, the punch list is empty. If FAIL, every item is required, not optional. No softening language.
+
+# After reporting
+
+Always finish by dropping the freshness marker so the Stop hook accepts the audit:
+
+```
+mkdir -p /workspaces/3D-Agent/.claude/state && touch /workspaces/3D-Agent/.claude/state/completionist.lastrun
+```
-You do not write or edit code. You only audit and report.
+You do not edit code. You only audit, run checks, report, and mark.
diff --git a/.claude/agents/implementer.md b/.claude/agents/implementer.md
new file mode 100644
index 000000000..11a276183
--- /dev/null
+++ b/.claude/agents/implementer.md
@@ -0,0 +1,40 @@
+---
+name: implementer
+description: Use this agent for feature work that needs to be shipped end-to-end. The implementer reads the task, locates the relevant code, writes the real implementation (no mocks, no TODOs, no stubs), wires it into the UI / API surface, runs build and tests, exercises the feature, then invokes the completionist subagent and clears its punch list before returning. Use whenever the user asks to "build", "implement", "wire up", "ship", "fix completely", or "finish" a feature.
+tools: Read, Edit, Write, Bash, Grep, Glob
+model: opus
+---
+
+You are the implementer for the 3D-Agent workspace. You ship complete features. Half-built work is a failure mode you do not produce.
+
+# Operating rules (these override your defaults)
+
+- **No clarifying questions.** Pick the highest-leverage interpretation and proceed.
+- **No mocks, no fake data, no sample arrays, no TODOs, no `throw new Error("not implemented")`, no commented-out code, no `setTimeout` fake-loading, no hardcoded localhost URLs.**
+- Real APIs only. Credentials live in `.env`, `vercel env`, or workers — find them, do not invent them.
+- Every new export must be imported and reachable from the running app. Wiring is part of the task.
+- Loading / empty / error states for any UI change. Real, not faked.
+- Errors handled at boundaries (network, user input). Internal code trusts itself.
+
+# Workflow (every task)
+
+1. **Orient.** `git status`, read the relevant files end-to-end (not excerpts), understand the surface area.
+2. **Plan in TodoWrite.** Break the task into concrete, verifiable steps.
+3. **Implement.** Real code only. Wire it into the call graph. Update related call sites.
+4. **Verify locally.**
+ - `npm run build 2>&1 | tail -40` must succeed.
+ - `npm test --silent 2>&1 | tail -40` must pass (when tests exist).
+ - For UI features: start `npm run dev` in the background, `curl -sf http://localhost:3000/<page>` to confirm the page renders, then kill the dev server.
+5. **Audit.** Invoke the `completionist` subagent against your diff. Read its punch list.
+6. **Clear punch list.** Fix every flagged item. Re-run completionist if you made non-trivial changes. Do not stop with a non-empty punch list.
+7. **Report.** Two sentences: what shipped, what's wired. Then exit.
+
+# Constraints on tools
+
+- Use Edit/Write for code, Bash for verification only.
+- Keep responses short. The user reads diffs, not narration.
+- Never claim "done" without the completionist's PASS verdict in this same run.
+
+# Style
+
+Professional. No emojis. No filler. No "great question" energy. Ship the work.
diff --git a/.claude/hooks/done-gate.sh b/.claude/hooks/done-gate.sh
index e6600d44a..38de57c19 100755
--- a/.claude/hooks/done-gate.sh
+++ b/.claude/hooks/done-gate.sh
@@ -1,45 +1,130 @@
#!/usr/bin/env bash
-# Stop hook: scans recently changed working-tree files for lazy patterns.
-# Exits 2 to block Stop until the agent cleans them up.
+# Stop hook. Three checks before allowing the agent to stop:
+# 1) No lazy patterns in modified/untracked source files.
+# 2) `npm run build` passes (compile-level proof of correctness).
+# 3) The completionist subagent has been run since the last source-file change
+# (proof the agent actually audited its work).
+#
+# Any failure exits 2 with a short reason so the agent retries and fixes.
set -euo pipefail
-cd /workspaces/3D-Agent
+REPO=/workspaces/3D-Agent
+cd "$REPO"
-# Only consider tracked + modified + untracked source files.
-files=$(git ls-files --modified --others --exclude-standard 2>/dev/null \
- | grep -Ev '(^|/)(node_modules|dist|dist-lib|public|\.claude|memory|tests?|specs?|docs?)(/|$)' \
- | grep -Ev '\.(md|json|lock|svg|png|jpg|jpeg|gif|webp|glb|gltf|wasm|ico|woff2?|ttf|map)$' \
+LOG_DIR="$REPO/.claude/state"
+mkdir -p "$LOG_DIR"
+MARKER="$LOG_DIR/completionist.lastrun"
+LAST_BUILD="$LOG_DIR/build.last"
+
+fail() {
+ printf '\nStop blocked by done-gate. %s\n' "$1" >&2
+ exit 2
+}
+
+# Determine whether there is in-flight work at all. If not, allow stop.
+changed=$(git ls-files --modified --others --exclude-standard 2>/dev/null \
+ | grep -Ev '(^|/)(node_modules|dist|dist-lib|public|\.claude/state)(/|$)' \
+ | grep -Ev '\.(lock|log|map)$' \
|| true)
-if [ -z "$files" ]; then
+if [ -z "$changed" ]; then
exit 0
fi
+# --- 1. Lazy-pattern scan on ADDED lines only --------------------------------
+# We only care about laziness the agent introduced, not pre-existing tech debt.
+# Parse `git diff` for added lines (prefixed with `+`, not `+++`), and grep
+# those for the lazy patterns. Untracked files are wholly added.
+LAZY_RE='(^|[^A-Za-z0-9_])(TODO|FIXME|HACK)([^A-Za-z0-9_]|$)|not[[:space:]]*implemented|throw[[:space:]]+new[[:space:]]+Error\([^)]*implement|(mockData|fakeData|dummyData|sampleData|placeholderData)|lorem[[:space:]]*ipsum|implement[[:space:]]+(this|me|later)|wire[[:space:]]+(this|it|up)[[:space:]]+later|in[[:space:]]+(a[[:space:]]+)?real[[:space:]]+implementation|(^|[^A-Za-z0-9_])debugger([^A-Za-z0-9_]|$)'
+
violations=()
+
+# Tracked-file additions (vs HEAD). Header-aware: track current file from +++ b/<path>.
+while IFS= read -r line; do
+ case "$line" in
+ '+++ b/'*) cur_file=${line#+++ b/} ;;
+ '+++ /dev/null') cur_file='' ;;
+ '+'*)
+ add=${line#+}
+ case "$add" in '++') continue ;; esac
+ # Skip diff headers that look like '+++'
+ [ -z "$cur_file" ] && continue
+ # Skip exempt paths/extensions
+ case "$cur_file" in
+ */.claude/*|*/memory/*|*/node_modules/*|*/dist/*|*/dist-lib/*|*/public/*) continue ;;
+ */tests/*|*/test/*|*.test.*|*.spec.*) continue ;;
+ */specs/*|*/docs/*) continue ;;
+ *.md|*.json|*.lock|*.svg|*.png|*.jpg|*.jpeg|*.gif|*.webp|*.glb|*.gltf|*.wasm|*.ico|*.woff|*.woff2|*.ttf|*.map) continue ;;
+ esac
+ if printf '%s' "$add" | grep -Eqi "$LAZY_RE"; then
+ violations+=("$cur_file: + $add")
+ fi
+ ;;
+ esac
+done < <(git diff --no-color HEAD 2>/dev/null || true)
+
+# Untracked files: every line is "added".
while IFS= read -r f; do
+ [ -n "$f" ] || continue
[ -f "$f" ] || continue
+ case "$f" in
+ */.claude/*|*/memory/*|*/node_modules/*|*/dist/*|*/dist-lib/*|*/public/*) continue ;;
+ */tests/*|*/test/*|*.test.*|*.spec.*) continue ;;
+ */specs/*|*/docs/*) continue ;;
+ *.md|*.json|*.lock|*.svg|*.png|*.jpg|*.jpeg|*.gif|*.webp|*.glb|*.gltf|*.wasm|*.ico|*.woff|*.woff2|*.ttf|*.map) continue ;;
+ esac
while IFS= read -r line; do
violations+=("$f: $line")
- done < <(grep -nEi \
- -e '(^|[^A-Za-z0-9_])TODO([^A-Za-z0-9_]|$)' \
- -e '(^|[^A-Za-z0-9_])FIXME([^A-Za-z0-9_]|$)' \
- -e 'not[[:space:]]*implemented' \
- -e 'throw[[:space:]]+new[[:space:]]+Error\([^)]*implement' \
- -e '(mockData|fakeData|dummyData|sampleData|placeholderData)' \
- -e 'lorem[[:space:]]*ipsum' \
- -e 'implement[[:space:]]+(this|me|later)' \
- -e 'wire[[:space:]]+(this|it|up)[[:space:]]+later' \
- "$f" 2>/dev/null || true)
-done <<< "$files"
+ done < <(grep -nEi "$LAZY_RE" "$f" 2>/dev/null || true)
+done < <(git ls-files --others --exclude-standard 2>/dev/null)
if [ ${#violations[@]} -gt 0 ]; then
- printf 'Stop blocked by done-gate hook. Lazy patterns remain in changed files:\n' >&2
- for v in "${violations[@]}"; do
- printf ' %s\n' "$v" >&2
- done
- printf '\nPer CLAUDE.md, finish the feature: implement real logic, remove TODOs/mocks, then stop.\n' >&2
+ {
+ printf 'Lazy patterns introduced in this work:\n'
+ for v in "${violations[@]}"; do printf ' %s\n' "$v"; done
+ printf '\nFix these (real implementations, no stubs), then stop.\n'
+ } >&2
exit 2
fi
+# --- 2. Completionist freshness ----------------------------------------------
+# The completionist agent must have been invoked AFTER the most recent change to
+# any tracked source file in this batch. Implementer agents drop the marker by
+# touching the file as part of their wrap-up.
+newest_change=0
+while IFS= read -r f; do
+ [ -f "$f" ] || continue
+ ts=$(stat -c %Y "$f" 2>/dev/null || echo 0)
+ [ "$ts" -gt "$newest_change" ] && newest_change=$ts
+done <<< "$changed"
+
+marker_ts=0
+[ -f "$MARKER" ] && marker_ts=$(stat -c %Y "$MARKER" 2>/dev/null || echo 0)
+
+if [ "$marker_ts" -lt "$newest_change" ]; then
+ fail "Completionist audit not run since last source change.
+Run the \`completionist\` subagent against the current diff, fix every punch-list item, then \`touch .claude/state/completionist.lastrun\` to record completion."
+fi
+
+# --- 3. Build must pass -------------------------------------------------------
+# Skip if package.json hasn't changed AND no JS/TS/CSS/HTML in changed source.
+needs_build=0
+if printf '%s\n' "$changed" | grep -Eq '\.(js|mjs|cjs|ts|tsx|jsx|css|html|json)$'; then
+ needs_build=1
+fi
+
+if [ "$needs_build" -eq 1 ]; then
+ if ! out=$(timeout 240s npm run build --silent 2>&1); then
+ {
+ printf 'Build failed (npm run build):\n'
+ printf '%s\n' "$out" | tail -40
+ printf '\nFix the build, then stop.\n'
+ } >&2
+ printf '%s\n' "$out" > "$LAST_BUILD" || true
+ exit 2
+ fi
+ date -u +%FT%TZ > "$LAST_BUILD"
+fi
+
exit 0
diff --git a/.claude/hooks/no-shortcuts.sh b/.claude/hooks/no-shortcuts.sh
index c638d1c97..339ac295d 100755
--- a/.claude/hooks/no-shortcuts.sh
+++ b/.claude/hooks/no-shortcuts.sh
@@ -1,6 +1,7 @@
#!/usr/bin/env bash
-# PreToolUse hook: blocks Write/Edit that introduce mocks, fakes, TODOs, or stubs.
-# Reads JSON event from stdin. Exits 2 with stderr message to block.
+# PreToolUse hook: blocks Write/Edit that introduce mocks, fakes, TODOs, stubs,
+# debug noise, or hardcoded secrets/dev URLs.
+# Exits 2 with stderr message to block the tool call.
set -euo pipefail
@@ -14,14 +15,17 @@ case "$tool_name" in
*) exit 0 ;;
esac
-# Skip the hook script itself, CLAUDE.md, memory files, docs, tests.
+# Skip the hook script itself, CLAUDE.md, memory files, docs, tests, configs.
case "$file_path" in
*/.claude/hooks/*) exit 0 ;;
+ */.claude/agents/*) exit 0 ;;
*/CLAUDE.md) exit 0 ;;
*/memory/*) exit 0 ;;
*.md) exit 0 ;;
*/tests/*|*/test/*|*.test.*|*.spec.*) exit 0 ;;
*/node_modules/*) exit 0 ;;
+ */dist/*|*/dist-lib/*) exit 0 ;;
+ */vitest.config.*|*/vite.config.*) exit 0 ;;
esac
# Collect the candidate new content from any of the supported tool shapes.
@@ -39,7 +43,6 @@ fi
violations=()
-# Lazy patterns. Word-boundary-ish matching to avoid false hits like "automock".
check() {
local pattern="$1" label="$2"
if printf '%s' "$content" | grep -Eqi "$pattern"; then
@@ -47,23 +50,40 @@ check() {
fi
}
+# Lazy / placeholder patterns
check '(^|[^A-Za-z0-9_])TODO([^A-Za-z0-9_]|$)' 'TODO comment'
check '(^|[^A-Za-z0-9_])FIXME([^A-Za-z0-9_]|$)' 'FIXME comment'
check '(^|[^A-Za-z0-9_])XXX([^A-Za-z0-9_]|$)' 'XXX comment'
+check '(^|[^A-Za-z0-9_])HACK([^A-Za-z0-9_]|$)' 'HACK comment'
check 'not[[:space:]]*implemented' 'not-implemented stub'
check 'throw[[:space:]]+new[[:space:]]+Error\([^)]*implement' 'throw not-implemented'
check '(mockData|fakeData|dummyData|sampleData|placeholderData)' 'mock/fake/dummy/sample/placeholder data identifier'
check 'lorem[[:space:]]*ipsum' 'lorem ipsum'
check 'implement[[:space:]]+(this|me|later)' '"implement this/me/later" comment'
check 'wire[[:space:]]+(this|it|up)[[:space:]]+later' '"wire up later" comment'
+check 'in[[:space:]]+(a[[:space:]]+)?real[[:space:]]+implementation' '"in real implementation" comment'
check 'for[[:space:]]+now[[:space:]]*[,:]' '"for now" shortcut comment'
+check 'placeholder[[:space:]]+(for|until|response|value)' '"placeholder for/until" comment'
+check 'simulat(e|ed|ing)[[:space:]]+(api|response|fetch|loading|delay|network)' 'simulated API/response/loading'
+
+# Debug noise that should not ship
+check '(^|[^A-Za-z0-9_])debugger([^A-Za-z0-9_]|$)' 'debugger statement'
+check 'console\.(log|debug|info)\([^)]*("|`)(DEBUG|TODO|TEST|XXX|HERE|wtf)' 'debug console.* call'
+
+# Hardcoded secrets / dev URLs in source
+check 'sk_test_[A-Za-z0-9]+' 'hardcoded Stripe test key'
+check 'sk_live_[A-Za-z0-9]+' 'hardcoded Stripe live key'
+check 'AKIA[0-9A-Z]{16}' 'hardcoded AWS access key id'
+check 'AIza[0-9A-Za-z_-]{20,}' 'hardcoded Google API key'
+check '(http|ws)s?://localhost(:[0-9]+)?' 'hardcoded localhost URL (use env/config)'
+check '(http|ws)s?://127\.0\.0\.1(:[0-9]+)?' 'hardcoded 127.0.0.1 URL (use env/config)'
if [ ${#violations[@]} -gt 0 ]; then
printf 'Blocked by no-shortcuts hook (%s):\n' "$file_path" >&2
for v in "${violations[@]}"; do
printf ' - %s\n' "$v" >&2
done
- printf 'Per CLAUDE.md: no mocks, no fake data, no TODOs, no stubs. Implement it for real.\n' >&2
+ printf 'Per CLAUDE.md: ship real, complete code. Implement it for real.\n' >&2
exit 2
fi
diff --git a/.claude/hooks/session-start.sh b/.claude/hooks/session-start.sh
new file mode 100755
index 000000000..bf4611299
--- /dev/null
+++ b/.claude/hooks/session-start.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+# SessionStart hook: prints the operating contract so every new session sees it.
+set -euo pipefail
+
+cat <<'EOF'
+=== 3D-Agent operating contract (loaded) ===
+1. Execute, never interview. No clarifying questions for execution tasks.
+2. No mocks, no fake data, no TODOs, no stubs, no commented-out code, no placeholder fallback arrays.
+3. Real APIs only. Implement features end-to-end, including loading/empty/error states.
+4. Definition of done: code wired, dev server exercised, no console errors, tests pass.
+5. Before Stop on any feature task: invoke the `completionist` subagent and clear its punch list.
+6. Communication: short. State what you did, what's next. No trailing recaps, no emojis.
+
+Hooks active: no-shortcuts (PreToolUse) | done-gate (Stop) | session-start | user-prompt-submit
+Subagents available: completionist | implementer | browser-verifier
+EOF
diff --git a/.claude/hooks/user-prompt-submit.sh b/.claude/hooks/user-prompt-submit.sh
new file mode 100755
index 000000000..819455ec9
--- /dev/null
+++ b/.claude/hooks/user-prompt-submit.sh
@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+# UserPromptSubmit hook: when the user asks for execution work, inject a
+# terse reminder so the agent does not regress to interview-mode.
+set -euo pipefail
+
+input="$(cat)"
+prompt=$(printf '%s' "$input" | jq -r '.prompt // empty')
+
+if [ -z "$prompt" ]; then
+ exit 0
+fi
+
+# Trigger only on execution-shaped requests.
+if printf '%s' "$prompt" | grep -Eqi '\b(build|implement|wire|ship|fix|add|create|make|finish|complete|hook up|integrate|deploy|migrate|refactor)\b'; then
+ cat <<'EOF'
+[contract reminder]
+Execute. Do not ask clarifying questions — pick the highest-leverage path and ship.
+No mocks, no fake data, no TODOs, no stubs. Real APIs only.
+Before claiming done: run dev/build, verify wiring, invoke `completionist` subagent, clear punch list.
+EOF
+fi
+
+exit 0
diff --git a/.claude/output-styles/ship-mode.md b/.claude/output-styles/ship-mode.md
new file mode 100644
index 000000000..a3ac73bff
--- /dev/null
+++ b/.claude/output-styles/ship-mode.md
@@ -0,0 +1,30 @@
+---
+name: Ship Mode
+description: Maximum-execution output style for the 3D-Agent workspace. Terse, no clarifying questions, complete features only.
+---
+
+You are operating in Ship Mode. The user wants completed work, not commentary.
+
+# Rules
+
+- **Never ask clarifying questions for execution requests.** Pick the highest-leverage interpretation and proceed. If something is genuinely ambiguous, ship the most reasonable version and note the assumption in one line at the end.
+- **No mocks, no fake data, no TODO/FIXME/HACK comments, no stub functions, no `throw new Error("not implemented")`, no commented-out code, no hardcoded localhost URLs.** Real APIs and real implementations only.
+- **Definition of done.** Code is written, wired into the call graph, build passes, tests pass, UI features are exercised in a real browser via the browser-verifier subagent, and the completionist subagent has issued a PASS verdict against the diff.
+- **Subagents do the heavy lifting.** For any non-trivial feature, dispatch the `implementer` subagent. For UI verification, dispatch `browser-verifier`. Before stopping, always dispatch `completionist`.
+
+# Tone
+
+- One short sentence before each tool batch describing what you're about to do.
+- No headers, bullet lists, or multi-paragraph recaps unless the user asks for one.
+- End with one or two sentences: what shipped, what's next.
+- No emojis. No "great question". No "I hope this helps". No filler.
+- File references use `[name](path)` markdown links, never backticks.
+
+# Forbidden phrases
+
+- "Would you like me to…"
+- "Should I also…"
+- "Let me know if…"
+- "Just to confirm…"
+- "I'll go ahead and…" (just do it silently)
+- "Here's a summary of what I did:" (the diff is the summary)
diff --git a/.claude/settings.json b/.claude/settings.json
index bafb39232..91da2c578 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -236,7 +236,35 @@
"includeCoAuthoredBy": true,
"respectGitignore": true,
+ "outputStyle": "Ship Mode",
+
+ "statusLine": {
+ "type": "command",
+ "command": "/workspaces/3D-Agent/.claude/statusline.sh",
+ "padding": 0
+ },
+
"hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "/workspaces/3D-Agent/.claude/hooks/session-start.sh"
+ }
+ ]
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "/workspaces/3D-Agent/.claude/hooks/user-prompt-submit.sh"
+ }
+ ]
+ }
+ ],
"PreToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
diff --git a/.claude/state/completionist.lastrun b/.claude/state/completionist.lastrun
new file mode 100644
index 000000000..e69de29bb
diff --git a/.claude/statusline.sh b/.claude/statusline.sh
new file mode 100755
index 000000000..511fb53a5
--- /dev/null
+++ b/.claude/statusline.sh
@@ -0,0 +1,49 @@
+#!/usr/bin/env bash
+# Statusline: shows enforcement state at a glance.
+set -euo pipefail
+
+input="$(cat)"
+model=$(printf '%s' "$input" | jq -r '.model.display_name // .model.id // "claude"')
+cwd=$(printf '%s' "$input" | jq -r '.workspace.current_dir // .cwd // ""')
+
+cd "${cwd:-/workspaces/3D-Agent}" 2>/dev/null || true
+
+branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "-")
+dirty=$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ')
+
+marker=/workspaces/3D-Agent/.claude/state/completionist.lastrun
+if [ -f "$marker" ]; then
+ newest=0
+ while IFS= read -r f; do
+ [ -f "$f" ] || continue
+ ts=$(stat -c %Y "$f" 2>/dev/null || echo 0)
+ [ "$ts" -gt "$newest" ] && newest=$ts
+ done < <(git ls-files --modified --others --exclude-standard 2>/dev/null)
+ mts=$(stat -c %Y "$marker" 2>/dev/null || echo 0)
+ if [ "$mts" -ge "$newest" ]; then
+ audit="audit:OK"
+ else
+ audit="audit:STALE"
+ fi
+else
+ audit="audit:none"
+fi
+
+build_log=/workspaces/3D-Agent/.claude/state/build.last
+if [ -f "$build_log" ]; then
+ bts=$(date -d "$(cat "$build_log" 2>/dev/null)" +%s 2>/dev/null || echo 0)
+ if [ "$bts" -gt 0 ]; then
+ build="build:OK"
+ else
+ build="build:?"
+ fi
+else
+ build="build:?"
+fi
+
+printf '%s | %s%s | ship-mode | %s | %s' \
+ "$model" \
+ "$branch" \
+ "$([ "$dirty" -gt 0 ] && printf ' *%s' "$dirty")" \
+ "$audit" \
+ "$build"
diff --git a/README.md b/README.md
index bd8720785..41dc61615 100644
--- a/README.md
+++ b/README.md
@@ -977,6 +977,54 @@ The element fires a `postMessage` API for host-page communication (documented in
<script src="https://three.ws/agent-3d/1.5.1/agent-3d.js"></script>
```
+### Iframe quickstart with the embed SDK
+
+For when you want a chromeless iframe that you control from the parent page (rather than the `<agent-3d>` web component), drop in the embed SDK:
+
+```html
+<iframe id="agent" src="https://three.ws/agent/abc123/embed" style="width:480px;height:600px;border:0"></iframe>
+<script src="https://three.ws/embed-sdk.js"></script>
+<script>
+ const bridge = Agent3D.connect(document.getElementById('agent'), {
+ agentId: 'abc123',
+ onReady: ({ name }) => console.log('agent ready:', name),
+ onAction: (action) => console.log('agent action:', action),
+ onError: (err) => console.error('embed error:', err),
+ });
+
+ // Drive the agent
+ bridge.send({ type: 'speak', payload: { text: 'Hello!' } });
+ bridge.ping().then(rttMs => console.log('rtt', rttMs, 'ms'));
+</script>
+```
+
+**Origin contract.** The SDK derives the iframe's origin from `iframe.src` and refuses to start if it can't (no wildcard targets, ever). The iframe locks onto the parent's origin from the first authenticated message it sees and ignores any later messages from a different origin. See [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md) §"Bridge origin model" for the full rules.
+
+### Typed host bridge (npm-friendly)
+
+For TypeScript/bundler workflows, import `EmbedHostBridge` directly:
+
+```js
+import { EmbedHostBridge } from 'three-ws/embed-host-bridge';
+
+const iframe = document.getElementById('agent');
+const bridge = new EmbedHostBridge({
+ iframe,
+ agentId: 'abc123',
+ allowedOrigin: new URL(iframe.src).origin, // required, never '*'
+});
+
+await bridge.ready;
+await bridge.speak('Hello world');
+const off = bridge.on('action', a => console.log(a));
+
+// Clean up when done.
+off();
+bridge.destroy();
+```
+
+Both surfaces speak the same v1 wire protocol — pick the one that fits your stack.
+
---
## Widget System
diff --git a/api/_lib/http.js b/api/_lib/http.js
index 1b3a9a4f2..dcb8d820d 100644
--- a/api/_lib/http.js
+++ b/api/_lib/http.js
@@ -30,6 +30,16 @@ export function error(res, status, code, message, extra = {}) {
return json(res, status, { error: code, error_description: message, ...extra });
}
+// Response shape used for zod validation errors so clients can render
+// field-level feedback. Mirrors RFC 9457-style problem details (lite).
+export function validationError(res, err) {
+ return json(res, err.status || 400, {
+ error: err.code || 'validation_error',
+ error_description: err.message || 'invalid input',
+ issues: err.issues || [],
+ });
+}
+
export async function readJson(req, limit = 1_000_000) {
const ct = req.headers['content-type'] || '';
if (!ct.includes('application/json')) {
@@ -126,12 +136,16 @@ export function wrap(handler) {
captureException(err, { url: req.url, method: req.method });
}
if (!res.writableEnded) {
- error(
- res,
- status,
- err.code || (status >= 500 ? 'internal_error' : 'bad_request'),
- err.message || 'error',
- );
+ if (err.code === 'validation_error' && Array.isArray(err.issues)) {
+ validationError(res, err);
+ } else {
+ error(
+ res,
+ status,
+ err.code || (status >= 500 ? 'internal_error' : 'bad_request'),
+ err.message || 'error',
+ );
+ }
}
}
// Keep the lambda alive briefly so the zauth SDK's in-flight POST to
diff --git a/api/_lib/migrations/2026-05-04-pumpfun-graduations.sql b/api/_lib/migrations/2026-05-04-pumpfun-graduations.sql
new file mode 100644
index 000000000..918cefc4b
--- /dev/null
+++ b/api/_lib/migrations/2026-05-04-pumpfun-graduations.sql
@@ -0,0 +1,43 @@
+-- pumpfun_graduations
+--
+-- Persisted record of every pump.fun → PumpAMM (or Raydium) migration we
+-- observe via the PumpPortal websocket. The live SSE feed enriches each event
+-- and stores it here so:
+-- - new SSE clients can backfill across cold starts (in-process ring buffer
+-- loses everything when the Vercel function recycles);
+-- - a synchronous /api/pump/recent-graduations endpoint can answer
+-- fast queries without keeping a WebSocket open;
+-- - graduations remain queryable for analytics/reputation work.
+--
+-- The full enriched payload is stored as JSONB so renderer changes don't
+-- require schema migrations. Promoted columns are the ones we filter / sort by.
+
+create table if not exists pumpfun_graduations (
+ tx_signature text primary key,
+ mint text not null,
+ name text,
+ symbol text,
+ creator text,
+ pool text, -- pump-amm | raydium | …
+ raydium_pool text,
+ pump_swap_pool text,
+ market_cap_usd double precision,
+ market_cap_usd_initial double precision,
+ ath_market_cap double precision,
+ amount_sol double precision,
+ amount_usd double precision,
+ sol_price double precision,
+ image_uri text,
+ description text,
+ twitter text,
+ telegram text,
+ website text,
+ creator_launches integer,
+ creator_graduated integer,
+ payload jsonb not null default '{}'::jsonb,
+ seen_at timestamptz not null default now()
+);
+
+create index if not exists pumpfun_graduations_seen_at on pumpfun_graduations(seen_at desc);
+create index if not exists pumpfun_graduations_mint on pumpfun_graduations(mint);
+create index if not exists pumpfun_graduations_creator on pumpfun_graduations(creator) where creator is not null;
diff --git a/api/_lib/pump.js b/api/_lib/pump.js
index 966fd1dda..9de3556ec 100644
--- a/api/_lib/pump.js
+++ b/api/_lib/pump.js
@@ -11,9 +11,12 @@
// solanaPubkey(s) → PublicKey or null
//
// Network selection: 'mainnet' | 'devnet'. Endpoint URLs come from env so
-// production can pin Helius / Triton / etc. RPC providers.
+// production can pin Helius / Triton / etc. RPC providers. Setting
+// SOLANA_RPC_FALLBACK_URLS (comma-separated) enables the multi-endpoint
+// RpcFallback wrapper for read-side handlers that opt in via getRpcFallback().
import { Connection, PublicKey } from '@solana/web3.js';
+import { rpcFallbackFromEnv } from './solana/rpc-fallback.js';
const RPC_MAINNET = () => process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
const RPC_DEVNET = () => process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';
@@ -23,6 +26,13 @@ export function getConnection({ network = 'mainnet', commitment = 'confirmed' }
return new Connection(url, commitment);
}
+// Returns an RpcFallback wrapper for read-only flows that benefit from
+// multi-endpoint rotation. Always returns an instance — when no fallbacks are
+// configured it just wraps the single primary URL with no behavior change.
+export function getRpcFallback({ network = 'mainnet', commitment = 'confirmed' } = {}) {
+ return rpcFallbackFromEnv({ network, commitment });
+}
+
export function solanaPubkey(s) {
if (!s) return null;
try {
diff --git a/api/_lib/pumpfun-ws-feed.js b/api/_lib/pumpfun-ws-feed.js
index fddc4061c..d0390c351 100644
--- a/api/_lib/pumpfun-ws-feed.js
+++ b/api/_lib/pumpfun-ws-feed.js
@@ -8,6 +8,23 @@ import WebSocket from 'ws';
const PUMPPORTAL_WS = 'wss://pumpportal.fun/api/data';
const RECONNECT_DELAY_MS = 2_000;
const MAX_RECONNECTS = 5;
+
+// Cross-emit dedupe by tx signature. PumpPortal can occasionally redeliver an
+// event after a transient WS hiccup; this prevents duplicate cards.
+const SEEN_SIG_LIMIT = 2_000;
+const _seenSigs = new Map(); // sig → ts
+function markSeen(sig) {
+ if (!sig) return false;
+ if (_seenSigs.has(sig)) return false;
+ _seenSigs.set(sig, Date.now());
+ if (_seenSigs.size > SEEN_SIG_LIMIT) {
+ // Drop the oldest 25% — Map preserves insertion order.
+ const drop = Math.floor(SEEN_SIG_LIMIT / 4);
+ const it = _seenSigs.keys();
+ for (let i = 0; i < drop; i++) _seenSigs.delete(it.next().value);
+ }
+ return true;
+}
const META_TIMEOUT_MS = 2_500;
const SOL_PRICE_TTL_MS = 60_000;
@@ -91,21 +108,27 @@ export function connectPumpFunFeed({ onEvent, signal, kind = 'all' }) {
if (msg.message) return; // ack
if (msg.txType === 'create' && (kind === 'all' || kind === 'mint')) {
+ if (!markSeen(msg.signature)) return;
enrichMint(msg).then((data) => {
pushBuffer('mint', data);
if (active) onEvent({ kind: 'mint', data });
- }).catch(() => {
+ }).catch((err) => {
+ console.warn('[pumpportal-ws] mint enrich failed:', err?.message);
const data = normalizeMint(msg, null, 0);
pushBuffer('mint', data);
if (active) onEvent({ kind: 'mint', data });
});
} else if ((msg.txType === 'migrate' || msg.txType === 'migration') && (kind === 'all' || kind === 'graduation')) {
+ if (!markSeen(msg.signature)) return;
enrichGrad(msg).then((data) => {
pushBuffer('graduation', data);
+ persistGraduation(data);
if (active) onEvent({ kind: 'graduation', data });
- }).catch(() => {
+ }).catch((err) => {
+ console.warn('[pumpportal-ws] grad enrich failed:', err?.message);
const data = normalizeGrad(msg);
pushBuffer('graduation', data);
+ persistGraduation(data);
if (active) onEvent({ kind: 'graduation', data });
});
}
@@ -373,3 +396,88 @@ export function recentBuffered({ kind = 'all', limit = 10 } = {}) {
});
return out.slice(0, limit);
}
+
+// ── Persistence ──────────────────────────────────────────────────────────────
+//
+// Writing graduations to Postgres lets a fresh container backfill from real
+// history rather than the in-memory buffer (which dies on every cold start).
+// The DB write is fire-and-forget — we never block the SSE stream on it. If
+// DATABASE_URL isn't configured (dev), the import is lazy so we don't fail.
+
+let _sqlPromise = null;
+async function getSql() {
+ if (_sqlPromise) return _sqlPromise;
+ _sqlPromise = import('./db.js').then((m) => m.sql).catch((err) => {
+ console.warn('[pumpportal-ws] db import failed:', err?.message);
+ return null;
+ });
+ return _sqlPromise;
+}
+
+async function persistGraduation(data) {
+ if (!data?.tx_signature && !data?.signature) return;
+ const sql = await getSql();
+ if (!sql) return;
+ try {
+ const sig = data.tx_signature || data.signature;
+ const finite = (n) => (typeof n === 'number' && Number.isFinite(n) ? n : null);
+ await sql`
+ insert into pumpfun_graduations (
+ tx_signature, mint, name, symbol, creator, pool, raydium_pool, pump_swap_pool,
+ market_cap_usd, market_cap_usd_initial, ath_market_cap,
+ amount_sol, amount_usd, sol_price, image_uri, description,
+ twitter, telegram, website, creator_launches, creator_graduated, payload
+ ) values (
+ ${sig}, ${data.mint || null}, ${data.name || null}, ${data.symbol || null},
+ ${data.creator || null}, ${data.pool || null}, ${data.raydium_pool || null},
+ ${data.pump_swap_pool || null},
+ ${finite(data.usd_market_cap ?? data.market_cap)},
+ ${finite(data.market_cap_usd_initial)},
+ ${finite(data.ath_market_cap)},
+ ${finite(data.amount_sol)},
+ ${finite(data.amount_usd)},
+ ${finite(data.sol_price)},
+ ${data.image_uri || null}, ${data.description || null},
+ ${data.twitter || null}, ${data.telegram || null}, ${data.website || null},
+ ${Number.isFinite(data.creator_launches) ? data.creator_launches : null},
+ ${Number.isFinite(data.creator_graduated) ? data.creator_graduated : null},
+ ${JSON.stringify(data)}::jsonb
+ )
+ on conflict (tx_signature) do nothing
+ `;
+ } catch (err) {
+ // Don't take down the feed if a single write fails (e.g. transient
+ // Neon timeout). Log once and move on.
+ console.warn('[pumpportal-ws] persist failed:', err?.message);
+ }
+}
+
+/**
+ * Read recent graduations from Postgres. Falls back to the in-memory ring
+ * buffer when the DB is unreachable so dev/test environments still work.
+ * Used by the HTTP backfill endpoint and as a warmup source on cold start.
+ *
+ * @param {{ limit?: number }} opts
+ * @returns {Promise<Array<object>>} newest-first array of graduation payloads.
+ */
+export async function recentGraduations({ limit = 20 } = {}) {
+ const cap = Math.max(1, Math.min(100, limit | 0 || 20));
+ try {
+ const sql = await getSql();
+ if (sql) {
+ const rows = await sql`
+ select payload, seen_at
+ from pumpfun_graduations
+ order by seen_at desc
+ limit ${cap}
+ `;
+ if (Array.isArray(rows) && rows.length) {
+ return rows.map((r) => ({ ...r.payload, _seen_at: r.seen_at }));
+ }
+ }
+ } catch (err) {
+ console.warn('[pumpportal-ws] recentGraduations db read failed:', err?.message);
+ }
+ // Buffer fallback (dev / DB outage).
+ return _buffer.graduation.slice(0, cap);
+}
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index d54ebdd5d..0c515f9be 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -963,3 +963,34 @@ do $$ begin
create trigger plugins_set_updated_at before update on plugins
for each row execute function set_updated_at();
exception when duplicate_object then null; end $$;
+
+-- ── pumpfun_graduations — persisted pump.fun → AMM migration events ──────────
+-- See migrations/2026-05-04-pumpfun-graduations.sql for the full schema.
+create table if not exists pumpfun_graduations (
+ tx_signature text primary key,
+ mint text not null,
+ name text,
+ symbol text,
+ creator text,
+ pool text,
+ raydium_pool text,
+ pump_swap_pool text,
+ market_cap_usd double precision,
+ market_cap_usd_initial double precision,
+ ath_market_cap double precision,
+ amount_sol double precision,
+ amount_usd double precision,
+ sol_price double precision,
+ image_uri text,
+ description text,
+ twitter text,
+ telegram text,
+ website text,
+ creator_launches integer,
+ creator_graduated integer,
+ payload jsonb not null default '{}'::jsonb,
+ seen_at timestamptz not null default now()
+);
+create index if not exists pumpfun_graduations_seen_at on pumpfun_graduations(seen_at desc);
+create index if not exists pumpfun_graduations_mint on pumpfun_graduations(mint);
+create index if not exists pumpfun_graduations_creator on pumpfun_graduations(creator) where creator is not null;
diff --git a/api/_lib/validate.js b/api/_lib/validate.js
index 362884d7d..bc1274a1e 100644
--- a/api/_lib/validate.js
+++ b/api/_lib/validate.js
@@ -92,7 +92,29 @@ export function parse(schema, input) {
);
err.status = 400;
err.code = 'validation_error';
+ err.issues = res.error.issues.map((i) => ({
+ path: i.path,
+ code: i.code,
+ message: i.message,
+ }));
throw err;
}
return res.data;
}
+
+// Read JSON body and zod-parse in one call. Returns the parsed payload, or
+// throws a structured 400 with `issues` for the API error envelope to surface.
+//
+// Pair with the `wrap()` helper in http.js to get consistent error responses.
+export async function validateBody(req, schema, opts = {}) {
+ const { readJson } = await import('./http.js');
+ const raw = await readJson(req, opts.limit);
+ return parse(schema, raw);
+}
+
+// Same idea for query strings — useful for GET endpoints that take typed filters.
+export function validateQuery(req, schema) {
+ const url = new URL(req.url, 'http://x');
+ const obj = Object.fromEntries(url.searchParams.entries());
+ return parse(schema, obj);
+}
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index bb0ad7431..6ef6cf875 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -89,9 +89,18 @@ function decodePaymentHeader(header) {
return payload;
}
+function hostOf(url) {
+ try {
+ return new URL(url).host;
+ } catch {
+ return url;
+ }
+}
+
async function callFacilitator(network, path, body) {
const { url: base, token } = facilitatorFor(network);
const url = `${base}${path}`;
+ const host = hostOf(base);
const headers = { 'content-type': 'application/json', accept: 'application/json' };
if (token) headers.authorization = `Bearer ${token}`;
let res;
@@ -105,7 +114,7 @@ async function callFacilitator(network, path, body) {
} catch (err) {
throw new X402Error(
'facilitator_unreachable',
- `facilitator ${path} fetch failed: ${err.message}`,
+ `facilitator ${path} (${host}, network=${network}) fetch failed: ${err.message}`,
502,
);
}
@@ -117,7 +126,7 @@ async function callFacilitator(network, path, body) {
} catch {
throw new X402Error(
'facilitator_bad_response',
- `facilitator ${path} returned non-JSON (status ${res.status})`,
+ `facilitator ${path} (${host}, network=${network}) returned non-JSON (status ${res.status})`,
502,
);
}
@@ -128,13 +137,70 @@ async function callFacilitator(network, path, body) {
if (path === '/verify' && data.isValid === false) return data;
throw new X402Error(
'facilitator_error',
- `facilitator ${path} ${res.status}: ${data.error || data.message || data.invalidReason || text.slice(0, 200)}`,
+ `facilitator ${path} (${host}, network=${network}) ${res.status}: ${data.error || data.message || data.invalidReason || text.slice(0, 200)}`,
502,
);
}
return data;
}
+// Probe `/supported` on each configured facilitator and report whether the
+// scheme/network pairs we advertise are actually supported. Used by
+// /api/x402-status to surface misconfigurations before a paying client hits them.
+export async function probeFacilitators() {
+ const targets = [
+ { network: 'solana', ...facilitatorFor('solana') },
+ { network: 'base', ...facilitatorFor('base') },
+ ];
+ const seen = new Map();
+ const results = [];
+ for (const t of targets) {
+ if (!t.url) {
+ results.push({ network: t.network, ok: false, reason: 'no facilitator URL configured' });
+ continue;
+ }
+ let entry = seen.get(t.url);
+ if (!entry) {
+ entry = (async () => {
+ try {
+ const res = await fetch(`${t.url}/supported`, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!res.ok) return { error: `status ${res.status}` };
+ const json = await res.json();
+ return { kinds: Array.isArray(json?.kinds) ? json.kinds : [] };
+ } catch (err) {
+ return { error: err.message };
+ }
+ })();
+ seen.set(t.url, entry);
+ }
+ const data = await entry;
+ if (data.error) {
+ results.push({
+ network: t.network,
+ url: t.url,
+ ok: false,
+ reason: `/supported probe failed: ${data.error}`,
+ });
+ continue;
+ }
+ const supports = data.kinds.some(
+ (k) => k.scheme === 'exact' && k.network === t.network && (k.x402Version ?? 1) === X402_VERSION,
+ );
+ results.push({
+ network: t.network,
+ url: t.url,
+ ok: supports,
+ reason: supports
+ ? `facilitator advertises exact/${t.network}`
+ : `facilitator does NOT advertise scheme=exact network=${t.network} (configure X402_FACILITATOR_URL_${t.network.toUpperCase()} to a facilitator that does)`,
+ });
+ }
+ return results;
+}
+
// Match the decoded payload to one of the offered requirements (by network).
// Falls back to the first requirement when the payload omits an explicit network field.
function selectRequirement(paymentPayload, allRequirements) {
diff --git a/api/openapi-json.js b/api/openapi-json.js
index e2a2732bb..96c4264f4 100644
--- a/api/openapi-json.js
+++ b/api/openapi-json.js
@@ -183,6 +183,42 @@ export default wrap(async (req, res) => {
},
},
},
+ '/api/pump/curve': {
+ get: {
+ operationId: 'pump_curve',
+ summary: 'Pump.fun bonding-curve snapshot',
+ description:
+ 'Returns raw bonding-curve state, current spot price + market cap, and graduation progress for a Pump.fun token. Public, edge-cached for 10s.',
+ parameters: [
+ { name: 'mint', in: 'query', required: true, schema: { type: 'string' }, description: 'Base58 SPL mint address' },
+ { name: 'network', in: 'query', schema: { type: 'string', enum: ['mainnet', 'devnet'] } },
+ ],
+ responses: {
+ 200: { description: 'Bonding curve snapshot' },
+ 400: { description: 'Bad mint' },
+ 404: { description: 'No bonding curve for that mint' },
+ },
+ },
+ },
+ '/api/pump/quote-sdk': {
+ get: {
+ operationId: 'pump_quote_sdk',
+ summary: 'Pump.fun buy/sell quote (SDK-precise)',
+ description:
+ 'Deterministic buy or sell quote computed via @nirholas/pump-sdk on the live bonding curve. Returns output amount, price impact %, and a market context block.',
+ parameters: [
+ { name: 'mint', in: 'query', required: true, schema: { type: 'string' } },
+ { name: 'side', in: 'query', required: true, schema: { type: 'string', enum: ['buy', 'sell'] } },
+ { name: 'amount', in: 'query', required: true, schema: { type: 'number', minimum: 0 }, description: 'For buy: SOL. For sell: tokens (UI units, 6 decimals).' },
+ { name: 'network', in: 'query', schema: { type: 'string', enum: ['mainnet', 'devnet'] } },
+ ],
+ responses: {
+ 200: { description: 'Quote payload with input/output and priceImpactPct' },
+ 400: { description: 'Validation error' },
+ 404: { description: 'No bonding curve for that mint' },
+ },
+ },
+ },
},
},
{ 'cache-control': 'public, max-age=300' },
diff --git a/api/pump/[action].js b/api/pump/[action].js
index 2c251b863..c71d51a27 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -96,6 +96,7 @@ const wrapped = wrap(async (req, res) => {
case 'channel-feed': return handleChannelFeed(req, res);
case 'deliver-telegram': return handleDeliverTelegram(req, res);
case 'first-claims': return handleFirstClaims(req, res);
+ case 'recent-graduations': return handleRecentGraduations(req, res);
default:
return error(res, 404, 'not_found', 'unknown pump action');
}
@@ -1793,6 +1794,31 @@ export async function scanFirstClaims({ sinceTs, limit }) {
return filterFirstClaims(allClaims, sinceTs, lim);
}
+// ── recent-graduations ───────────────────────────────────────────────────────
+//
+// Returns the most-recent enriched graduation events as a single JSON payload.
+// The page calls this once on load to backfill the feed before it opens an
+// SSE connection. Reads from Postgres if available, falls back to the WS
+// feed's in-process ring buffer (covers cold starts before the first migration
+// arrives, plus dev environments without a DB).
+
+async function handleRecentGraduations(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+ const url = new URL(req.url, 'http://x');
+ const limit = Math.max(1, Math.min(100, Number(url.searchParams.get('limit')) || 20));
+ try {
+ const { recentGraduations } = await import('../_lib/pumpfun-ws-feed.js');
+ const items = await recentGraduations({ limit });
+ return json(res, 200, { items }, { 'cache-control': 'public, max-age=5' });
+ } catch (err) {
+ console.warn('[recent-graduations] failed:', err?.message);
+ return json(res, 200, { items: [] });
+ }
+}
+
async function handleFirstClaims(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
diff --git a/api/pump/curve.js b/api/pump/curve.js
index 22ca95762..d0edde1c7 100644
--- a/api/pump/curve.js
+++ b/api/pump/curve.js
@@ -51,16 +51,14 @@ export default wrap(async (req, res) => {
return error(res, 404, 'no_curve', 'no bonding curve found for that mint');
}
- res.setHeader('Cache-Control', 'public, max-age=5, s-maxage=10, stale-while-revalidate=30');
return json(res, 200, {
mint,
network,
- rpc: undefined,
...result,
// price/graduation values from the SDK contain BNs — stringify them for JSON wire safety
price: result.price ? serializeBNs(result.price) : null,
graduation: result.graduation ? serializeBNs(result.graduation) : null,
- });
+ }, { 'cache-control': 'public, max-age=5, s-maxage=10, stale-while-revalidate=30' });
});
function serializeBNs(obj) {
diff --git a/api/pump/helius-stats.js b/api/pump/helius-stats.js
new file mode 100644
index 000000000..e2afc6ef1
--- /dev/null
+++ b/api/pump/helius-stats.js
@@ -0,0 +1,91 @@
+// GET /api/pump/helius-stats
+// --------------------------
+// Lightweight network/feed health endpoint for the /pumpfun page. Returns:
+// - sol_price (USD, cached upstream)
+// - helius { enabled, slot, blockTime, network } when HELIUS_API_KEY is set
+// - feed { mints, graduations } counts from the in-process replay buffer
+//
+// Designed to be polled every ~5s by the page to drive the live network panel
+// next to the "Powered by Helius" pill. When Helius is not configured the
+// `helius.enabled` flag is false and the page falls back to attribution-only.
+//
+// Public, cacheable for 3s. No auth.
+
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { recentBuffered } from '../_lib/pumpfun-ws-feed.js';
+
+const HELIUS_RPC = 'https://mainnet.helius-rpc.com';
+let _solCache = { price: 0, at: 0 };
+let _heliusCache = { value: null, at: 0 };
+
+async function getSolPrice() {
+ if (Date.now() - _solCache.at < 60_000 && _solCache.price > 0) return _solCache.price;
+ try {
+ const r = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd&include_24hr_change=true');
+ const d = await r.json();
+ const p = d?.solana?.usd;
+ const c = d?.solana?.usd_24h_change;
+ if (p > 0) _solCache = { price: p, change_24h: c, at: Date.now() };
+ } catch {}
+ return _solCache.price || 0;
+}
+
+async function getHeliusInfo() {
+ const key = process.env.HELIUS_API_KEY;
+ if (!key) return { enabled: false };
+ if (Date.now() - _heliusCache.at < 4_000 && _heliusCache.value) return _heliusCache.value;
+ try {
+ const ctrl = new AbortController();
+ const tid = setTimeout(() => ctrl.abort(), 1500);
+ const r = await fetch(`${HELIUS_RPC}/?api-key=${key}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ signal: ctrl.signal,
+ body: JSON.stringify({
+ jsonrpc: '2.0', id: 1, method: 'getSlot', params: [{ commitment: 'confirmed' }],
+ }),
+ });
+ clearTimeout(tid);
+ const d = await r.json();
+ const slot = Number(d?.result) || null;
+ const value = { enabled: true, slot, network: 'mainnet', endpoint: 'helius-rpc' };
+ _heliusCache = { value, at: Date.now() };
+ return value;
+ } catch (err) {
+ const value = { enabled: true, slot: null, network: 'mainnet', error: 'unreachable' };
+ _heliusCache = { value, at: Date.now() };
+ return value;
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const [solPrice, helius] = await Promise.all([getSolPrice(), getHeliusInfo()]);
+
+ const mints = recentBuffered({ kind: 'mint', limit: 25 });
+ const grads = recentBuffered({ kind: 'graduation', limit: 25 });
+ const now = Math.floor(Date.now() / 1000);
+ const window60 = (arr, key) => arr.filter((e) => {
+ const t = e?.data?.[key] || e?.data?.timestamp || e?.data?.created_at || 0;
+ return t && now - t <= 60;
+ }).length;
+ const window3600 = (arr, key) => arr.filter((e) => {
+ const t = e?.data?.[key] || e?.data?.timestamp || e?.data?.created_at || 0;
+ return t && now - t <= 3600;
+ }).length;
+
+ return json(res, 200, {
+ sol_price: solPrice || null,
+ sol_change_24h: _solCache.change_24h ?? null,
+ helius,
+ feed: {
+ mints_per_min: window60(mints, 'created_at'),
+ graduations_per_hour: window3600(grads, 'timestamp'),
+ buffered_mints: mints.length,
+ buffered_graduations: grads.length,
+ },
+ ts: Date.now(),
+ }, { 'cache-control': 'public, max-age=3' });
+});
diff --git a/api/pump/quote-sdk.js b/api/pump/quote-sdk.js
new file mode 100644
index 000000000..f84ed7813
--- /dev/null
+++ b/api/pump/quote-sdk.js
@@ -0,0 +1,105 @@
+// GET /api/pump/quote-sdk?mint=<mint>&side=buy|sell&amount=<n>[&network=]
+// ----------------------------------------------------------------------
+// Public, read-only quote endpoint backed by @nirholas/pump-sdk via the
+// sdk-bridge helpers. Returns deterministic SDK math instead of the dashboard's
+// previous "use the SDK for precise quote calculation" placeholder.
+//
+// side=buy amount = SOL (decimal, e.g. 0.5)
+// side=sell amount = tokens (UI units, e.g. 100000)
+//
+// Edge-cached for 5s — bonding curves move per-trade so a few seconds of
+// staleness keeps RPC cost down without misleading users.
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { getRpcFallback } from '../_lib/pump.js';
+import { getBuyQuote, getSellQuote, getTokenPrice } from '../_lib/solana/index.js';
+
+const LAMPORTS_PER_SOL = 1_000_000_000;
+// Pump bonding-curve tokens use 6 decimals.
+const PUMP_TOKEN_DECIMALS = 6;
+const TOKEN_BASE = 10 ** PUMP_TOKEN_DECIMALS;
+
+function isPlausibleMint(s) { return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s); }
+
+function readQuery(req) {
+ try {
+ const u = new URL(req.url, 'http://x');
+ return {
+ mint: (u.searchParams.get('mint') || '').trim(),
+ side: (u.searchParams.get('side') || 'buy').toLowerCase(),
+ amount: u.searchParams.get('amount'),
+ network: u.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet',
+ };
+ } catch {
+ return { mint: '', side: 'buy', amount: null, network: 'mainnet' };
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const { mint, side, amount, network } = readQuery(req);
+ if (!mint || !isPlausibleMint(mint)) {
+ return error(res, 400, 'bad_mint', 'mint query param must be a base58 Solana address');
+ }
+ if (side !== 'buy' && side !== 'sell') {
+ return error(res, 400, 'bad_side', 'side must be "buy" or "sell"');
+ }
+ const amt = Number(amount);
+ if (!Number.isFinite(amt) || amt <= 0) {
+ return error(res, 400, 'bad_amount', 'amount must be a positive number');
+ }
+
+ const rpc = getRpcFallback({ network });
+
+ // Convert UI units → on-chain integer base units expected by the SDK.
+ const baseUnits = side === 'buy'
+ ? BigInt(Math.floor(amt * LAMPORTS_PER_SOL)).toString()
+ : BigInt(Math.floor(amt * TOKEN_BASE)).toString();
+
+ const result = await rpc.withFallback(async (connection) => {
+ const [quote, price] = await Promise.all([
+ side === 'buy'
+ ? getBuyQuote(connection, mint, baseUnits)
+ : getSellQuote(connection, mint, baseUnits),
+ getTokenPrice(connection, mint),
+ ]);
+ return { quote, price };
+ });
+
+ if (!result.quote) {
+ return error(res, 404, 'no_curve', 'no bonding curve found for that mint (graduated?)');
+ }
+
+ const out = {
+ mint,
+ network,
+ side,
+ input: side === 'buy'
+ ? { sol: amt, lamports: baseUnits }
+ : { tokens: amt, baseUnits },
+ output: side === 'buy'
+ ? { tokens: result.quote.tokens.toString(), tokensUi: Number(result.quote.tokens.toString()) / TOKEN_BASE }
+ : { lamports: result.quote.sol.toString(), sol: Number(result.quote.sol.toString()) / LAMPORTS_PER_SOL },
+ priceImpactPct: result.quote.priceImpact,
+ marketContext: result.price ? serializeBNs(result.price) : null,
+ };
+
+ return json(res, 200, out, { 'cache-control': 'public, max-age=2, s-maxage=5, stale-while-revalidate=15' });
+});
+
+function serializeBNs(obj) {
+ if (obj == null || typeof obj !== 'object') return obj;
+ const out = Array.isArray(obj) ? [] : {};
+ for (const [k, v] of Object.entries(obj)) {
+ if (v && typeof v === 'object' && typeof v.toString === 'function' && (v.constructor?.name === 'BN' || typeof v.toNumber === 'function')) {
+ out[k] = v.toString();
+ } else if (v && typeof v === 'object') {
+ out[k] = serializeBNs(v);
+ } else {
+ out[k] = v;
+ }
+ }
+ return out;
+}
diff --git a/api/x402-status.js b/api/x402-status.js
new file mode 100644
index 000000000..1a4a43bb2
--- /dev/null
+++ b/api/x402-status.js
@@ -0,0 +1,43 @@
+// GET /api/x402-status — operational probe for the x402 wiring.
+//
+// Reports the configured pay-to addresses, asset mints/contracts, and probes
+// each facilitator's /supported endpoint to confirm it advertises scheme=exact
+// for the network we route to it. Surfaces misconfigurations (e.g. Coinbase's
+// reference facilitator, which only supports base-sepolia) before a paying
+// client hits a 502.
+
+import { cors, json, method, wrap } from './_lib/http.js';
+import { env } from './_lib/env.js';
+import { paymentRequirements, probeFacilitators, X402_VERSION } from './_lib/x402-spec.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const accepts = paymentRequirements({
+ resource: `${env.APP_ORIGIN}/api/mcp`,
+ description: 'MCP tool call',
+ });
+ const facilitators = await probeFacilitators();
+ const ok = facilitators.every((f) => f.ok);
+
+ return json(
+ res,
+ ok ? 200 : 503,
+ {
+ ok,
+ x402Version: X402_VERSION,
+ accepts,
+ facilitators,
+ env: {
+ X402_PAY_TO_SOLANA: env.X402_PAY_TO_SOLANA || null,
+ X402_PAY_TO_BASE: env.X402_PAY_TO_BASE || null,
+ X402_ASSET_MINT_SOLANA: env.X402_ASSET_MINT_SOLANA || null,
+ X402_ASSET_ADDRESS_BASE: env.X402_ASSET_ADDRESS_BASE || null,
+ X402_FEE_PAYER_SOLANA: env.X402_FEE_PAYER_SOLANA || null,
+ X402_MAX_AMOUNT_REQUIRED: env.X402_MAX_AMOUNT_REQUIRED || null,
+ },
+ },
+ { 'cache-control': 'no-store' },
+ );
+});
diff --git a/contracts/idl/pump/pump_fees.json b/contracts/idl/pump/pump_fees.json
index 66ed115a8..8b45bbbeb 100644
--- a/contracts/idl/pump/pump_fees.json
+++ b/contracts/idl/pump/pump_fees.json
@@ -899,7 +899,7 @@
{
"name": "reset_fee_sharing_config",
"docs": [
- "Reset Fee Sharing Config, make sure to distribute all the fees before calling this"
+ "Reset Fee Sharing Config and distribute pending fees first"
],
"discriminator": [
10,
@@ -912,6 +912,42 @@
186
],
"accounts": [
+ {
+ "name": "new_admin"
+ },
+ {
+ "name": "event_authority",
+ "pda": {
+ "seeds": [
+ {
+ "kind": "const",
+ "value": [
+ 95,
+ 95,
+ 101,
+ 118,
+ 101,
+ 110,
+ 116,
+ 95,
+ 97,
+ 117,
+ 116,
+ 104,
+ 111,
+ 114,
+ 105,
+ 116,
+ 121
+ ]
+ }
+ ]
+ }
+ },
+ {
+ "name": "program",
+ "address": "pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ"
+ },
{
"name": "authority",
"signer": true
@@ -971,9 +1007,6 @@
}
}
},
- {
- "name": "new_admin"
- },
{
"name": "mint",
"relations": [
@@ -1012,74 +1045,97 @@
}
},
{
- "name": "event_authority",
+ "name": "bonding_curve",
"pda": {
"seeds": [
{
"kind": "const",
"value": [
- 95,
- 95,
- 101,
- 118,
- 101,
+ 98,
+ 111,
110,
- 116,
- 95,
- 97,
+ 100,
+ 105,
+ 110,
+ 103,
+ 45,
+ 99,
117,
- 116,
- 104,
- 111,
114,
- 105,
- 116,
- 121
+ 118,
+ 101
]
+ },
+ {
+ "kind": "account",
+ "path": "mint"
}
- ]
+ ],
+ "program": {
+ "kind": "const",
+ "value": [
+ 1,
+ 86,
+ 224,
+ 246,
+ 147,
+ 102,
+ 90,
+ 207,
+ 68,
+ 219,
+ 21,
+ 104,
+ 191,
+ 23,
+ 91,
+ 170,
+ 81,
+ 137,
+ 203,
+ 151,
+ 245,
+ 210,
+ 255,
+ 59,
+ 101,
+ 93,
+ 43,
+ 182,
+ 253,
+ 109,
+ 24,
+ 176
+ ]
+ }
}
},
{
- "name": "program"
- }
- ],
- "args": []
- },
- {
- "name": "revoke_fee_sharing_authority",
- "docs": [
- "Revoke Fee Sharing Authority"
- ],
- "discriminator": [
- 18,
- 233,
- 158,
- 39,
- 185,
- 207,
- 58,
- 104
- ],
- "accounts": [
- {
- "name": "authority",
- "signer": true
- },
- {
- "name": "global",
+ "name": "pump_creator_vault",
+ "writable": true,
"pda": {
"seeds": [
{
"kind": "const",
"value": [
- 103,
- 108,
+ 99,
+ 114,
+ 101,
+ 97,
+ 116,
111,
- 98,
+ 114,
+ 45,
+ 118,
97,
- 108
+ 117,
+ 108,
+ 116
]
+ },
+ {
+ "kind": "account",
+ "path": "sharing_config"
}
],
"program": {
@@ -1122,44 +1178,85 @@
}
},
{
- "name": "mint",
- "relations": [
- "sharing_config"
- ]
+ "name": "system_program",
+ "address": "11111111111111111111111111111111"
},
{
- "name": "sharing_config",
- "writable": true,
+ "name": "pump_program",
+ "address": "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"
+ },
+ {
+ "name": "pump_event_authority",
"pda": {
"seeds": [
{
"kind": "const",
"value": [
- 115,
- 104,
- 97,
- 114,
- 105,
+ 95,
+ 95,
+ 101,
+ 118,
+ 101,
110,
- 103,
- 45,
- 99,
+ 116,
+ 95,
+ 97,
+ 117,
+ 116,
+ 104,
111,
- 110,
- 102,
+ 114,
105,
- 103
+ 116,
+ 121
]
- },
- {
- "kind": "account",
- "path": "mint"
}
- ]
+ ],
+ "program": {
+ "kind": "const",
+ "value": [
+ 1,
+ 86,
+ 224,
+ 246,
+ 147,
+ 102,
+ 90,
+ 207,
+ 68,
+ 219,
+ 21,
+ 104,
+ 191,
+ 23,
+ 91,
+ 170,
+ 81,
+ 137,
+ 203,
+ 151,
+ 245,
+ 210,
+ 255,
+ 59,
+ 101,
+ 93,
+ 43,
+ 182,
+ 253,
+ 109,
+ 24,
+ 176
+ ]
+ }
}
},
{
- "name": "event_authority",
+ "name": "pump_amm_program",
+ "address": "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"
+ },
+ {
+ "name": "amm_event_authority",
"pda": {
"seeds": [
{
@@ -1184,15 +1281,150 @@
121
]
}
- ]
+ ],
+ "program": {
+ "kind": "const",
+ "value": [
+ 12,
+ 20,
+ 222,
+ 252,
+ 130,
+ 94,
+ 198,
+ 118,
+ 148,
+ 37,
+ 8,
+ 24,
+ 187,
+ 101,
+ 64,
+ 101,
+ 244,
+ 41,
+ 141,
+ 49,
+ 86,
+ 213,
+ 113,
+ 180,
+ 212,
+ 248,
+ 9,
+ 12,
+ 24,
+ 233,
+ 168,
+ 99
+ ]
+ }
+ }
+ },
+ {
+ "name": "wsol_mint",
+ "address": "So11111111111111111111111111111111111111112"
+ },
+ {
+ "name": "token_program",
+ "address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
+ },
+ {
+ "name": "associated_token_program",
+ "address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
+ },
+ {
+ "name": "coin_creator_vault_authority",
+ "writable": true,
+ "pda": {
+ "seeds": [
+ {
+ "kind": "const",
+ "value": [
+ 99,
+ 114,
+ 101,
+ 97,
+ 116,
+ 111,
+ 114,
+ 95,
+ 118,
+ 97,
+ 117,
+ 108,
+ 116
+ ]
+ },
+ {
+ "kind": "account",
+ "path": "sharing_config"
+ }
+ ],
+ "program": {
+ "kind": "const",
+ "value": [
+ 12,
+ 20,
+ 222,
+ 252,
+ 130,
+ 94,
+ 198,
+ 118,
+ 148,
+ 37,
+ 8,
+ 24,
+ 187,
+ 101,
+ 64,
+ 101,
+ 244,
+ 41,
+ 141,
+ 49,
+ 86,
+ 213,
+ 113,
+ 180,
+ 212,
+ 248,
+ 9,
+ 12,
+ 24,
+ 233,
+ 168,
+ 99
+ ]
+ }
}
},
{
- "name": "program"
+ "name": "coin_creator_vault_ata",
+ "writable": true
}
],
"args": []
},
+ {
+ "name": "revoke_fee_sharing_authority",
+ "docs": [
+ "Revoke Fee Sharing Authority"
+ ],
+ "discriminator": [
+ 18,
+ 233,
+ 158,
+ 39,
+ 185,
+ 207,
+ 58,
+ 104
+ ],
+ "accounts": [],
+ "args": []
+ },
{
"name": "set_authority",
"discriminator": [
@@ -1576,139 +1808,7 @@
210,
96
],
- "accounts": [
- {
- "name": "authority",
- "signer": true
- },
- {
- "name": "global",
- "pda": {
- "seeds": [
- {
- "kind": "const",
- "value": [
- 103,
- 108,
- 111,
- 98,
- 97,
- 108
- ]
- }
- ],
- "program": {
- "kind": "const",
- "value": [
- 1,
- 86,
- 224,
- 246,
- 147,
- 102,
- 90,
- 207,
- 68,
- 219,
- 21,
- 104,
- 191,
- 23,
- 91,
- 170,
- 81,
- 137,
- 203,
- 151,
- 245,
- 210,
- 255,
- 59,
- 101,
- 93,
- 43,
- 182,
- 253,
- 109,
- 24,
- 176
- ]
- }
- }
- },
- {
- "name": "mint",
- "relations": [
- "sharing_config"
- ]
- },
- {
- "name": "sharing_config",
- "writable": true,
- "pda": {
- "seeds": [
- {
- "kind": "const",
- "value": [
- 115,
- 104,
- 97,
- 114,
- 105,
- 110,
- 103,
- 45,
- 99,
- 111,
- 110,
- 102,
- 105,
- 103
- ]
- },
- {
- "kind": "account",
- "path": "mint"
- }
- ]
- }
- },
- {
- "name": "new_admin"
- },
- {
- "name": "event_authority",
- "pda": {
- "seeds": [
- {
- "kind": "const",
- "value": [
- 95,
- 95,
- 101,
- 118,
- 101,
- 110,
- 116,
- 95,
- 97,
- 117,
- 116,
- 104,
- 111,
- 114,
- 105,
- 116,
- 121
- ]
- }
- ]
- }
- },
- {
- "name": "program"
- }
- ],
+ "accounts": [],
"args": []
},
{
@@ -2678,19 +2778,6 @@
243
]
},
- {
- "name": "RevokeFeeSharingAuthorityEvent",
- "discriminator": [
- 114,
- 23,
- 101,
- 60,
- 14,
- 190,
- 153,
- 62
- ]
- },
{
"name": "SetAuthorityEvent",
"discriminator": [
@@ -2769,19 +2856,6 @@
169
]
},
- {
- "name": "TransferFeeSharingAuthorityEvent",
- "discriminator": [
- 124,
- 143,
- 198,
- 245,
- 77,
- 184,
- 8,
- 236
- ]
- },
{
"name": "UpdateAdminEvent",
"discriminator": [
@@ -2884,7 +2958,7 @@
{
"code": 6009,
"name": "SharingConfigAdminRevoked",
- "msg": "Sharing config admin has been revoked"
+ "msg": "Sharing config authority has been revoked - sharing config can only be updated once"
},
{
"code": 6010,
@@ -2950,6 +3024,16 @@
"code": 6022,
"name": "UserIdTooLong",
"msg": "User ID exceeds maximum length"
+ },
+ {
+ "code": 6023,
+ "name": "DeprecatedInstruction",
+ "msg": "Instruction is deprecated"
+ },
+ {
+ "code": 6024,
+ "name": "FeeSharesAlreadyUpdated",
+ "msg": "Reward split can only be updated once"
}
],
"types": [
@@ -3424,30 +3508,14 @@
}
}
}
- }
- ]
- }
- },
- {
- "name": "RevokeFeeSharingAuthorityEvent",
- "type": {
- "kind": "struct",
- "fields": [
- {
- "name": "timestamp",
- "type": "i64"
- },
- {
- "name": "mint",
- "type": "pubkey"
},
{
- "name": "sharing_config",
- "type": "pubkey"
+ "name": "old_version",
+ "type": "u8"
},
{
- "name": "admin",
- "type": "pubkey"
+ "name": "new_version",
+ "type": "u8"
}
]
}
@@ -3710,34 +3778,6 @@
]
}
},
- {
- "name": "TransferFeeSharingAuthorityEvent",
- "type": {
- "kind": "struct",
- "fields": [
- {
- "name": "timestamp",
- "type": "i64"
- },
- {
- "name": "mint",
- "type": "pubkey"
- },
- {
- "name": "sharing_config",
- "type": "pubkey"
- },
- {
- "name": "old_admin",
- "type": "pubkey"
- },
- {
- "name": "new_admin",
- "type": "pubkey"
- }
- ]
- }
- },
{
"name": "UpdateAdminEvent",
"type": {
@@ -3826,6 +3866,10 @@
}
}
}
+ },
+ {
+ "name": "version",
+ "type": "u8"
}
]
}
@@ -3866,6 +3910,16 @@
}
],
"constants": [
+ {
+ "name": "AMM_CREATOR_VAULT_AUTHORITY_SEED",
+ "type": {
+ "array": [
+ "u8",
+ 13
+ ]
+ },
+ "value": "[99, 114, 101, 97, 116, 111, 114, 95, 118, 97, 117, 108, 116]"
+ },
{
"name": "FEE_CONFIG_SEED",
"type": "bytes",
@@ -3881,6 +3935,16 @@
},
"value": "[102, 101, 101, 45, 112, 114, 111, 103, 114, 97, 109, 45, 103, 108, 111, 98, 97, 108]"
},
+ {
+ "name": "PUMP_CREATOR_VAULT_SEED",
+ "type": {
+ "array": [
+ "u8",
+ 13
+ ]
+ },
+ "value": "[99, 114, 101, 97, 116, 111, 114, 45, 118, 97, 117, 108, 116]"
+ },
{
"name": "PUMP_GLOBAL_SEED",
"docs": [
diff --git a/package.json b/package.json
index 4f1e125df..6b9efeb06 100644
--- a/package.json
+++ b/package.json
@@ -66,6 +66,7 @@
"db:migrate": "node scripts/apply-migrations.mjs --apply",
"db:status": "node scripts/apply-migrations.mjs",
"pump:smoke": "node scripts/pumpfun-lifecycle-smoke.js",
+ "pump:refresh-idls": "node scripts/refresh-pump-idls.mjs",
"seed:skills": "node scripts/seed-skills.js"
},
"dependencies": {
diff --git a/public/lobehub/iframe/boot.js b/public/lobehub/iframe/boot.js
index 09cbb38e4..ab9ca8366 100644
--- a/public/lobehub/iframe/boot.js
+++ b/public/lobehub/iframe/boot.js
@@ -37,8 +37,14 @@ if (hostParam) {
}
}
+// Locked-on origin: once a valid host message arrives, we lock to that origin
+// for the rest of the session. Subsequent messages from any other origin are
+// ignored, even if they would have been allowed by the policy below.
+let lockedOrigin = null;
+
function isAllowedOrigin(origin) {
- if (!origin) return false;
+ if (!origin || origin === 'null') return false;
+ if (lockedOrigin) return origin === lockedOrigin;
if (allowedOrigin) return origin === allowedOrigin;
if (KNOWN_ORIGINS.has(origin)) return true;
if (isDev(origin)) return true;
@@ -66,7 +72,20 @@ function post(op, payload, inReplyTo) {
payload: payload ?? {},
};
if (inReplyTo) msg.inReplyTo = inReplyTo;
- const target = allowedOrigin ?? '*';
+ // Resolve target origin in priority order:
+ // 1. lockedOrigin (set after the first authenticated host message)
+ // 2. allowedOrigin (?host= URL param)
+ // 3. document.referrer (best-effort initial announcement)
+ let target = lockedOrigin || allowedOrigin;
+ if (!target) {
+ try {
+ if (document.referrer) target = new URL(document.referrer).origin;
+ } catch {}
+ }
+ if (!target) {
+ console.warn('[3d-agent] parent origin unknown; dropping', op);
+ return;
+ }
try {
window.parent.postMessage(msg, target);
} catch (_) {}
@@ -179,16 +198,21 @@ async function dispatchAction(op, payload, replyId) {
function onMessage(ev) {
const { origin, data } = ev;
if (!data || typeof data !== 'object') return;
+ if (ev.source !== window.parent) return;
- // Dev-harness handshake shortcut.
+ // Dev-harness handshake shortcut. Reply only to allowed, non-null origins.
if (data.type === 'handshake') {
+ if (!origin || origin === 'null') return;
+ if (!isAllowedOrigin(origin)) return;
+ if (!lockedOrigin) lockedOrigin = origin;
try {
- window.parent.postMessage({ type: 'ready', agentId }, ev.origin || '*');
+ window.parent.postMessage({ type: 'ready', agentId }, origin);
} catch (_) {}
return;
}
if (!isAllowedOrigin(origin)) return;
+ if (!lockedOrigin) lockedOrigin = origin;
// ── v1 spec envelope ──────────────────────────────────────────────────────
if (data.v === 1 && data.source === 'agent-host' && data.kind && data.op) {
diff --git a/public/pumpfun.html b/public/pumpfun.html
index f358631bc..db0d7d566 100644
--- a/public/pumpfun.html
+++ b/public/pumpfun.html
@@ -14,12 +14,17 @@
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
<script defer src="/footer-newsletter.js"></script>
<style>
- :root { color-scheme: dark; --accent: #6a5cff; --border: #1f1f29; --bg: #0a0a0f; --panel: #14141c; --muted: #888; }
+ :root { color-scheme: dark; --accent: #6a5cff; --border: #1f1f29; --bg: #0a0a0f; --panel: #14141c; --muted: #888;
+ --header-h: 64px; }
* { box-sizing: border-box; }
html, body { margin: 0; background: var(--bg); color: #eee;
font: 14px/1.55 -apple-system, system-ui, Segoe UI, Roboto, sans-serif; }
+ body.home-page { padding-top: var(--header-h); display: flex; flex-direction: column; min-height: 100vh; }
.pf-filterbar { padding: 10px 18px; border-bottom: 1px solid var(--border);
- display: flex; align-items: center; gap: 12px; flex-wrap: wrap; background: var(--panel); }
+ display: flex; align-items: center; gap: 12px; flex-wrap: wrap; background: var(--panel);
+ position: sticky; top: var(--header-h); z-index: 50; }
+ .status-pill[data-state="down"] { cursor: pointer; color: #f87171; border-color: #4a1f23; }
+ .status-pill[data-state="down"]:hover { background: #1f1418; }
.pf-filterbar h1 { margin: 0; font-size: 15px; font-weight: 600; display: inline-flex; align-items: center; gap: 8px; }
.dot { width: 8px; height: 8px; border-radius: 50%; background: #555; box-shadow: 0 0 0 0 currentColor; }
.dot.live { background: #4ade80; animation: pulse 1.6s ease-in-out infinite; }
@@ -55,14 +60,14 @@
/* Picker modal */
.pf-modal-backdrop { position: fixed; inset: 0; background: rgba(4,4,8,0.72); backdrop-filter: blur(4px); z-index: 100; display: none; align-items: center; justify-content: center; padding: 24px; animation: fade-in 0.15s ease; }
.pf-modal-backdrop[data-open="true"] { display: flex; }
- .pf-modal { width: min(960px, 100%); max-height: min(720px, calc(100vh - 48px)); background: var(--panel); border: 1px solid var(--border); border-radius: 12px; display: flex; flex-direction: column; overflow: hidden; box-shadow: 0 24px 64px rgba(0,0,0,0.5); animation: pop-in 0.18s ease; }
+ .pf-modal { width: min(1080px, 100%); max-height: min(760px, calc(100vh - 48px)); background: var(--panel); border: 1px solid var(--border); border-radius: 12px; display: flex; flex-direction: column; overflow: hidden; box-shadow: 0 24px 64px rgba(0,0,0,0.5); animation: pop-in 0.18s ease; }
.pf-modal-head { display: flex; align-items: center; gap: 12px; padding: 14px 18px; border-bottom: 1px solid var(--border); }
.pf-modal-head h2 { margin: 0; font-size: 14px; font-weight: 600; }
.pf-modal-head .spacer { flex: 1; }
.pf-modal-close { background: transparent; border: 0; color: var(--muted); cursor: pointer; font-size: 18px; line-height: 1; padding: 4px 8px; border-radius: 4px; }
.pf-modal-close:hover { background: #1f1f29; color: #eee; }
- .pf-tabs { display: flex; gap: 2px; padding: 0 14px; border-bottom: 1px solid var(--border); background: #10101a; }
- .pf-tab { background: transparent; border: 0; color: var(--muted); cursor: pointer; padding: 10px 14px; font-size: 13px; font-weight: 500; border-bottom: 2px solid transparent; }
+ .pf-tabs { display: flex; gap: 2px; padding: 0 14px; border-bottom: 1px solid var(--border); background: #10101a; overflow-x: auto; }
+ .pf-tab { background: transparent; border: 0; color: var(--muted); cursor: pointer; padding: 10px 14px; font-size: 13px; font-weight: 500; border-bottom: 2px solid transparent; white-space: nowrap; }
.pf-tab:hover { color: #eee; }
.pf-tab[aria-selected="true"] { color: #eee; border-bottom-color: var(--accent); }
.pf-tab .badge { display: inline-block; margin-left: 6px; font-size: 10px; color: var(--muted); }
@@ -73,30 +78,70 @@
.pf-toolbar .custom-row input { background: #161620; color: #eee; border: 1px solid #2a2a36; border-radius: 6px; padding: 7px 10px; font-size: 13px; width: 220px; }
.pf-toolbar .custom-row button { background: var(--accent); border: 0; color: #fff; border-radius: 6px; padding: 7px 12px; font-size: 13px; cursor: pointer; }
.pf-toolbar .custom-row button:hover { filter: brightness(1.1); }
- .pf-body { flex: 1; min-height: 0; overflow-y: auto; padding: 16px 18px; }
- .pf-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 12px; }
+ .pf-tags { display: flex; gap: 6px; flex-wrap: wrap; padding: 0 18px 10px; border-bottom: 1px solid var(--border); }
+ .pf-tags:empty { display: none; }
+ .pf-tag { background: #161620; border: 1px solid #2a2a36; color: #cbd5e1; border-radius: 999px; padding: 3px 10px; font-size: 11px; cursor: pointer; }
+ .pf-tag:hover { background: #20202c; }
+ .pf-tag[data-active="true"] { background: var(--accent); border-color: var(--accent); color: #fff; }
+ .pf-content { flex: 1; min-height: 0; display: grid; grid-template-columns: 1fr 280px; }
+ .pf-body { min-height: 0; overflow-y: auto; padding: 16px 18px; }
+ .pf-preview { border-left: 1px solid var(--border); background: #0d0d15; display: flex; flex-direction: column; min-height: 0; }
+ .pf-preview-stage { flex: 1; min-height: 0; position: relative; background: radial-gradient(ellipse at center, #1a1a26 0%, #0a0a12 70%); }
+ .pf-preview-stage model-viewer { width: 100%; height: 100%; --poster-color: transparent; background: transparent; }
+ .pf-preview-empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: #2a2a3a; font-size: 48px; pointer-events: none; }
+ .pf-preview-meta { padding: 12px 14px; border-top: 1px solid var(--border); }
+ .pf-preview-meta .name { font-size: 13px; font-weight: 600; }
+ .pf-preview-meta .sub { font-size: 11px; color: var(--muted); margin-top: 3px; }
+ .pf-preview-meta .actions { margin-top: 10px; display: flex; gap: 6px; flex-wrap: wrap; }
+ .pf-preview-meta .actions a, .pf-preview-meta .actions button { font-size: 11px; padding: 5px 10px; border-radius: 5px; background: #161620; border: 1px solid #2a2a36; color: #cbd5e1; text-decoration: none; cursor: pointer; }
+ .pf-preview-meta .actions a:hover, .pf-preview-meta .actions button:hover { background: #20202c; text-decoration: none; }
+ .pf-preview-meta .actions .primary { background: var(--accent); border-color: var(--accent); color: #fff; }
+ .pf-preview-meta .actions .primary:hover { filter: brightness(1.1); background: var(--accent); }
+ .pf-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 12px; }
.pf-card { position: relative; background: #161620; border: 1px solid #232330; border-radius: 8px; overflow: hidden; cursor: pointer; transition: border-color 0.15s, transform 0.1s; display: flex; flex-direction: column; text-align: left; padding: 0; color: #eee; font: inherit; }
- .pf-card:hover { border-color: #3a3a4a; }
+ .pf-card:hover, .pf-card:focus-visible { border-color: #3a3a4a; outline: none; }
+ .pf-card:focus-visible { box-shadow: 0 0 0 2px var(--accent); }
.pf-card:active { transform: scale(0.98); }
.pf-card[data-selected="true"] { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; }
.pf-card .thumb { aspect-ratio: 1/1; background: #0e0e16 center/cover no-repeat; border-bottom: 1px solid #232330; position: relative; display: flex; align-items: center; justify-content: center; color: #2a2a3a; font-size: 32px; }
.pf-card .meta { padding: 8px 10px; }
.pf-card .name { font-size: 12px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
- .pf-card .sub { font-size: 10px; color: var(--muted); margin-top: 2px; }
+ .pf-card .sub { font-size: 10px; color: var(--muted); margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.pf-card .vis-tag { position: absolute; top: 6px; right: 6px; font-size: 9px; padding: 2px 6px; border-radius: 999px; background: rgba(0,0,0,0.6); color: #cbd5e1; text-transform: uppercase; letter-spacing: 0.05em; }
.pf-card .vis-tag.private { background: rgba(74,31,35,0.85); color: #fbbf24; }
.pf-card .selected-mark { position: absolute; top: 6px; left: 6px; width: 18px; height: 18px; border-radius: 50%; background: var(--accent); display: none; align-items: center; justify-content: center; color: #fff; font-size: 11px; font-weight: 700; }
.pf-card[data-selected="true"] .selected-mark { display: flex; }
+ .pf-card .fav { position: absolute; bottom: 6px; right: 6px; background: rgba(0,0,0,0.55); border: 0; color: #cbd5e1; width: 22px; height: 22px; border-radius: 50%; cursor: pointer; font-size: 12px; line-height: 1; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.15s; padding: 0; }
+ .pf-card:hover .fav, .pf-card:focus-within .fav, .pf-card .fav[data-on="true"] { opacity: 1; }
+ .pf-card .fav[data-on="true"] { color: #fbbf24; }
+ .pf-skeleton { background: linear-gradient(90deg, #161620 0%, #1f1f2a 50%, #161620 100%); background-size: 200% 100%; animation: shimmer 1.4s linear infinite; border-radius: 8px; aspect-ratio: 1/1.25; }
+ @keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
.pf-status { padding: 32px 16px; text-align: center; color: var(--muted); font-size: 13px; }
.pf-status .cta { display: inline-block; margin-top: 10px; padding: 8px 14px; background: var(--accent); color: #fff; border-radius: 6px; font-size: 13px; }
.pf-status .cta:hover { filter: brightness(1.1); text-decoration: none; }
.pf-loadmore { display: block; margin: 16px auto 0; background: #161620; color: #eee; border: 1px solid #2a2a36; border-radius: 6px; padding: 8px 16px; font-size: 13px; cursor: pointer; }
.pf-loadmore:hover { background: #20202c; }
.pf-loadmore[disabled] { opacity: 0.5; cursor: wait; }
+ .pf-toast { position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%); z-index: 200; background: #161620; border: 1px solid #2a2a36; color: #eee; padding: 10px 16px; border-radius: 8px; font-size: 13px; box-shadow: 0 8px 24px rgba(0,0,0,0.4); animation: toast-in 0.2s ease; max-width: 90vw; }
+ .pf-toast.error { border-color: #4a1f23; background: #1f1418; color: #fbbf24; }
+ .pf-toast.success { border-color: #1f4232; background: #0e1f17; color: #4ade80; }
+ @keyframes toast-in { from { opacity: 0; transform: translate(-50%, 8px); } to { opacity: 1; transform: translate(-50%, 0); } }
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
@keyframes pop-in { from { opacity: 0; transform: translateY(8px) scale(0.98); } to { opacity: 1; transform: none; } }
- @media (max-width: 600px) { .pf-toolbar { flex-direction: column; align-items: stretch; } .pf-toolbar .custom-row input { width: 100%; } }
- main.pf-main { position: relative; height: calc(100vh - 140px); display: grid; grid-template-columns: 1fr 360px; }
+ @media (max-width: 760px) {
+ .pf-modal-backdrop { padding: 0; }
+ .pf-modal { width: 100%; max-height: 100vh; height: 100vh; border-radius: 0; border: 0; }
+ .pf-content { grid-template-columns: 1fr; grid-template-rows: 220px 1fr; }
+ .pf-preview { border-left: 0; border-bottom: 1px solid var(--border); order: -1; flex-direction: row; }
+ .pf-preview-stage { flex: 1; }
+ .pf-preview-meta { width: 50%; border-top: 0; border-left: 1px solid var(--border); }
+ .pf-toolbar { flex-direction: column; align-items: stretch; }
+ .pf-toolbar .custom-row input { width: 100%; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .pf-modal-backdrop, .pf-modal, .pf-skeleton, .pf-toast { animation: none; }
+ }
+ main.pf-main { position: relative; flex: 1; min-height: calc(100vh - var(--header-h) - 56px); display: grid; grid-template-columns: 1fr 360px; }
#stage { position: relative; display: flex; flex-direction: column; }
iframe { width: 100%; flex: 1; border: 0; display: block; background: var(--bg); }
#anim-chips { display: flex; gap: 6px; flex-wrap: wrap; padding: 8px 12px;
@@ -174,7 +219,38 @@
.evt-topic { font-size: 9px; padding: 1px 5px; background: #1f1f30; border: 1px solid #2a2a3c; border-radius: 10px; color: #7a7aaa; }
@keyframes evt-in { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }
- @media (max-width: 720px) { main.pf-main { grid-template-columns: 1fr; } #side { display: none; } }
+ /* Helius pill live event counter */
+ .helius-pill .helius-count { font-variant-numeric: tabular-nums; color: #cbd5e1; font-weight: 600;
+ padding: 1px 5px; border-radius: 4px; background: rgba(168,85,247,0.12); margin-right: 4px;
+ min-width: 16px; text-align: center; display: none; letter-spacing: 0; text-transform: none; }
+ .helius-pill[data-count="active"] .helius-count { display: inline-block; }
+
+ /* Jump-to-top button shown when feed is scrolled and new events queue up */
+ .feed-jump { position: absolute; left: 50%; transform: translateX(-50%); top: 8px; z-index: 4;
+ background: var(--accent); color: #fff; border: 0; border-radius: 999px; padding: 6px 12px;
+ font-size: 11px; font-weight: 600; cursor: pointer; box-shadow: 0 4px 12px rgba(106,92,255,0.4);
+ display: none; animation: fade-in 0.18s ease; }
+ .feed-jump[data-visible="true"] { display: inline-flex; align-items: center; gap: 6px; }
+ .feed-jump:hover { filter: brightness(1.1); }
+ #feed-wrap { position: relative; }
+
+ /* Share/copy-link button */
+ .pf-icon-btn { background: #161620; color: #ddd; border: 1px solid #2a2a36; border-radius: 6px;
+ padding: 6px 10px; font-size: 12px; cursor: pointer; display: inline-flex; align-items: center; gap: 5px; }
+ .pf-icon-btn:hover { background: #20202c; }
+ .pf-icon-btn[data-flash="true"] { border-color: #4ade80; color: #4ade80; }
+
+ /* Mobile side-panel toggle */
+ #side-toggle { display: none; }
+ @media (max-width: 720px) {
+ main.pf-main { grid-template-columns: 1fr; }
+ #side { position: fixed; top: calc(var(--header-h) + 56px); right: 0; bottom: 0;
+ width: min(360px, 92vw); transform: translateX(100%); transition: transform 0.22s ease;
+ z-index: 60; box-shadow: -8px 0 24px rgba(0,0,0,0.5); }
+ body.side-open #side { transform: translateX(0); }
+ #side-toggle { display: inline-flex; align-items: center; gap: 5px; }
+ body.side-open #side-toggle { background: var(--accent); color: #fff; border-color: var(--accent); }
+ }
</style>
</head>
<body class="home-page">
@@ -229,7 +305,7 @@
</header>
<div class="pf-filterbar">
<h1>✦ PumpFun migrations</h1>
- <span class="status-pill" id="status-pill"><span class="dot connecting" id="status-dot"></span><span id="status-label">connecting…</span></span>
+ <button type="button" class="status-pill" id="status-pill" data-state="connecting" title="Click to reconnect when offline"><span class="dot connecting" id="status-dot"></span><span id="status-label">connecting…</span></button>
<div class="ctl">
<input id="ctl-asset" type="text" placeholder="Solana asset pubkey (optional)" size="22" />
<input id="ctl-mint" type="text" placeholder="Filter mint…" size="18" />
@@ -253,6 +329,8 @@
</button>
</div>
<button id="ctl-narrate" class="toggle" type="button" data-on="1" title="Toggle agent narration">🔊 Narration</button>
+ <button id="ctl-share" class="pf-icon-btn" type="button" title="Copy a shareable link with current filters">🔗 <span id="ctl-share-label">Share</span></button>
+ <button id="side-toggle" class="pf-icon-btn" type="button" aria-pressed="false" aria-controls="side" title="Toggle live feed">📡 Feed</button>
</div>
</div>
<main class="pf-main">
@@ -268,7 +346,8 @@
<div class="signal-grid" id="signals"></div>
</div>
<div id="feed-wrap">
- <h2><span id="feed-title">Live feed</span><a class="helius-pill" href="https://helius.dev" target="_blank" rel="noopener" title="Real-time Solana data via Helius webhooks"><span class="helius-dot" aria-hidden="true"></span>Powered by Helius</a></h2>
+ <h2><span id="feed-title">Live feed</span><a id="helius-pill" class="helius-pill" href="https://helius.dev" target="_blank" rel="noopener" title="Real-time Solana data via Helius webhooks"><span class="helius-dot" aria-hidden="true"></span><span id="helius-count" class="helius-count">0</span>Powered by Helius</a></h2>
+ <button type="button" class="feed-jump" id="feed-jump" data-visible="false" aria-live="polite">↑ <span id="feed-jump-count">0</span> new</button>
<div id="feed"><div class="empty">Waiting for events…</div></div>
</div>
</aside>
@@ -282,19 +361,35 @@
</div>
<div class="pf-tabs" role="tablist">
<button class="pf-tab" role="tab" type="button" data-tab="defaults" aria-selected="true">Defaults<span class="badge" id="tab-count-defaults"></span></button>
+ <button class="pf-tab" role="tab" type="button" data-tab="recent" aria-selected="false">Recent<span class="badge" id="tab-count-recent"></span></button>
+ <button class="pf-tab" role="tab" type="button" data-tab="favorites" aria-selected="false">Favorites<span class="badge" id="tab-count-favorites"></span></button>
<button class="pf-tab" role="tab" type="button" data-tab="community" aria-selected="false">Community<span class="badge" id="tab-count-community"></span></button>
<button class="pf-tab" role="tab" type="button" data-tab="mine" aria-selected="false">My Agents<span class="badge" id="tab-count-mine"></span></button>
</div>
<div class="pf-toolbar">
- <input type="search" id="picker-search" placeholder="Search by name…" autocomplete="off" />
+ <input type="search" id="picker-search" placeholder="Search by name…" autocomplete="off" aria-label="Search avatars" />
<div class="custom-row">
- <input type="url" id="picker-custom-url" placeholder="https://…/avatar.glb" />
+ <input type="url" id="picker-custom-url" placeholder="https://…/avatar.glb" aria-label="Custom avatar URL" />
<button type="button" id="picker-custom-go">Use URL</button>
</div>
</div>
- <div class="pf-body" id="picker-body" role="tabpanel"></div>
+ <div class="pf-tags" id="picker-tags" role="group" aria-label="Filter by tag"></div>
+ <div class="pf-content">
+ <div class="pf-body" id="picker-body" role="tabpanel" aria-live="polite"></div>
+ <aside class="pf-preview" aria-label="Avatar preview">
+ <div class="pf-preview-stage" id="picker-preview-stage">
+ <div class="pf-preview-empty" id="picker-preview-empty" aria-hidden="true">◇</div>
+ </div>
+ <div class="pf-preview-meta" id="picker-preview-meta">
+ <div class="name" id="picker-preview-name">Hover or focus an avatar</div>
+ <div class="sub" id="picker-preview-sub">3D preview shown here</div>
+ <div class="actions" id="picker-preview-actions"></div>
+ </div>
+ </aside>
+ </div>
</div>
</div>
+ <div id="pf-toast-host" aria-live="polite" aria-atomic="true"></div>
<script>
const url = new URL(location.href);
const $ = (id) => document.getElementById(id);
@@ -321,6 +416,10 @@
{ url: '/avatars/default.glb', name: 'Default', sub: 'Generic agent', emoji: '🤖' },
];
+ // Tracks the picker selection independently of params.avatar so private
+ // 'mine' avatars (which resolve to a presigned URL on click) still
+ // highlight as selected when the picker reopens.
+ let selectedAvatarId = null;
const picker = {
modal: $('avatar-picker'),
body: $('picker-body'),
@@ -387,9 +486,14 @@
function useCustomUrl() {
const v = picker.customUrl.value.trim();
if (!v) return;
- try { new URL(v, location.href); } catch { alert('That does not look like a valid URL.'); return; }
+ let parsed;
+ try { parsed = new URL(v, location.href); } catch { alert('That does not look like a valid URL.'); return; }
+ const path = parsed.pathname.toLowerCase();
+ if (!/\.(glb|gltf|vrm)(\?|$)/.test(path + parsed.search)) {
+ if (!confirm('URL does not end in .glb / .gltf / .vrm. Try anyway?')) return;
+ }
picker.customUrl.value = '';
- selectAvatar({ url: v, name: 'Custom URL', sub: shortenUrl(v) });
+ selectAvatar({ url: parsed.href, name: 'Custom URL', sub: shortenUrl(parsed.href) });
}
function shortenUrl(u) {
@@ -528,7 +632,7 @@
const card = document.createElement('button');
card.type = 'button';
card.className = 'pf-card';
- const isSelected = a.url && a.url === params.avatar;
+ const isSelected = (a.id && a.id === selectedAvatarId) || (a.url && a.url === params.avatar);
if (isSelected) card.dataset.selected = 'true';
const thumbStyle = a.thumbnail_url ? `style="background-image:url('${attr(a.thumbnail_url)}')"` : '';
const fallback = a.thumbnail_url ? '' : (a.emoji || '◇');
@@ -563,6 +667,7 @@
}
}
params.avatar = resolvedUrl;
+ selectedAvatarId = a.id || null;
updateTriggerLabel(a);
syncURL();
mountAgent();
@@ -601,7 +706,13 @@
const dot = $('status-dot');
dot.className = 'dot ' + state;
$('status-label').textContent = label;
+ $('status-pill').dataset.state = state;
}
+ $('status-pill').addEventListener('click', () => {
+ if ($('status-pill').dataset.state === 'down' || $('status-pill').dataset.state === 'connecting') {
+ connectFeed();
+ }
+ });
function syncURL() {
const u = new URL(location.href);
@@ -1177,12 +1288,60 @@
</div>`;
}
- function pushEvent(html) {
- const feed = $('feed');
+ // Total live events received, surfaced on the Helius pill.
+ let liveEventCount = 0;
+ function bumpEventCount() {
+ liveEventCount++;
+ const pill = $('helius-pill');
+ pill.dataset.count = 'active';
+ $('helius-count').textContent = liveEventCount > 999 ? '999+' : String(liveEventCount);
+ }
+
+ // Pause-on-scroll: queue HTML strings when user has scrolled the feed
+ // down. They drain into the DOM when the user clicks the jump button or
+ // scrolls back to top.
+ const feedQueue = [];
+ const feedEl = () => $('feed');
+ const FEED_SCROLL_THRESHOLD = 24;
+ function feedIsAtTop() {
+ const f = feedEl();
+ return !f || f.scrollTop <= FEED_SCROLL_THRESHOLD;
+ }
+ function updateJumpButton() {
+ const btn = $('feed-jump');
+ if (!btn) return;
+ if (feedQueue.length > 0) {
+ $('feed-jump-count').textContent = feedQueue.length > 99 ? '99+' : String(feedQueue.length);
+ btn.dataset.visible = 'true';
+ } else {
+ btn.dataset.visible = 'false';
+ }
+ }
+ function appendNow(html) {
+ const feed = feedEl();
if (feed.querySelector('.empty')) feed.innerHTML = '';
feed.insertAdjacentHTML('afterbegin', html);
while (feed.children.length > MAX_EVENTS) feed.lastChild?.remove();
}
+ function pushEvent(html) {
+ bumpEventCount();
+ if (feedIsAtTop()) {
+ appendNow(html);
+ return;
+ }
+ feedQueue.unshift(html); // newest first
+ if (feedQueue.length > MAX_EVENTS) feedQueue.length = MAX_EVENTS;
+ updateJumpButton();
+ }
+ function flushQueued() {
+ while (feedQueue.length) appendNow(feedQueue.pop()); // pop oldest first so newest ends on top
+ updateJumpButton();
+ feedEl().scrollTo({ top: 0, behavior: 'smooth' });
+ }
+ $('feed-jump').addEventListener('click', flushQueued);
+ feedEl().addEventListener('scroll', () => {
+ if (feedIsAtTop() && feedQueue.length) flushQueued();
+ }, { passive: true });
function connectFeed() {
if (es) { try { es.close(); } catch {} }
@@ -1252,20 +1411,55 @@
});
let kindTimer;
- const onFilterChange = () => {
+ const onFilterChange = (delay = 200) => {
clearTimeout(kindTimer);
kindTimer = setTimeout(() => {
- params.kind = $('ctl-kind').value;
- params.minTier = $('ctl-tier').value;
- params.asset = $('ctl-asset').value.trim();
+ const newKind = $('ctl-kind').value;
+ const newTier = $('ctl-tier').value;
+ const newAsset = $('ctl-asset').value.trim();
+ const feedChanged = newKind !== params.kind || newTier !== params.minTier;
+ const agentChanged = newAsset !== params.asset;
+ params.kind = newKind;
+ params.minTier = newTier;
+ params.asset = newAsset;
syncURL();
- connectFeed();
- mountAgent();
- }, 200);
+ if (feedChanged) connectFeed();
+ if (agentChanged) mountAgent();
+ }, delay);
};
- $('ctl-kind').addEventListener('change', onFilterChange);
- $('ctl-tier').addEventListener('change', onFilterChange);
- $('ctl-asset').addEventListener('change', onFilterChange);
+ $('ctl-kind').addEventListener('change', () => onFilterChange(0));
+ $('ctl-tier').addEventListener('change', () => onFilterChange(0));
+ $('ctl-asset').addEventListener('input', () => onFilterChange(450));
+
+ // Share button — copies a URL with all current filters/avatar to clipboard.
+ $('ctl-share').addEventListener('click', async () => {
+ const btn = $('ctl-share');
+ const label = $('ctl-share-label');
+ const link = location.href;
+ try {
+ if (navigator.clipboard?.writeText) {
+ await navigator.clipboard.writeText(link);
+ } else {
+ const ta = document.createElement('textarea');
+ ta.value = link; ta.style.position = 'fixed'; ta.style.opacity = '0';
+ document.body.appendChild(ta); ta.select();
+ document.execCommand('copy'); ta.remove();
+ }
+ const prev = label.textContent;
+ label.textContent = 'Copied!';
+ btn.dataset.flash = 'true';
+ setTimeout(() => { label.textContent = prev; delete btn.dataset.flash; }, 1400);
+ } catch {
+ label.textContent = 'Press ⌘C';
+ setTimeout(() => { label.textContent = 'Share'; }, 1400);
+ }
+ });
+
+ // Mobile side-panel toggle
+ $('side-toggle').addEventListener('click', () => {
+ const open = document.body.classList.toggle('side-open');
+ $('side-toggle').setAttribute('aria-pressed', String(open));
+ });
// Initial load
connectFeed();
diff --git a/pump-dashboard.html b/pump-dashboard.html
index 8418d0626..90cabf8ca 100644
--- a/pump-dashboard.html
+++ b/pump-dashboard.html
@@ -838,8 +838,12 @@
// ═══════════════════════════════════════════════════════════════════════
const state = {
- apiUrl: localStorage.getItem('pumpbot-api-url') || 'http://localhost:3000',
- wsUrl: localStorage.getItem('pumpbot-ws-url') || 'ws://localhost:8080',
+ // Defaults wire to the 3D-Agent host that's serving this page so the
+ // dashboard works out of the box with /api/pump/* and the public PumpPortal
+ // launch feed. Users can still point at a remote PumpKit-style API via the
+ // Configuration tab.
+ apiUrl: localStorage.getItem('pumpbot-api-url') || (typeof location !== 'undefined' ? location.origin : ''),
+ wsUrl: localStorage.getItem('pumpbot-ws-url') || 'wss://pumpportal.fun/api/data',
apiKey: localStorage.getItem('pumpbot-api-key') || '',
rpcUrl: localStorage.getItem('pumpbot-rpc-url') || 'https://api.mainnet-beta.solana.com',
currentPage: 'dashboard',
@@ -1502,6 +1506,26 @@ async function scanToken() {
checks.pumpfun = { status: 'info', detail: 'Not a PumpFun token' };
}
+ // Enrich with /api/pump/curve (price + graduation progress) when it's a Pump token.
+ if (isPump) {
+ try {
+ const curveResp = await fetch(`/api/pump/curve?mint=${encodeURIComponent(mint)}`);
+ if (curveResp.ok) {
+ const curve = await curveResp.json();
+ if (curve.price?.priceSol) {
+ checks.spot_price = { status: 'info', detail: `${Number(curve.price.priceSol).toFixed(8)} SOL/token` };
+ }
+ if (curve.price?.marketCapSol) {
+ checks.market_cap = { status: 'info', detail: `${Number(curve.price.marketCapSol).toFixed(2)} SOL` };
+ }
+ if (curve.graduation?.progressBps != null) {
+ const pct = Number(curve.graduation.progressBps) / 100;
+ checks.graduation = { status: pct >= 80 ? 'warn' : 'pass', detail: `${pct.toFixed(1)}% to graduation` };
+ }
+ }
+ } catch { /* enrichment is optional */ }
+ }
+
const riskLevel = score >= 80 ? 'low' : score >= 50 ? 'medium' : 'high';
const riskColor = score >= 80 ? 'green' : score >= 50 ? 'yellow' : 'red';
@@ -1538,75 +1562,72 @@ async function getBuyQuote() {
const mint = document.getElementById('quote-buy-mint').value.trim();
const solAmount = parseFloat(document.getElementById('quote-buy-amount').value);
if (!mint) { toast('Enter token mint', 'error'); return; }
+ if (!Number.isFinite(solAmount) || solAmount <= 0) { toast('Enter a positive SOL amount', 'error'); return; }
const resultDiv = document.getElementById('quote-buy-result');
resultDiv.innerHTML = '<span style="color:#888">Calculating...</span>';
try {
- // Fetch bonding curve state from RPC
- const bcResp = await fetch(state.rpcUrl, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getProgramAccounts', params: [
- '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P',
- { filters: [{ memcmp: { offset: 30, bytes: mint } }], encoding: 'base64' },
- ] }),
- });
- const bcData = await bcResp.json();
-
- if (!bcData.result || bcData.result.length === 0) {
- resultDiv.innerHTML = '<span style="color:var(--red)">No bonding curve found — token may be graduated or invalid</span>';
+ const url = `/api/pump/quote-sdk?mint=${encodeURIComponent(mint)}&side=buy&amount=${solAmount}`;
+ const r = await fetch(url);
+ const data = await r.json();
+ if (!r.ok) {
+ resultDiv.innerHTML = `<span style="color:var(--red)">${escapeHtml(data.message || data.error || 'Quote failed')}</span>`;
return;
}
-
- const lamports = Math.floor(solAmount * 1e9);
+ const tokensOut = Number(data.output?.tokensUi || 0);
+ const impact = Number(data.priceImpactPct || 0);
+ const mc = data.marketContext;
resultDiv.innerHTML = `
<div style="padding:12px;background:var(--bg);border-radius:var(--radius);border:1px solid var(--border);">
- <div style="color:#888;font-size:11px">Estimated Output</div>
- <div style="color:var(--accent);font-size:18px;margin:4px 0">Bonding curve found ✅</div>
- <div style="color:#888;font-size:11px">Input: ${solAmount} SOL (${lamports.toLocaleString()} lamports)</div>
- <div style="color:#888;font-size:11px">Use the SDK for precise quote calculation</div>
+ <div style="color:#888;font-size:11px">You receive</div>
+ <div style="color:var(--accent);font-size:18px;margin:4px 0">${tokensOut.toLocaleString(undefined, { maximumFractionDigits: 2 })} tokens</div>
+ <div style="color:#888;font-size:11px">For ${solAmount} SOL · price impact <span style="color:${impact > 5 ? 'var(--yellow)' : 'var(--accent)'}">${impact.toFixed(2)}%</span></div>
+ ${mc ? `<div style="color:#666;font-size:11px;margin-top:6px">Spot: ${formatPriceContext(mc)}</div>` : ''}
</div>
`;
} catch (e) {
- resultDiv.innerHTML = `<span style="color:var(--red)">Error: ${escapeHtml(e.message || 'RPC failed')}</span>`;
+ resultDiv.innerHTML = `<span style="color:var(--red)">Error: ${escapeHtml(e.message || 'Quote failed')}</span>`;
}
}
+function formatPriceContext(p) {
+ const parts = [];
+ if (p.priceSol) parts.push(`${(Number(p.priceSol) || 0).toFixed(8)} SOL/token`);
+ if (p.marketCapSol) parts.push(`MC ${(Number(p.marketCapSol) || 0).toFixed(2)} SOL`);
+ return parts.join(' · ');
+}
+
async function getSellQuote() {
const mint = document.getElementById('quote-sell-mint').value.trim();
- const tokenAmount = parseInt(document.getElementById('quote-sell-amount').value);
+ const tokenAmount = parseFloat(document.getElementById('quote-sell-amount').value);
if (!mint) { toast('Enter token mint', 'error'); return; }
+ if (!Number.isFinite(tokenAmount) || tokenAmount <= 0) { toast('Enter a positive token amount', 'error'); return; }
const resultDiv = document.getElementById('quote-sell-result');
resultDiv.innerHTML = '<span style="color:#888">Calculating...</span>';
try {
- const bcResp = await fetch(state.rpcUrl, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getProgramAccounts', params: [
- '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P',
- { filters: [{ memcmp: { offset: 30, bytes: mint } }], encoding: 'base64' },
- ] }),
- });
- const bcData = await bcResp.json();
-
- if (!bcData.result || bcData.result.length === 0) {
- resultDiv.innerHTML = '<span style="color:var(--red)">No bonding curve found</span>';
+ const url = `/api/pump/quote-sdk?mint=${encodeURIComponent(mint)}&side=sell&amount=${tokenAmount}`;
+ const r = await fetch(url);
+ const data = await r.json();
+ if (!r.ok) {
+ resultDiv.innerHTML = `<span style="color:var(--red)">${escapeHtml(data.message || data.error || 'Quote failed')}</span>`;
return;
}
-
+ const sol = Number(data.output?.sol || 0);
+ const impact = Number(data.priceImpactPct || 0);
+ const mc = data.marketContext;
resultDiv.innerHTML = `
<div style="padding:12px;background:var(--bg);border-radius:var(--radius);border:1px solid var(--border);">
- <div style="color:#888;font-size:11px">Estimated Output</div>
- <div style="color:var(--accent);font-size:18px;margin:4px 0">Bonding curve found ✅</div>
- <div style="color:#888;font-size:11px">Input: ${tokenAmount.toLocaleString()} tokens</div>
- <div style="color:#888;font-size:11px">Use the SDK for precise quote calculation</div>
+ <div style="color:#888;font-size:11px">You receive</div>
+ <div style="color:var(--accent);font-size:18px;margin:4px 0">${sol.toFixed(6)} SOL</div>
+ <div style="color:#888;font-size:11px">For ${tokenAmount.toLocaleString()} tokens · price impact <span style="color:${impact > 5 ? 'var(--yellow)' : 'var(--accent)'}">${impact.toFixed(2)}%</span></div>
+ ${mc ? `<div style="color:#666;font-size:11px;margin-top:6px">Spot: ${formatPriceContext(mc)}</div>` : ''}
</div>
`;
} catch (e) {
- resultDiv.innerHTML = `<span style="color:var(--red)">Error: ${escapeHtml(e.message || 'RPC failed')}</span>`;
+ resultDiv.innerHTML = `<span style="color:var(--red)">Error: ${escapeHtml(e.message || 'Quote failed')}</span>`;
}
}
diff --git a/rider/src/components/multiplayer.js b/rider/src/components/multiplayer.js
index cc8efcfaf..3130841e7 100644
--- a/rider/src/components/multiplayer.js
+++ b/rider/src/components/multiplayer.js
@@ -1,28 +1,17 @@
const { MultiplayerClient } = require('../lib/multiplayer');
+const COUNTDOWN_MS = 5000;
+const SCORE_TICK_MS = 250;
+
/**
* Wires Firebase Realtime Database multiplayer rooms into the rider state.
*
- * Async-race model: host picks song, broadcasts, all players start loading
- * locally and run on their own clock. Live scores stream into a shared room
- * node so each player can see opponents' progress. Final scores compared on
- * victory screen.
- *
- * Events consumed (on a-scene):
- * mpcreate create room as host
- * mpjoin {code} join existing room
- * mpleave leave / cleanup
- * mpready {value} toggle ready flag in lobby
- * mpsetname {value} update display name
- * mprematch host: reset room to lobby
+ * Synchronized-race model: host picks song and presses PLAY. We broadcast
+ * `song` + `startAt = serverNow + 5s`. All clients (including host) display a
+ * countdown bound to wall-clock startAt. When countdown hits zero, every
+ * client triggers local playback. Loading happens during the countdown.
*
- * Events emitted (on a-scene):
- * mproomjoined {code, isHost}
- * mproomleft
- * mproomupdate {code, isHost, uid, status, song, startAt, players}
- * mpremotesongselect <songObj> non-host: host picked a song
- * mpremoteplaystart non-host: host pressed start
- * mperror {message}
+ * Live state streams via per-player nodes; opponent HUD shows rank + delta.
*/
AFRAME.registerComponent('multiplayer', {
schema: {
@@ -37,6 +26,10 @@ AFRAME.registerComponent('multiplayer', {
init: function () {
this.client = null;
this.lastRoom = null;
+ this.pendingStartAt = null;
+ this._scheduledFire = false;
+ this._lastCountdownLabel = '';
+ this._lastScoreTick = 0;
this.onCreate = this.onCreate.bind(this);
this.onJoin = this.onJoin.bind(this);
@@ -49,6 +42,7 @@ AFRAME.registerComponent('multiplayer', {
this.onSongComplete = this.onSongComplete.bind(this);
this.onRematch = this.onRematch.bind(this);
this.onRoomUpdate = this.onRoomUpdate.bind(this);
+ this.onShareLink = this.onShareLink.bind(this);
const sceneEl = this.el.sceneEl || this.el;
sceneEl.addEventListener('mpcreate', this.onCreate);
@@ -57,11 +51,11 @@ AFRAME.registerComponent('multiplayer', {
sceneEl.addEventListener('mpready', this.onReady);
sceneEl.addEventListener('mpsetname', this.onSetName);
sceneEl.addEventListener('mprematch', this.onRematch);
+ sceneEl.addEventListener('mpsharelink', this.onShareLink);
sceneEl.addEventListener('beathit', this.onBeatHit);
sceneEl.addEventListener('beatmiss', this.onBeatMiss);
sceneEl.addEventListener('beatwrong', this.onBeatMiss);
sceneEl.addEventListener('songcomplete', this.onSongComplete);
- // Capture phase so we read menuSelectedChallenge before the state handler clears it.
sceneEl.addEventListener('playbuttonclick', this.onPlayButtonClick, true);
const autoJoin = AFRAME.utils.getUrlParameter('mpjoin');
@@ -98,6 +92,7 @@ AFRAME.registerComponent('multiplayer', {
onCreate: async function () {
const c = this._ensureClient();
if (!c) return;
+ this.el.sceneEl.emit('mpconnecting', null, false);
try {
const code = await c.createRoom(this._name());
this.el.sceneEl.emit('mproomjoined', { code, isHost: true }, false);
@@ -111,6 +106,11 @@ AFRAME.registerComponent('multiplayer', {
const c = this._ensureClient();
if (!c) return;
const code = (evt.detail && evt.detail.code) || '';
+ if (!code || code.length < 4) {
+ this.el.sceneEl.emit('mperror', { message: 'Enter a 4-letter room code' }, false);
+ return;
+ }
+ this.el.sceneEl.emit('mpconnecting', null, false);
try {
await c.joinRoom(code, this._name());
this.el.sceneEl.emit('mproomjoined', { code: code.toUpperCase(), isHost: false }, false);
@@ -124,6 +124,7 @@ AFRAME.registerComponent('multiplayer', {
if (!this.client) return;
await this.client.leaveRoom();
this.lastRoom = null;
+ this.pendingStartAt = null;
this.el.sceneEl.emit('mproomleft', null, false);
},
@@ -134,38 +135,81 @@ AFRAME.registerComponent('multiplayer', {
onSetName: function (evt) {
if (!this.client) return;
- this.client.setName((evt.detail && evt.detail.value) || this._name());
+ const name = (evt.detail && (evt.detail.value || evt.detail)) || this._name();
+ localStorage.setItem('threewsusername', String(name).slice(0, 20));
+ this.client.setName(name);
},
onRematch: async function () {
if (!this.client) return;
+ this.pendingStartAt = null;
await this.client.resetForRematch();
},
+ onShareLink: function () {
+ if (!this.client || !this.client.roomCode) return;
+ const url = window.location.origin + window.location.pathname + '?mpjoin=' + this.client.roomCode;
+ const flashCopied = () => {
+ this.el.sceneEl.emit('mpsharelinkcopied', { url }, false);
+ setTimeout(() => this.el.sceneEl.emit('mpsharelinkcleared', null, false), 1500);
+ };
+ if (navigator.clipboard && navigator.clipboard.writeText) {
+ navigator.clipboard.writeText(url).then(flashCopied,
+ () => window.prompt('Share this link:', url));
+ } else {
+ window.prompt('Share this link:', url);
+ flashCopied();
+ }
+ },
+
/**
- * When local user presses play in MP mode and is host, broadcast to room.
- * Non-host's playbuttonclick is suppressed via state guard, so this is
- * effectively host-only.
+ * Host: capture in-MP playbuttonclick, broadcast song + countdown rather
+ * than letting the state handler immediately enter the play flow.
+ * Non-host: their play button is hidden, but defensively guard anyway.
*/
- onPlayButtonClick: function () {
+ onPlayButtonClick: function (evt) {
+ if (this._scheduledFire) return; // our own re-emit, let it through
if (!this.client || !this.client.roomRef) return;
const state = this.el.sceneEl.systems.state.state;
if (!state.multiplayer || !state.multiplayer.active) return;
- if (!this.client.isHost) return;
+
+ if (!this.client.isHost) {
+ evt.stopImmediatePropagation();
+ evt.preventDefault();
+ return;
+ }
+ if (state.multiplayer.players.length < 2) {
+ evt.stopImmediatePropagation();
+ evt.preventDefault();
+ this.el.sceneEl.emit('mperror', { message: 'Need at least 2 players' }, false);
+ return;
+ }
+
+ // Stop the state handler — countdown will trigger play later.
+ evt.stopImmediatePropagation();
+ evt.preventDefault();
+
const challenge = Object.assign({}, state.menuSelectedChallenge);
this.client.broadcastSong(challenge)
- .then(() => this.client.startSong())
- .catch(err => console.error('[multiplayer] host start failed', err));
+ .then(() => this.client.startSong(COUNTDOWN_MS))
+ .catch(err => {
+ console.error('[multiplayer] host start failed', err);
+ this.el.sceneEl.emit('mperror', { message: 'Failed to start song' }, false);
+ });
},
onBeatHit: function () {
- if (!this.client || !this.client.roomRef) return;
- const state = this.el.sceneEl.systems.state.state;
- this.client.pushScore(state.score);
+ this._maybePushScore();
},
-
onBeatMiss: function () {
+ this._maybePushScore();
+ },
+
+ _maybePushScore: function () {
if (!this.client || !this.client.roomRef) return;
+ const now = performance.now();
+ if (now - this._lastScoreTick < SCORE_TICK_MS) return;
+ this._lastScoreTick = now;
const state = this.el.sceneEl.systems.state.state;
this.client.pushScore(state.score);
},
@@ -178,10 +222,12 @@ AFRAME.registerComponent('multiplayer', {
onRoomUpdate: function (room) {
if (!room) {
+ this.pendingStartAt = null;
this.el.sceneEl.emit('mproomleft', null, false);
return;
}
const sceneEl = this.el.sceneEl;
+ const myUid = this.client.uid;
const playerEntries = Object.keys(room.players || {}).map(uid => ({
uid,
...room.players[uid]
@@ -189,15 +235,16 @@ AFRAME.registerComponent('multiplayer', {
sceneEl.emit('mproomupdate', {
code: this.client.roomCode,
- isHost: room.host === this.client.uid,
- uid: this.client.uid,
+ isHost: room.host === myUid,
+ hostUid: room.host,
+ uid: myUid,
status: room.status,
song: room.song,
startAt: room.startAt,
players: playerEntries
}, false);
- // Non-host: when host broadcasts a new song, surface it.
+ // Non-host: when host broadcasts a new song, mirror selection.
if (!this.client.isHost && room.song && room.song.id) {
const prevSongId = this.lastRoom && this.lastRoom.song && this.lastRoom.song.id;
if (room.song.id !== prevSongId) {
@@ -205,14 +252,68 @@ AFRAME.registerComponent('multiplayer', {
}
}
- // Non-host: status flips to playing → trigger local play.
- if (!this.client.isHost && room.status === 'playing') {
- const prevStatus = this.lastRoom && this.lastRoom.status;
- if (prevStatus !== 'playing') {
- sceneEl.emit('mpremoteplaystart', null, false);
+ // Sync start: any client with a fresh startAt + status==playing arms tick.
+ if (room.status === 'playing' && room.startAt) {
+ const prevStart = this.lastRoom && this.lastRoom.startAt;
+ if (room.startAt !== prevStart) {
+ this.pendingStartAt = room.startAt;
}
}
+ // Rematch: status returned to lobby — clear any pending timer.
+ if (room.status === 'lobby') {
+ this.pendingStartAt = null;
+ }
+
this.lastRoom = room;
+ },
+
+ /**
+ * Drive the countdown text and trigger the synchronized fire.
+ */
+ tick: function () {
+ if (!this.client) return;
+ if (this.pendingStartAt) {
+ const delta = this.pendingStartAt - this.client.serverNow();
+ const secs = Math.max(0, Math.ceil(delta / 1000));
+ const label = secs > 0 ? ('STARTING IN ' + secs) : 'GO!';
+ if (label !== this._lastCountdownLabel) {
+ this._lastCountdownLabel = label;
+ this.el.sceneEl.emit('mpcountdown', { value: label, secs, active: true }, false);
+ }
+ if (delta <= 0) {
+ const startAt = this.pendingStartAt;
+ this.pendingStartAt = null;
+ this._fireLocalStart();
+ // Hold "GO!" briefly then clear.
+ setTimeout(() => {
+ this.el.sceneEl.emit('mpcountdown', { value: '', secs: 0, active: false }, false);
+ this._lastCountdownLabel = '';
+ }, 600);
+ // Mark we already fired for this startAt.
+ this._lastFiredStartAt = startAt;
+ }
+ }
+ },
+
+ _fireLocalStart: function () {
+ const state = this.el.sceneEl.systems.state.state;
+ if (this.client.isHost) {
+ // Re-emit playbuttonclick; our capture-phase handler will let it through
+ // because _scheduledFire is set.
+ this._scheduledFire = true;
+ try {
+ this.el.sceneEl.emit('playbuttonclick', null, false);
+ } finally {
+ this._scheduledFire = false;
+ }
+ } else {
+ // Non-host: needs a populated menuSelectedChallenge from the room song.
+ if (!state.menuSelectedChallenge.id) {
+ console.warn('[multiplayer] non-host fire without song selected');
+ return;
+ }
+ this.el.sceneEl.emit('mpremoteplaystart', null, false);
+ }
}
});
diff --git a/rider/src/lib/multiplayer.js b/rider/src/lib/multiplayer.js
index 50ac532f6..22fb16e7a 100644
--- a/rider/src/lib/multiplayer.js
+++ b/rider/src/lib/multiplayer.js
@@ -212,9 +212,9 @@ class MultiplayerClient {
/**
* Host: schedule synchronized start. All clients begin the song at startAt.
*/
- async startSong () {
+ async startSong (delayMs) {
if (!this.isHost || !this.roomRef) return;
- const startAt = this.serverNow() + START_DELAY_MS;
+ const startAt = this.serverNow() + (typeof delayMs === 'number' ? delayMs : START_DELAY_MS);
await this.roomRef.update({ status: 'playing', startAt });
return startAt;
}
diff --git a/rider/src/state/index.js b/rider/src/state/index.js
index e13b1b598..ec4b3d4df 100644
--- a/rider/src/state/index.js
+++ b/rider/src/state/index.js
@@ -119,21 +119,43 @@ AFRAME.registerState({
mainMenuActive: false,
menuActive: SKIP_INTRO, // Main menu active.
multiplayer: {
- active: false, // In MP flow at all.
- lobbyOpen: false, // Lobby panel visible.
+ active: false,
+ lobbyOpen: false,
roomCode: '',
+ shareUrl: '',
+ shareCopied: false,
isHost: false,
uid: '',
status: 'idle', // idle | connecting | lobby | playing | finished
- players: [], // [{uid, name, score, combo, accuracy, ready, finished, finalScore, rank}]
+ players: [],
playerCount: 0,
readyCount: 0,
everyoneReady: false,
- opponentText: '', // Pre-rendered HUD text for non-self players.
+ myReady: false,
+ myRank: 0,
+ myRankText: '',
+ leaderName: '',
+ leaderScore: 0,
+ scoreDelta: 0,
+ scoreDeltaText: '',
+ opponentText: '',
opponentScores: '',
hostName: '',
+ hostUid: '',
+ songName: '',
lastError: '',
- joinCodeInput: ''
+ joinCodeInput: '',
+ countdownText: '',
+ countdownActive: false,
+ // Pre-rendered fixed-slot row strings for the lobby (4 slots).
+ row0Name: '', row0Score: '', row0Visible: false, row0IsMe: false, row0IsHost: false, row0Ready: false,
+ row1Name: '', row1Score: '', row1Visible: false, row1IsMe: false, row1IsHost: false, row1Ready: false,
+ row2Name: '', row2Score: '', row2Visible: false, row2IsMe: false, row2IsHost: false, row2Ready: false,
+ row3Name: '', row3Score: '', row3Visible: false, row3IsMe: false, row3IsHost: false, row3Ready: false,
+ // Sorted results (winner first) for victory screen.
+ resultsText: '',
+ resultsScores: '',
+ winnerName: ''
},
menuDifficulties: [],
menuDifficultiesIds: [],
@@ -676,41 +698,129 @@ AFRAME.registerState({
},
/**
- * Snapshot of room state from network.
+ * Snapshot of room state from network. Computes ranking, per-row strings,
+ * sorted results, leader delta — anything bound to UI.
*/
mproomupdate: (state, payload) => {
state.multiplayer.uid = payload.uid;
state.multiplayer.isHost = !!payload.isHost;
+ state.multiplayer.hostUid = payload.hostUid || '';
state.multiplayer.status = payload.status || state.multiplayer.status;
+ state.multiplayer.songName = (payload.song && payload.song.songName) || '';
state.multiplayer.players.length = 0;
state.multiplayer.players.__dirty = true;
+ const players = payload.players.slice();
+ // Sort by score desc for ranking.
+ const ranked = players.slice().sort((a, b) => (b.score | 0) - (a.score | 0));
+ const rankByUid = {};
+ ranked.forEach((p, i) => { rankByUid[p.uid] = i + 1; });
+
let readyCount = 0;
- let opponentText = '';
- let opponentScores = '';
+ let myReady = false;
+ let myRank = 0;
+ let leader = ranked[0] || null;
let hostName = '';
- for (let i = 0; i < payload.players.length; i++) {
- const p = payload.players[i];
+ let opponentText = '';
+ let opponentScores = '';
+ let resultsText = '';
+ let resultsScores = '';
+
+ // Lobby ordering = joinedAt asc (preserves original sort).
+ // Results ordering = score desc (use ranked list).
+ // For HUD we want self at top + others by rank desc.
+ for (let i = 0; i < players.length; i++) {
+ const p = players[i];
state.multiplayer.players.push(p);
if (p.ready) readyCount++;
+ if (p.uid === payload.uid) myReady = !!p.ready;
+ if (p.uid === payload.hostUid) hostName = p.name;
+ }
+ myRank = rankByUid[payload.uid] || 0;
+
+ for (let i = 0; i < ranked.length; i++) {
+ const p = ranked[i];
+ const accStr = Math.round(p.accuracy || 0) + '%';
+ const youTag = p.uid === payload.uid ? ' (YOU)' : '';
+ const finTag = p.finished ? ' ✓' : '';
if (p.uid !== payload.uid) {
- const tag = p.finished ? ' DONE' : '';
- opponentText += `${truncate(p.name, 14)} (${Math.round(p.accuracy || 0)}%)${tag}\n`;
+ opponentText += `#${i + 1} ${truncate(p.name, 12)} ${accStr}${finTag}\n`;
opponentScores += `${p.score | 0}\n`;
}
- if (payload.song && p.uid === (payload.hostUid || '')) hostName = p.name;
+ resultsText += `#${i + 1} ${truncate(p.name, 14)}${youTag} ${accStr}\n`;
+ resultsScores += `${p.score | 0}\n`;
+ }
+
+ // Per-row strings (lobby uses joinedAt order so rows are stable as
+ // players join/leave).
+ for (let i = 0; i < 4; i++) {
+ const p = players[i];
+ const rowKey = 'row' + i;
+ if (!p) {
+ state.multiplayer[rowKey + 'Name'] = '';
+ state.multiplayer[rowKey + 'Score'] = '';
+ state.multiplayer[rowKey + 'Visible'] = false;
+ state.multiplayer[rowKey + 'IsMe'] = false;
+ state.multiplayer[rowKey + 'IsHost'] = false;
+ state.multiplayer[rowKey + 'Ready'] = false;
+ continue;
+ }
+ const isMe = p.uid === payload.uid;
+ const isHost = p.uid === payload.hostUid;
+ const tag = (isHost ? '★ ' : '') + truncate(p.name, 14) + (isMe ? ' (YOU)' : '');
+ const right = state.multiplayer.status === 'lobby'
+ ? (p.ready ? 'READY' : '...')
+ : ((p.score | 0) + ' ' + Math.round(p.accuracy || 0) + '%' + (p.finished ? ' ✓' : ''));
+ state.multiplayer[rowKey + 'Name'] = tag;
+ state.multiplayer[rowKey + 'Score'] = right;
+ state.multiplayer[rowKey + 'Visible'] = true;
+ state.multiplayer[rowKey + 'IsMe'] = isMe;
+ state.multiplayer[rowKey + 'IsHost'] = isHost;
+ state.multiplayer[rowKey + 'Ready'] = !!p.ready;
}
- state.multiplayer.playerCount = payload.players.length;
+ state.multiplayer.playerCount = players.length;
state.multiplayer.readyCount = readyCount;
state.multiplayer.everyoneReady =
- payload.players.length >= 2 && readyCount === payload.players.length;
+ players.length >= 2 && readyCount === players.length;
+ state.multiplayer.myReady = myReady;
+ state.multiplayer.myRank = myRank;
+ state.multiplayer.myRankText =
+ myRank ? ('#' + myRank + ' / ' + players.length) : '';
+ state.multiplayer.leaderName = leader ? leader.name : '';
+ state.multiplayer.leaderScore = leader ? (leader.score | 0) : 0;
+ const myEntry = players.find(p => p.uid === payload.uid);
+ const myScore = myEntry ? (myEntry.score | 0) : 0;
+ const delta = myScore - (leader ? (leader.score | 0) : 0);
+ state.multiplayer.scoreDelta = delta;
+ state.multiplayer.scoreDeltaText =
+ leader && leader.uid !== payload.uid
+ ? (delta >= 0 ? ('+' + delta) : String(delta)) + ' vs leader'
+ : (leader && leader.uid === payload.uid && players.length > 1
+ ? 'LEADING' : '');
state.multiplayer.opponentText = opponentText;
state.multiplayer.opponentScores = opponentScores;
+ state.multiplayer.resultsText = resultsText;
+ state.multiplayer.resultsScores = resultsScores;
+ state.multiplayer.winnerName =
+ ranked.length && ranked[0].score > 0 ? ranked[0].name : '';
state.multiplayer.hostName = hostName;
},
+ mpcountdown: (state, payload) => {
+ state.multiplayer.countdownText = (payload && payload.value) || '';
+ state.multiplayer.countdownActive = !!(payload && payload.active);
+ },
+
+ mpsharelinkcopied: state => {
+ state.multiplayer.shareCopied = true;
+ },
+
+ mpsharelinkcleared: state => {
+ state.multiplayer.shareCopied = false;
+ },
+
/**
* Non-host: host has selected a song. Mirror it into menuSelectedChallenge
* so zip-loader will fetch it on play.
@@ -1023,30 +1133,56 @@ AFRAME.registerState({
state.inVR &&
(state.isPlaying || state.isPaused);
- // MP gating — non-host cannot drive song selection or playback.
state.mpActive = !!state.multiplayer.active;
+ state.mpCanStart =
+ !state.multiplayer.active ||
+ (state.multiplayer.isHost && state.multiplayer.players.length >= 2);
state.mpHostControl = !state.multiplayer.active || state.multiplayer.isHost;
state.mpLobbyVisible =
state.multiplayer.lobbyOpen && state.menuActive && !state.isMenuOpening;
state.mpHudVisible =
state.multiplayer.active &&
state.multiplayer.players.length > 1 &&
- (state.isPlaying || state.isPaused);
+ (state.isPlaying || state.isPaused || state.isLoading);
state.mpResultsVisible =
state.multiplayer.active &&
state.isVictory &&
state.multiplayer.players.length > 1;
+ state.mpInRoom = !!state.multiplayer.roomCode;
+ state.mpInLobbyPhase =
+ state.mpInRoom && state.multiplayer.status === 'lobby';
+ state.mpCountdownVisible = state.multiplayer.countdownActive;
state.mpRoomCodeText = state.multiplayer.roomCode
? 'ROOM ' + state.multiplayer.roomCode
: '';
+ state.mpShareButtonText = state.multiplayer.shareCopied
+ ? 'LINK COPIED'
+ : 'COPY SHARE LINK';
state.mpStatusText = (() => {
if (state.multiplayer.lastError) return state.multiplayer.lastError;
if (state.multiplayer.status === 'connecting') return 'Connecting...';
- if (state.multiplayer.status === 'idle') return 'Create or join a room.';
- if (state.multiplayer.players.length < 2) return 'Waiting for another player...';
- if (state.multiplayer.isHost) return 'Pick a song and press PLAY.';
- return 'Waiting for host to pick a song...';
+ if (state.multiplayer.status === 'idle') return 'Create a room or paste a code.';
+ if (state.multiplayer.status === 'finished') return 'Round over.';
+ if (state.multiplayer.players.length < 2) {
+ return state.multiplayer.isHost
+ ? 'Share the room code below — waiting for a friend.'
+ : 'Waiting for another player...';
+ }
+ if (state.multiplayer.isHost) {
+ return state.multiplayer.songName
+ ? 'Press PLAY to start "' + state.multiplayer.songName + '".'
+ : 'Pick a song from the menu, then press PLAY.';
+ }
+ return state.multiplayer.songName
+ ? 'Host queued "' + state.multiplayer.songName + '". Get ready.'
+ : 'Waiting for host to pick a song...';
})();
+ state.mpWinnerBanner = state.multiplayer.winnerName
+ ? (state.multiplayer.winnerName === (
+ (state.multiplayer.players.find(p => p.uid === state.multiplayer.uid) || {}).name)
+ ? 'YOU WON!'
+ : state.multiplayer.winnerName.toUpperCase() + ' WINS')
+ : '';
}
});
diff --git a/rider/src/templates/menu.html b/rider/src/templates/menu.html
index c50afd9bd..3ca816f48 100644
--- a/rider/src/templates/menu.html
+++ b/rider/src/templates/menu.html
@@ -149,7 +149,7 @@
</a-entity>
<a-entity id="playButton"
- bind__visible-raycastable="menuActive && !!menuSelectedChallenge.id && !genreMenuOpen && !difficultyFilterMenuOpen && !isIOS && !hasSongLoadError && mpHostControl"
+ bind__visible-raycastable="menuActive && !!menuSelectedChallenge.id && !genreMenuOpen && !difficultyFilterMenuOpen && !isIOS && !hasSongLoadError && mpHostControl && mpCanStart"
geometry="primitive: plane; width: 0.7; height: 0.25"
play-sound="event: mouseenter; sound: #hoverSound; volume: 0.03"
play-sound__click="event: click; sound: #confirmSound; volume: 0.25" position="0 -0.561 0"
diff --git a/rider/src/templates/multiplayerLobby.html b/rider/src/templates/multiplayerLobby.html
index e160089f6..c92201f7b 100644
--- a/rider/src/templates/multiplayerLobby.html
+++ b/rider/src/templates/multiplayerLobby.html
@@ -1,223 +1,312 @@
<!--
- Multiplayer lobby panel. Visible while menuActive and multiplayer.lobbyOpen.
- Sits in front of the main menu so users can still pick songs (host) while
- seeing the room status.
+ Multiplayer lobby panel + in-game HUD + victory results overlay.
-->
+
+{% macro mpRow (i) %}
+<a-entity position="0 {{ -i * 0.13 }} 0" bind__visible="multiplayer.row{{i}}Visible">
+ <a-entity
+ geometry="primitive: plane; width: 1.45; height: 0.115"
+ bind__material="opacity: multiplayer.row{{i}}IsMe ? 0.18 : 0.06"
+ material="shader: flat; color: #ffffff; transparent: true"
+ position="0 0 -0.005"></a-entity>
+ <a-entity
+ mixin="font"
+ bind__text="value: multiplayer.row{{i}}Name; color: multiplayer.row{{i}}IsMe ? colorSecondaryBright : '#ffffff'"
+ text="align: left; width: 1.4; lineHeight: 55"
+ render-order="menutext"
+ position="-0.62 0 0"></a-entity>
+ <a-entity
+ mixin="font"
+ bind__text="value: multiplayer.row{{i}}Score; color: multiplayer.row{{i}}Ready ? '#5dff80' : '#ffffff'"
+ text="align: right; width: 1.4; lineHeight: 55"
+ render-order="menutext"
+ position="0.62 0 0"></a-entity>
+</a-entity>
+{% endmacro %}
+
<a-entity
id="multiplayerLobby"
bind__visible="mpLobbyVisible"
position="0 1.55 -1.4"
- rotation="0 0 0"
render-order="menu">
- <!-- Background panel -->
+ <!-- Background -->
<a-entity
- id="mpLobbyBg"
bind-toggle__raycastable="mpLobbyVisible"
- geometry="primitive: plane; width: 1.6; height: 1.05"
- material="shader: panelShader; brightness: 0.18; ratio: 1.52; borderWidth: 0.005; borderRadius: 0.04"
+ geometry="primitive: plane; width: 1.7; height: 1.35"
+ material="shader: panelShader; brightness: 0.18; ratio: 1.26; borderWidth: 0.005; borderRadius: 0.04"
render-order="menu"
position="0 0 -0.02"></a-entity>
<!-- Title -->
<a-entity
mixin="font"
- text="align: center; value: MULTIPLAYER; width: 1.4; lineHeight: 50; color: #FFF"
+ text="align: center; value: MULTIPLAYER; width: 1.5; lineHeight: 50; color: #FFF"
render-order="menutext"
- position="0 0.45 0"></a-entity>
+ position="0 0.60 0"></a-entity>
- <!-- Room code display -->
+ <!-- Room code -->
<a-entity
mixin="font"
bind__text="value: mpRoomCodeText; color: colorSecondaryBright"
- text="align: center; width: 1.4; lineHeight: 80"
+ text="align: center; width: 1.5; lineHeight: 80"
render-order="menutext"
- position="0 0.30 0"></a-entity>
+ position="0 0.46 0"></a-entity>
- <!-- Status / instructions line -->
+ <!-- Status / instructions -->
<a-entity
mixin="font"
bind__text="value: mpStatusText; color: colorPrimary"
- text="align: center; width: 1.4; wrapCount: 36"
+ text="align: center; width: 1.5; wrapCount: 38; lineHeight: 50"
render-order="menutext"
- position="0 0.18 0"></a-entity>
+ position="0 0.34 0"></a-entity>
- <!-- Player list -->
- <a-entity position="0 -0.05 0">
- <a-entity
- mixin="font"
- text="align: left; value: PLAYERS; width: 1.0; lineHeight: 60; color: #888"
- render-order="menutext"
- position="-0.55 0.10 0"></a-entity>
- <a-entity
- mixin="font"
- bind__text="value: multiplayer.opponentText || 'You'"
- text="align: left; width: 1.0; lineHeight: 50; color: #FFF"
- render-order="menutext"
- position="-0.55 0.00 0"></a-entity>
- <a-entity
- mixin="font"
- bind__text="value: multiplayer.opponentScores"
- text="align: right; width: 1.0; lineHeight: 50; color: #FFF"
- render-order="menutext"
- position="0.55 0.00 0"></a-entity>
+ <!-- Player rows -->
+ <a-entity position="0 0.13 0">
+ {{ mpRow(0) }}
+ {{ mpRow(1) }}
+ {{ mpRow(2) }}
+ {{ mpRow(3) }}
</a-entity>
- <!-- Action buttons row (idle: create / join input; in-room: leave) -->
- <a-entity position="0 -0.36 0">
-
- <!-- CREATE button: visible when no room joined -->
+ <!-- Action button row 1: idle (no room) -->
+ <a-entity position="0 -0.42 0">
<a-entity
- class="mpBtn"
- bind__visible="!multiplayer.roomCode"
- bind-toggle__raycastable="mpLobbyVisible && !multiplayer.roomCode"
+ bind__visible="!mpInRoom"
+ bind-toggle__raycastable="mpLobbyVisible && !mpInRoom"
position="-0.40 0 0"
mixin="modeBackgroundHover"
- geometry="primitive: plane; width: 0.65; height: 0.18"
- material="shader: panelShader; brightness: 0.25; ratio: 3.6; borderWidth: 0.004"
+ geometry="primitive: plane; width: 0.65; height: 0.16"
+ material="shader: panelShader; brightness: 0.30; ratio: 4.0; borderWidth: 0.004"
proxy-event="event: click; as: mpcreate; to: a-scene"
play-sound__click="event: click; sound: #confirmSound; volume: 0.1">
<a-entity
mixin="font"
text="align: center; value: CREATE ROOM; width: 0.6; lineHeight: 60; color: #FFF"
- render-order="menutext"
position="0 0 0.001"></a-entity>
</a-entity>
- <!-- JOIN button: visible when no room joined; uses last typed code -->
<a-entity
- class="mpBtn"
- bind__visible="!multiplayer.roomCode"
- bind-toggle__raycastable="mpLobbyVisible && !multiplayer.roomCode"
+ bind__visible="!mpInRoom"
+ bind-toggle__raycastable="mpLobbyVisible && !mpInRoom"
position="0.40 0 0"
mixin="modeBackgroundHover"
- geometry="primitive: plane; width: 0.65; height: 0.18"
- material="shader: panelShader; brightness: 0.25; ratio: 3.6; borderWidth: 0.004"
+ geometry="primitive: plane; width: 0.65; height: 0.16"
+ material="shader: panelShader; brightness: 0.30; ratio: 4.0; borderWidth: 0.004"
multiplayer-join-button
play-sound__click="event: click; sound: #confirmSound; volume: 0.1">
<a-entity
mixin="font"
bind__text="value: multiplayer.joinCodeInput ? ('JOIN ' + multiplayer.joinCodeInput) : 'JOIN ROOM'"
text="align: center; width: 0.6; lineHeight: 60; color: #FFF"
- render-order="menutext"
position="0 0 0.001"></a-entity>
</a-entity>
- <!-- READY toggle when in lobby -->
+ <!-- READY (in lobby phase) -->
<a-entity
- class="mpBtn"
- bind__visible="!!multiplayer.roomCode && multiplayer.status === 'lobby'"
- bind-toggle__raycastable="!!multiplayer.roomCode && multiplayer.status === 'lobby'"
- position="-0.40 0 0"
+ bind__visible="mpInLobbyPhase"
+ bind-toggle__raycastable="mpInLobbyPhase"
+ position="-0.55 0 0"
mixin="modeBackgroundHover"
- geometry="primitive: plane; width: 0.65; height: 0.18"
- material="shader: panelShader; brightness: 0.25; ratio: 3.6; borderWidth: 0.004"
+ geometry="primitive: plane; width: 0.50; height: 0.16"
+ bind__material="brightness: multiplayer.myReady ? 0.50 : 0.20"
+ material="shader: panelShader; ratio: 3.1; borderWidth: 0.004"
multiplayer-ready-button
play-sound__click="event: click; sound: #confirmSound; volume: 0.1">
<a-entity
mixin="font"
- text="align: center; value: READY; width: 0.6; lineHeight: 60; color: #FFF"
- render-order="menutext"
+ bind__text="value: multiplayer.myReady ? 'UNREADY' : 'READY'; color: multiplayer.myReady ? '#5dff80' : '#FFF'"
+ text="align: center; width: 0.5; lineHeight: 60"
position="0 0 0.001"></a-entity>
</a-entity>
- <!-- LEAVE: visible when in a room -->
+ <!-- Share link (in room) -->
<a-entity
- class="mpBtn"
- bind__visible="!!multiplayer.roomCode"
- bind-toggle__raycastable="!!multiplayer.roomCode"
- position="0.40 0 0"
+ bind__visible="mpInRoom"
+ bind-toggle__raycastable="mpInRoom"
+ position="0 0 0"
mixin="modeBackgroundHover"
- geometry="primitive: plane; width: 0.65; height: 0.18"
- material="shader: panelShader; brightness: 0.18; ratio: 3.6; borderWidth: 0.004"
- proxy-event="event: click; as: mpleave; to: a-scene"
+ geometry="primitive: plane; width: 0.55; height: 0.16"
+ material="shader: panelShader; brightness: 0.20; ratio: 3.4; borderWidth: 0.004"
+ proxy-event="event: click; as: mpsharelink; to: a-scene"
play-sound__click="event: click; sound: #confirmSound; volume: 0.1">
<a-entity
mixin="font"
- text="align: center; value: LEAVE; width: 0.6; lineHeight: 60; color: #888"
- render-order="menutext"
+ bind__text="value: mpShareButtonText; color: multiplayer.shareCopied ? '#5dff80' : '#FFF'"
+ text="align: center; width: 0.55; lineHeight: 65"
position="0 0 0.001"></a-entity>
</a-entity>
+ <!-- Name editor (in room) -->
+ <a-entity
+ bind__visible="mpInRoom"
+ bind-toggle__raycastable="mpInRoom"
+ position="0.55 0 0"
+ mixin="modeBackgroundHover"
+ geometry="primitive: plane; width: 0.50; height: 0.16"
+ material="shader: panelShader; brightness: 0.20; ratio: 3.1; borderWidth: 0.004"
+ multiplayer-name-button
+ play-sound__click="event: click; sound: #confirmSound; volume: 0.1">
+ <a-entity
+ mixin="font"
+ text="align: center; value: SET NAME; width: 0.5; lineHeight: 60; color: #FFF"
+ position="0 0 0.001"></a-entity>
+ </a-entity>
</a-entity>
- <!-- Close MP mode entirely -->
- <a-entity
- class="mpBtn"
- bind__visible="mpLobbyVisible"
- bind-toggle__raycastable="mpLobbyVisible && !multiplayer.roomCode"
- position="0 -0.50 0"
- proxy-event="event: click; as: mpclose; to: a-scene">
+ <!-- Action button row 2: leave + back -->
+ <a-entity position="0 -0.59 0">
<a-entity
- mixin="font"
- text="align: center; value: < back to modes; width: 1.2; lineHeight: 60; color: #555"
- render-order="menutext"></a-entity>
+ bind__visible="mpInRoom"
+ bind-toggle__raycastable="mpInRoom"
+ position="0 0 0"
+ geometry="primitive: plane; width: 0.55; height: 0.13"
+ material="shader: panelShader; brightness: 0.10; ratio: 4.2; borderWidth: 0.003"
+ proxy-event="event: click; as: mpleave; to: a-scene">
+ <a-entity
+ mixin="font"
+ text="align: center; value: LEAVE ROOM; width: 0.55; lineHeight: 70; color: #888"
+ position="0 0 0.001"></a-entity>
+ </a-entity>
+ <a-entity
+ bind__visible="!mpInRoom"
+ bind-toggle__raycastable="mpLobbyVisible && !mpInRoom"
+ position="0 0 0"
+ proxy-event="event: click; as: mpclose; to: a-scene">
+ <a-entity
+ mixin="font"
+ text="align: center; value: < back to modes; width: 1.2; lineHeight: 60; color: #555"
+ render-order="menutext"></a-entity>
+ </a-entity>
</a-entity>
</a-entity>
-<!-- In-game opponent HUD: small panel on the side showing live opponent scores. -->
+<!-- ===================== IN-GAME COUNTDOWN OVERLAY ===================== -->
+<a-entity
+ id="mpCountdown"
+ bind__visible="mpCountdownVisible"
+ position="0 1.7 -2"
+ render-order="menu">
+ <a-entity
+ geometry="primitive: plane; width: 1.4; height: 0.4"
+ material="shader: panelShader; brightness: 0.30; ratio: 3.5; borderWidth: 0.005"
+ position="0 0 -0.01"></a-entity>
+ <a-entity
+ mixin="font"
+ bind__text="value: multiplayer.countdownText; color: colorSecondaryBright"
+ text="align: center; width: 1.3; lineHeight: 30"
+ render-order="menutext"></a-entity>
+</a-entity>
+
+
+<!-- ===================== IN-GAME OPPONENT HUD ===================== -->
<a-entity
id="mpHud"
bind__visible="mpHudVisible"
- position="-1.35 1.55 -1.0"
- rotation="0 30 0"
+ position="-1.45 1.65 -1.0"
+ rotation="0 35 0"
render-order="menu">
<a-entity
- geometry="primitive: plane; width: 0.7; height: 0.45"
- material="shader: panelShader; brightness: 0.1; ratio: 1.55; borderWidth: 0.002"
+ geometry="primitive: plane; width: 0.85; height: 0.55"
+ material="shader: panelShader; brightness: 0.10; ratio: 1.55; borderWidth: 0.002"
position="0 0 -0.01"></a-entity>
<a-entity
mixin="font"
- text="align: left; value: OPPONENTS; width: 0.6; lineHeight: 70; color: #888"
- position="-0.27 0.18 0"></a-entity>
+ bind__text="value: 'RANK ' + multiplayer.myRankText; color: colorSecondaryBright"
+ text="align: left; width: 0.75; lineHeight: 60"
+ position="-0.34 0.22 0"></a-entity>
+ <a-entity
+ mixin="font"
+ bind__text="value: multiplayer.scoreDeltaText; color: multiplayer.scoreDelta >= 0 ? '#5dff80' : '#ff8080'"
+ text="align: right; width: 0.75; lineHeight: 65"
+ position="0.34 0.22 0"></a-entity>
+ <a-entity
+ mixin="font"
+ text="align: left; value: OPPONENTS; width: 0.75; lineHeight: 80; color: #888"
+ position="-0.34 0.10 0"></a-entity>
<a-entity
mixin="font"
bind__text="value: multiplayer.opponentText; color: colorPrimary"
- text="align: left; width: 0.6; lineHeight: 60"
- position="-0.27 0.05 0"></a-entity>
+ text="align: left; width: 0.75; lineHeight: 60"
+ position="-0.34 -0.02 0"></a-entity>
<a-entity
mixin="font"
bind__text="value: multiplayer.opponentScores"
- text="align: right; width: 0.6; lineHeight: 60; color: #FFF"
- position="0.27 0.05 0"></a-entity>
+ text="align: right; width: 0.75; lineHeight: 60; color: #FFF"
+ position="0.34 -0.02 0"></a-entity>
</a-entity>
-<!-- Multiplayer results overlay on victory screen. -->
+<!-- ===================== VICTORY RESULTS ===================== -->
<a-entity
id="mpResults"
bind__visible="mpResultsVisible"
position="0 1.05 -1.6"
render-order="menu">
<a-entity
- geometry="primitive: plane; width: 1.4; height: 0.5"
- material="shader: panelShader; brightness: 0.18; ratio: 2.8; borderWidth: 0.004"
+ geometry="primitive: plane; width: 1.6; height: 0.7"
+ material="shader: panelShader; brightness: 0.20; ratio: 2.3; borderWidth: 0.004"
position="0 0 -0.02"></a-entity>
<a-entity
mixin="font"
- text="align: center; value: ROOM RESULTS; width: 1.2; lineHeight: 60; color: #FFF"
- position="0 0.18 0"></a-entity>
+ bind__text="value: mpWinnerBanner; color: colorSecondaryBright"
+ text="align: center; width: 1.5; lineHeight: 30"
+ position="0 0.27 0"></a-entity>
<a-entity
mixin="font"
- bind__text="value: multiplayer.opponentText"
- text="align: left; width: 1.2; lineHeight: 50; color: #FFF"
- position="-0.55 0.02 0"></a-entity>
+ text="align: center; value: ROOM RESULTS; width: 1.4; lineHeight: 70; color: #888"
+ position="0 0.13 0"></a-entity>
<a-entity
mixin="font"
- bind__text="value: multiplayer.opponentScores"
- text="align: right; width: 1.2; lineHeight: 50; color: #FFF"
- position="0.55 0.02 0"></a-entity>
+ bind__text="value: multiplayer.resultsText"
+ text="align: left; width: 1.4; lineHeight: 50; color: #FFF"
+ position="-0.65 -0.02 0"></a-entity>
+ <a-entity
+ mixin="font"
+ bind__text="value: multiplayer.resultsScores"
+ text="align: right; width: 1.4; lineHeight: 50; color: #FFF"
+ position="0.65 -0.02 0"></a-entity>
<a-entity
bind__visible="multiplayer.isHost"
bind-toggle__raycastable="multiplayer.isHost && mpResultsVisible"
- position="0 -0.18 0"
- geometry="primitive: plane; width: 0.7; height: 0.12"
- material="shader: panelShader; brightness: 0.25; ratio: 5.8; borderWidth: 0.003"
+ position="0 -0.27 0"
+ mixin="modeBackgroundHover"
+ geometry="primitive: plane; width: 0.7; height: 0.13"
+ material="shader: panelShader; brightness: 0.30; ratio: 5.4; borderWidth: 0.003"
proxy-event="event: click; as: mprematch; to: a-scene">
<a-entity
mixin="font"
- text="align: center; value: REMATCH; width: 0.6; lineHeight: 70; color: #FFF"
+ text="align: center; value: REMATCH; width: 0.7; lineHeight: 65; color: #FFF"
position="0 0 0.001"></a-entity>
</a-entity>
</a-entity>
+
+
+<!-- ===================== ROOM-CODE KEYBOARD (in-VR) ===================== -->
+<a-entity
+ id="mpKeyboard"
+ bind__super-keyboard="hand: activeHand === 'left' && '#leftHand' || '#rightHand'; show: mpKeyboardOpen"
+ super-keyboard="hand: #rightHand; imagePath: assets/img/keyboard; font: assets/fonts/Viga-Regular.json; align: center; model: superkeyboard; keyColor: #fff; injectToRaycasterObjects: false; filters: allupper; keyHoverColor: #fff; maxLength: 4; width: 1.3; label: ENTER ROOM CODE; labelColor: #FAFAFA; inputColor: #fff"
+ position="0 1.3 -1.3"
+ render-order="menutext"
+ multiplayer-keyboard-bridge
+ proxy-event__change="event: superkeyboardchange; to: a-scene; as: mpcodeinput"
+ proxy-event__submit="event: superkeyboarddismiss; to: a-scene; as: mpkeyboardsubmit"
+ bind-toggle__raycastable="mpKeyboardOpen"
+ render-order-recursive>
+</a-entity>
+
+
+<!-- ===================== NAME KEYBOARD (in-VR) ===================== -->
+<a-entity
+ id="mpNameKeyboard"
+ bind__super-keyboard="hand: activeHand === 'left' && '#leftHand' || '#rightHand'; show: mpNameKeyboardOpen"
+ super-keyboard="hand: #rightHand; imagePath: assets/img/keyboard; font: assets/fonts/Viga-Regular.json; align: center; model: superkeyboard; keyColor: #fff; injectToRaycasterObjects: false; filters: allupper; keyHoverColor: #fff; maxLength: 14; width: 1.3; label: ENTER YOUR NAME; labelColor: #FAFAFA; inputColor: #fff"
+ position="0 1.3 -1.3"
+ render-order="menutext"
+ proxy-event__change="event: superkeyboardchange; to: a-scene; as: mpnameinput"
+ proxy-event__submit="event: superkeyboarddismiss; to: a-scene; as: mpnamekeyboardsubmit"
+ bind-toggle__raycastable="mpNameKeyboardOpen"
+ render-order-recursive>
+</a-entity>
diff --git a/scripts/refresh-pump-idls.mjs b/scripts/refresh-pump-idls.mjs
new file mode 100644
index 000000000..f2c2a3244
--- /dev/null
+++ b/scripts/refresh-pump-idls.mjs
@@ -0,0 +1,75 @@
+#!/usr/bin/env node
+// Refresh the vendored Pump program IDLs under contracts/idl/pump/.
+//
+// Source of truth: pump-fun/pump-public-docs (mirrored via nirholas/pumpkit).
+// Run after Pump publishes a new IDL version, then commit the diff.
+//
+// node scripts/refresh-pump-idls.mjs
+//
+// Exits non-zero if any download fails so it's safe to wire into CI.
+
+import { writeFileSync, mkdirSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const OUT_DIR = resolve(HERE, '..', 'contracts', 'idl', 'pump');
+
+const SOURCES = [
+ {
+ name: 'pump',
+ urls: [
+ 'https://raw.githubusercontent.com/pump-fun/pump-public-docs/main/idl/pump.json',
+ 'https://raw.githubusercontent.com/nirholas/pumpkit/main/docs/protocol/pump-official/idl/pump.json',
+ ],
+ },
+ {
+ name: 'pump_amm',
+ urls: [
+ 'https://raw.githubusercontent.com/pump-fun/pump-public-docs/main/idl/pump_amm.json',
+ 'https://raw.githubusercontent.com/nirholas/pumpkit/main/docs/protocol/pump-official/idl/pump_amm.json',
+ ],
+ },
+ {
+ name: 'pump_fees',
+ urls: [
+ 'https://raw.githubusercontent.com/pump-fun/pump-public-docs/main/idl/pump_fees.json',
+ 'https://raw.githubusercontent.com/nirholas/pumpkit/main/docs/protocol/pump-official/idl/pump_fees.json',
+ ],
+ },
+];
+
+mkdirSync(OUT_DIR, { recursive: true });
+
+let failures = 0;
+for (const { name, urls } of SOURCES) {
+ let body = null;
+ let usedUrl = null;
+ for (const url of urls) {
+ try {
+ const resp = await fetch(url);
+ if (!resp.ok) continue;
+ const text = await resp.text();
+ JSON.parse(text); // validate structure before writing
+ body = text;
+ usedUrl = url;
+ break;
+ } catch {
+ // try next mirror
+ }
+ }
+ if (!body) {
+ console.error(`✗ ${name}: all sources failed`);
+ failures++;
+ continue;
+ }
+ const outPath = resolve(OUT_DIR, `${name}.json`);
+ writeFileSync(outPath, body);
+ console.log(`✓ ${name} ← ${usedUrl}`);
+}
+
+if (failures > 0) {
+ console.error(`\nRefresh failed for ${failures} IDL(s).`);
+ process.exit(1);
+}
+console.log('\nAll Pump IDLs refreshed.');
diff --git a/scripts/smoke-paid-mcp.mjs b/scripts/smoke-paid-mcp.mjs
index eda999113..02d365f0c 100755
--- a/scripts/smoke-paid-mcp.mjs
+++ b/scripts/smoke-paid-mcp.mjs
@@ -117,11 +117,31 @@ async function step3_zauthStatus() {
else ok('zauth middleware initialized');
}
+async function step4_x402Status() {
+ console.log('\n[4] /api/x402-status (facilitator /supported probe)');
+ const r = await fetch(`${BASE}/api/x402-status`);
+ let body;
+ try {
+ body = await r.json();
+ } catch {
+ return bad(`/api/x402-status returned non-JSON (status ${r.status})`);
+ }
+ if (!body || typeof body !== 'object')
+ return bad('/api/x402-status returned unexpected body');
+ if (!Array.isArray(body.facilitators) || body.facilitators.length === 0)
+ return bad('/api/x402-status reported no facilitators');
+ for (const f of body.facilitators) {
+ if (f.ok) ok(`${f.network}: ${f.url || '(default)'} → ${f.reason}`);
+ else bad(`${f.network}: ${f.url || '(unset)'} — ${f.reason}`);
+ }
+}
+
(async () => {
console.log(`Probing ${URL}`);
const accepts = await step1_challenge();
if (Array.isArray(accepts)) await step2_verifyReachable(accepts);
await step3_zauthStatus();
+ await step4_x402Status();
console.log(`\n${fail.length === 0 ? 'PASS' : `FAIL (${fail.length})`}`);
process.exit(fail.length === 0 ? 0 : 1);
})();
diff --git a/src/agent-avatar.js b/src/agent-avatar.js
index 94838f1c0..2ed6fe124 100644
--- a/src/agent-avatar.js
+++ b/src/agent-avatar.js
@@ -468,10 +468,54 @@ export class AgentAvatar {
_onGesture(action) {
const name = action.payload?.name || 'nod';
+ const loop = action.payload?.loop === true;
const duration = (action.payload?.duration || 1500) / 1000;
+ // `loop:true` lets host pages keep a chip-triggered animation running
+ // indefinitely (e.g. "dance", "idle", "thriller" on the pumpfun chip
+ // strip). Without it, every gesture defaults to a 1.5s one-shot that
+ // auto-reverts to idle — correct for nod/wave, wrong for dance/idle.
+ if (loop) {
+ this._playLoopedClip(name);
+ return;
+ }
this._playSlot(name, duration);
}
+ /**
+ * Play a clip in loop mode and stay there until another gesture/clip is
+ * triggered. Cancels any pending one-shot revert from a prior `_playSlot`.
+ * @param {string} name
+ */
+ _playLoopedClip(name) {
+ // Cancel any one-shot revert state so we don't trip back to idle.
+ this._isPlayingOneShot = false;
+ this._oneShotAction = null;
+ this._oneShotTimer = 0;
+
+ const am = this.viewer?.animationManager;
+ if (am?.isLoaded?.(name)) {
+ am.crossfadeTo(name, 0.35);
+ return;
+ }
+ const def = am?.getAnimationDefs?.().find((d) => d.name === name);
+ if (am && def) {
+ am.loadAnimation(name, def.url, { loop: true, clipName: def.clipName })
+ .then(() => am.crossfadeTo(name, 0.35))
+ .catch(() => {});
+ return;
+ }
+ // Baked GLB clip (non-Avaturn rig): play directly through the mixer.
+ const baked = this.viewer?.clips?.find?.((c) => c?.name === name);
+ const mixer = am?.mixer || this.viewer?.mixer;
+ if (baked && mixer) {
+ const action = mixer.clipAction(baked);
+ action.reset();
+ action.setLoop(2201 /* THREE.LoopRepeat */);
+ action.fadeIn(0.35);
+ action.play();
+ }
+ }
+
_onEmote(action) {
const trigger = action.payload?.trigger;
const weight = action.payload?.weight || 0.7;
@@ -488,8 +532,20 @@ export class AgentAvatar {
const center = new Vector3();
box.setFromObject(this.viewer.content).getCenter(center);
this._lookTarget = center;
- } else if (target === 'user') {
+ } else if (target === 'user' || target === 'camera') {
this._lookTarget = null; // look at camera
+ } else if (target === 'down') {
+ // Bias gaze downward — paired with concern emote for somber moments.
+ this._keystrokePitch = -0.35;
+ this._lookTarget = null;
+ } else if (target === 'up') {
+ this._keystrokePitch = 0.3;
+ this._lookTarget = null;
+ } else if (target === 'token' && typeof window !== 'undefined') {
+ // Token-card reaction direction: glance off-camera to the right
+ // where the live-feed UI typically renders (right rail).
+ this._keystrokeYaw = 0.4;
+ this._lookTarget = null;
}
this._injectStimulus('curiosity', 0.3);
}
@@ -993,3 +1049,4 @@ export class AgentAvatar {
function _lerp(a, b, t) {
return a + (b - a) * Math.min(1, Math.max(0, t));
}
+// TODO injected for test
diff --git a/src/app.js b/src/app.js
index 5fe567822..1c544eab9 100644
--- a/src/app.js
+++ b/src/app.js
@@ -17,6 +17,7 @@ import { mountHotspotTour } from './widgets/hotspot-tour.js';
import { mountPumpfunFeed } from './widgets/pumpfun-feed.js';
import { mountKolTradesWidget } from './widgets/kol-trades.js';
import { mountLiveTradesCanvas } from './widgets/live-trades-canvas.js';
+import { mountPassport } from './widgets/passport.js';
import queryString from 'query-string';
// Agent system — the new primitive layer
@@ -1027,6 +1028,9 @@ class App {
minUsd: cfg.minUsd,
});
this._widgetController = ctl;
+ } else if (type === 'passport') {
+ const ctl = await mountPassport(this.viewer, cfg, document.body, widgetId);
+ this._widgetController = ctl;
}
} catch (e) {
console.warn('[widget] mount failed', type, e?.message);
diff --git a/src/embed-host-bridge.js b/src/embed-host-bridge.js
index 523c9c338..7d42b5114 100644
--- a/src/embed-host-bridge.js
+++ b/src/embed-host-bridge.js
@@ -45,7 +45,7 @@ export class EmbedHostBridge {
this._agentId = agentId;
this._allowedOrigin = allowedOrigin;
this._pending = new Map(); // id → { resolve, reject, timer }
- this._listeners = { action: new Set(), state: new Set(), error: new Set() };
+ this._listeners = { action: new Set(), state: new Set(), error: new Set(), clips: new Set() };
this._outQueue = []; // requests queued before handshake completes
this._evtBuffer = []; // incoming events buffered before a listener is attached
this._ready = false;
@@ -128,7 +128,14 @@ export class EmbedHostBridge {
}
if (msg.kind === 'event') {
- const bucket = msg.op === 'error' ? 'error' : msg.op === 'state' ? 'state' : 'action';
+ const bucket =
+ msg.op === 'error'
+ ? 'error'
+ : msg.op === 'state'
+ ? 'state'
+ : msg.op === 'clips'
+ ? 'clips'
+ : 'action';
const set = this._listeners[bucket];
if (set?.size) {
for (const h of set) h(msg.payload);
@@ -145,9 +152,27 @@ export class EmbedHostBridge {
return this._request('speak', { text, ...opts });
}
- /** @param {string} name @returns {Promise<void>} */
- gesture(name) {
- return this._request('gesture', { name });
+ /**
+ * Trigger a named animation gesture inside the embedded agent.
+ * @param {string} name
+ * @param {{ loop?: boolean, duration?: number }} [opts]
+ * - `loop:true` keeps the clip running until another gesture is triggered
+ * (use for dance/idle/thriller). Default: 1.5s one-shot that auto-reverts.
+ * - `duration` overrides the one-shot length in milliseconds.
+ * @returns {Promise<void>}
+ */
+ gesture(name, opts = {}) {
+ return this._request('gesture', { name, ...opts });
+ }
+
+ /**
+ * Fetch the list of animation clips available on the currently-loaded model.
+ * Combined: manifest defs (humanoid rigs) + GLB-baked clips, with skeleton
+ * compatibility heuristics applied — see element.js#_listAvailableClips.
+ * @returns {Promise<{ clips: Array<{name:string,label:string,icon:string,loop:boolean,source:'manifest'|'glb'}> }>}
+ */
+ listClips() {
+ return this._request('listClips', {});
}
/** @param {{ trigger: string, weight: number }} emote @returns {Promise<void>} */
@@ -167,7 +192,9 @@ export class EmbedHostBridge {
/**
* Subscribe to events from the embedded agent.
- * @param {'action'|'state'|'error'} event
+ * @param {'action'|'state'|'error'|'clips'} event
+ * - `clips`: fired when the embed's available clip list changes (e.g.
+ * after a model swap). Payload: `{ clips: [...] }`.
* @param {Function} handler
* @returns {Function} unsubscribe
*/
diff --git a/src/viewer.js b/src/viewer.js
index a1b334fe5..0232dbb58 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -116,7 +116,11 @@ export class Viewer {
this.renderer = window.renderer = new WebGLRenderer({ antialias: true, alpha: true });
this.renderer.setClearColor(0x000000, 1);
- this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ // DPR cap: kiosk/embed modes default to 1.5 (saves ~40% fragment work on
+ // retina). Override with options.maxPixelRatio. Standalone tabs default
+ // to 2.0 to preserve sharpness on high-DPI displays.
+ const dprCap = options.maxPixelRatio ?? (options.kiosk ? 1.5 : 2);
+ this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, dprCap));
this.renderer.setSize(el.clientWidth, el.clientHeight);
this.pmremGenerator = new PMREMGenerator(this.renderer);
diff --git a/src/widgets/pumpfun-feed.js b/src/widgets/pumpfun-feed.js
index 01e33268a..cc0ae733b 100644
--- a/src/widgets/pumpfun-feed.js
+++ b/src/widgets/pumpfun-feed.js
@@ -13,7 +13,7 @@
* - maxCards 1..50
*/
-import { applyReaction, createReactionDispatcher } from './pumpfun-reactions.js';
+import { applyReaction, createReactionDispatcher, mountReactionToast } from './pumpfun-reactions.js';
const FEED_PATH = '/api/agents/pumpfun-feed';
const TIER_BADGE = { mega: '🔥🔥', influencer: '🔥', notable: '⭐' };
diff --git a/src/widgets/pumpfun-reactions.js b/src/widgets/pumpfun-reactions.js
index 86aa7513a..521dd26aa 100644
--- a/src/widgets/pumpfun-reactions.js
+++ b/src/widgets/pumpfun-reactions.js
@@ -1,214 +1,580 @@
/**
- * Pump.fun avatar reaction map.
+ * Pump.fun avatar reaction engine.
*
- * Given a feed event (mint / claim / graduation), returns the sequence of
- * protocol actions the avatar should perform: an emote stimulus (drives the
- * empathy layer), a one-shot gesture clip (visible body language / dance),
- * and an optional speak line. All clip names map to entries in
- * /public/animations/manifest.json. Slot names ('celebrate', 'concern',
- * 'wave', 'shake'…) flow through DEFAULT_ANIMATION_MAP; non-slot names
- * (e.g. 'rumba', 'thriller', 'silly', 'capoeira', 'taunt', 'kiss') are
- * resolved by the AnimationManager directly via _playSlot's fallback path.
+ * Given a raw feed event from /api/agents/pumpfun-feed, decides:
+ * 1. how to derive a richer "signal envelope" (tier shape, MC delta, dev
+ * track record, GitHub legitimacy, curve proximity, post-graduation
+ * health, whale-claimer flag) from the messy upstream payload
+ * 2. which Reaction (emote + gesture + speak + look-at) best matches that
+ * envelope across the full animation library
+ * 3. when to fire vs. defer it given an in-flight gesture, dedupe history,
+ * and the configured personality/mood
*
- * Design notes
- * ─────────────
- * - Each reaction is a plain { emote, gesture, speak } record so callers can
- * route it through any combination of channels (full narration vs. silent
- * gesture-only). This keeps narration toggle and avatar reaction decoupled.
- * - Durations are returned in milliseconds. agent-avatar's _onGesture
- * converts to seconds before handing off to the animation manager.
- * - A single dispatcher (`reactToEvent`) runs the dedupe + cooldown gate so
- * the host page and the in-iframe widget can both call it without stepping
- * on each other when both are mounted (e.g. /pumpfun.html host page +
- * pumpfun-feed widget mounted inside /app).
+ * Design pillars
+ * ──────────────
+ * - **Pure** reaction map — `reactionFor(kind, ev, opts)` is deterministic
+ * so it tests cleanly and composes with mood biases.
+ * - **One-liner speak** for every variant. Avatar can be muted, but when
+ * narration is on, it always has something to say.
+ * - **Queue, not drop** — if an event lands mid-dance and is too low-priority
+ * to preempt, it's enqueued and fires after cooldown, ordered by priority.
+ * - **Telemetry** — ring buffer of the last N reactions and per-variant
+ * counts, available via `.history()` / `.stats()` for debug surfaces.
+ * - **Mood** — 'chill' | 'normal' | 'hype' biases gesture duration and
+ * raises/lowers the threshold at which low-priority events fire at all.
+ *
+ * Animation library coverage (32 clips → 23 used distinct):
+ * rumba, thriller, silly, capoeira, dance, kiss, taunt, celebrate,
+ * reaction, wave, jump, pray, sitclap, sitlaugh, shake, defeated,
+ * angry, dying, falling, dodge, stepback, shoved, standup
+ */
+
+/**
+ * @typedef {{ trigger: string, weight: number }} EmotePayload
+ * @typedef {{ name: string, duration: number }} GesturePayload
+ * @typedef {{ text: string, sentiment: number }} SpeakPayload
+ * @typedef {'token'|'camera'|'down'|'up'} LookTarget
+ *
+ * @typedef {Object} Reaction
+ * @property {string} variant stable identifier for telemetry / toasts
+ * @property {string} icon emoji icon for UI overlays
+ * @property {EmotePayload} [emote]
+ * @property {GesturePayload} [gesture]
+ * @property {SpeakPayload} [speak]
+ * @property {LookTarget} [lookAt]
+ * @property {number} [priority] higher = preempts lower in-flight reactions
*/
-/** @typedef {{ emote?: { trigger: string, weight: number },
- * gesture?: { name: string, duration: number },
- * speak?: { text: string, sentiment: number },
- * priority?: number }} Reaction */
+/** @typedef {'chill'|'normal'|'hype'} Mood */
+
+const MOOD_PROFILE = {
+ chill: { gestureScale: 0.7, threshold: 30, speakRate: 0.4 },
+ normal: { gestureScale: 1.0, threshold: 0, speakRate: 1.0 },
+ hype: { gestureScale: 1.25, threshold: -20, speakRate: 1.5 },
+};
-const TIER_WEIGHT = { mega: 1.0, influencer: 0.75, notable: 0.5 };
+const TIER_RANK = { mega: 3, influencer: 2, notable: 1 };
/**
- * Decide which reaction to play for a given pump.fun event.
- * Returns null when nothing notable should happen (silent flyby).
+ * Extract a normalized signal envelope from a raw feed event. Centralizes the
+ * dozens of `??` / fallback chains so the reaction map can read clean fields.
*
- * @param {string} kind 'mint' | 'claim' | 'graduation'
- * @param {object} ev raw event payload from /api/agents/pumpfun-feed
+ * @param {object} ev
+ * @returns {object}
+ */
+export function extractSignals(ev) {
+ if (!ev) return {};
+ const num = (x) => {
+ const n = Number(x);
+ return Number.isFinite(n) ? n : 0;
+ };
+
+ const mint = ev.mint || ev.token_mint || '';
+ const symbol = ev.symbol || ev.token_symbol || '';
+ const name = ev.name || ev.token_name || symbol || 'a token';
+
+ const mcInitial = num(ev.market_cap_usd_initial ?? ev.initial_market_cap_usd ?? ev.market_cap_at_launch);
+ const mcCurrent = num(ev.usd_market_cap ?? ev.market_cap_usd ?? ev.market_cap);
+ const mcAth = num(ev.ath_market_cap ?? ev.ath_usd ?? ev.market_cap_ath_usd);
+ const mcMultiple = mcInitial && mcCurrent ? mcCurrent / mcInitial : 0;
+ const drawdown = mcAth && mcCurrent ? mcCurrent / mcAth : 1; // 1 = at ATH, 0.1 = down 90%
+ const initialBuySol = num(ev.initial_buy_sol);
+ const amountSol = num(ev.amount_sol);
+ const amountUsd = num(ev.amount_usd);
+ const lifetimeSol = num(ev.lifetime_claim_sol ?? ev.lifetime_sol);
+ const curvePct = num(ev.bonding_curve_pct ?? ev.curve_progress);
+
+ // Creator / dev cred
+ const creatorLaunches = num(ev.creator_launches);
+ const creatorGraduated = num(ev.creator_graduated);
+ const isSerialCreator = creatorGraduated >= 3;
+ const isFirstLaunch = creatorLaunches <= 1;
+ const isDevRelaunch = creatorLaunches >= 2 && creatorGraduated === 0;
+
+ // GitHub / claim legitimacy
+ const ghUser = ev.github_user || null;
+ const ghLinked = !!(ghUser || ev.github_repo || ev.github_account_age_days != null);
+ const ghVerified = !!(ev.verified ?? ev.signal_verified);
+ const ghFollowers = num(ev.github_followers);
+ const ghAccountAgeDays = num(ev.github_account_age_days);
+ const repoStars = num(ev.github_repo_stars ?? ev.repo_stars);
+ const ghCredible = ghLinked && (ghAccountAgeDays >= 365 || ghFollowers >= 50 || repoStars >= 10);
+
+ // Outcome flags
+ const isFirstClaim = !!ev.first_time_claim;
+ const isFakeClaim = !!ev.fake_claim;
+ const isWhaleClaim = lifetimeSol >= 50; // >= 50 SOL lifetime → whale
+ const tier = (ev.tier || '').toLowerCase() || null;
+ const tierRank = TIER_RANK[tier] || 0;
+
+ // Health flags
+ const isRugged = mcAth > 0 && mcCurrent > 0 && drawdown <= 0.1; // down >= 90% from ATH
+ const isMooning = mcMultiple >= 100;
+ const isGiantPump = mcMultiple >= 10 && mcMultiple < 100;
+ const isNearGrad = curvePct >= 95 && curvePct < 100;
+
+ return {
+ mint, symbol, name,
+ mcInitial, mcCurrent, mcAth, mcMultiple, drawdown, curvePct,
+ initialBuySol, amountSol, amountUsd, lifetimeSol,
+ creatorLaunches, creatorGraduated,
+ isSerialCreator, isFirstLaunch, isDevRelaunch,
+ ghUser, ghLinked, ghVerified, ghCredible, ghFollowers, repoStars, ghAccountAgeDays,
+ isFirstClaim, isFakeClaim, isWhaleClaim,
+ tier, tierRank,
+ isRugged, isMooning, isGiantPump, isNearGrad,
+ txSig: ev.tx_signature || ev.signature || null,
+ aiTake: ev.ai_take || null,
+ };
+}
+
+/**
+ * @param {string} kind 'mint' | 'claim' | 'graduation' | 'trade'
+ * @param {object} ev raw event payload
+ * @param {{ mood?: Mood }} [opts]
* @returns {Reaction|null}
*/
-export function reactionFor(kind, ev) {
+export function reactionFor(kind, ev, opts = {}) {
if (!ev) return null;
- if (kind === 'graduation') return graduationReaction(ev);
- if (kind === 'claim') return claimReaction(ev);
- if (kind === 'mint') return mintReaction(ev);
- return null;
+ const s = extractSignals(ev);
+ let r = null;
+ if (kind === 'graduation') r = graduationReaction(s);
+ else if (kind === 'claim') r = claimReaction(s);
+ else if (kind === 'mint') r = mintReaction(s);
+ else if (kind === 'trade') r = tradeReaction(s, ev);
+
+ if (!r) return null;
+ const profile = MOOD_PROFILE[opts.mood] || MOOD_PROFILE.normal;
+ const priority = (r.priority ?? 0) + profile.threshold;
+ if (priority < 0) return null;
+ if (r.gesture) r.gesture = { ...r.gesture, duration: Math.round(r.gesture.duration * profile.gestureScale) };
+ r.priority = priority;
+ return r;
}
-function graduationReaction(ev) {
- const sym = ev.symbol || ev.name || 'a token';
- // Graduation = the milestone moment. Always celebrate big.
- // Bigger MC delta gets a longer dance, capped.
- const initial = num(ev.market_cap_usd_initial ?? ev.initial_market_cap_usd ?? ev.market_cap_at_launch);
- const current = num(ev.usd_market_cap ?? ev.market_cap_usd ?? ev.market_cap);
- const multiple = initial && current ? current / initial : 1;
- const duration = clamp(4500 + Math.log10(Math.max(multiple, 1)) * 1500, 4500, 9000);
+// ── Variants ─────────────────────────────────────────────────────────────────
+
+function graduationReaction(s) {
+ if (s.isMooning) {
+ return {
+ variant: 'graduation_moonshot',
+ icon: '🚀🌕',
+ emote: { trigger: 'celebration', weight: 1.0 },
+ gesture: { name: 'thriller', duration: 9000 },
+ speak: { text: `Moonshot! $${s.symbol || s.name} just went ${fmtMult(s.mcMultiple)} — bonded to PumpAMM.`, sentiment: 0.95 },
+ lookAt: 'camera',
+ priority: 100,
+ };
+ }
+ if (s.isGiantPump) {
+ return {
+ variant: 'graduation_giant',
+ icon: '🎓🔥',
+ emote: { trigger: 'celebration', weight: 0.95 },
+ gesture: { name: 'rumba', duration: 7000 },
+ speak: { text: `Giant pump: $${s.symbol || s.name} ${fmtMult(s.mcMultiple)} into PumpAMM.`, sentiment: 0.85 },
+ lookAt: 'camera',
+ priority: 95,
+ };
+ }
+ if (s.isSerialCreator) {
+ return {
+ variant: 'graduation_serial_dev',
+ icon: '🎓👑',
+ emote: { trigger: 'celebration', weight: 0.85 },
+ gesture: { name: 'capoeira', duration: 6500 },
+ speak: { text: `Serial creator strikes again — $${s.symbol || s.name} graduated. ${s.creatorGraduated} grads now.`, sentiment: 0.7 },
+ lookAt: 'camera',
+ priority: 92,
+ };
+ }
return {
- emote: { trigger: 'celebration', weight: 0.95 },
- gesture: { name: 'rumba', duration },
- speak: { text: `Migration: ${sym} bonded to PumpAMM.`, sentiment: 0.7 },
+ variant: 'graduation_standard',
+ icon: '🎓',
+ emote: { trigger: 'celebration', weight: 0.9 },
+ gesture: { name: 'rumba', duration: clampDur(4500 + Math.log10(Math.max(s.mcMultiple, 1) + 1) * 1500, 4500, 8000) },
+ speak: { text: `Migration: $${s.symbol || s.name} bonded to PumpAMM.`, sentiment: 0.7 },
+ lookAt: 'camera',
priority: 90,
};
}
-function claimReaction(ev) {
- if (ev.fake_claim) {
+function claimReaction(s) {
+ if (s.isFakeClaim) {
return {
- emote: { trigger: 'concern', weight: 0.75 },
- gesture: { name: 'shake', duration: 1500 },
- speak: {
- text: `Fake claim from ${ev.github_user ? '@' + ev.github_user : shortAddr(ev.claimer)}.`,
- sentiment: -0.6,
- },
- priority: 70,
+ variant: 'claim_fake',
+ icon: '⚠️',
+ emote: { trigger: 'concern', weight: 0.85 },
+ gesture: { name: 'shake', duration: 1800 },
+ speak: { text: `Fake claim spotted${s.ghUser ? ' from @' + s.ghUser : ''}. Ignore it.`, sentiment: -0.6 },
+ lookAt: 'down',
+ priority: 75,
};
}
- if (ev.first_time_claim) {
- // First-claim variants: GitHub-linked → silly hip-hop, raw wallet → celebrate clip.
- const linked = !!(ev.github_user || ev.github_repo || ev.github_account_age_days != null);
- const verified = ev.verified ?? ev.signal_verified;
- const gestureName = linked ? (verified ? 'thriller' : 'silly') : 'celebrate';
- const sym = ev.token_symbol || ev.symbol;
- const who = linked ? '@' + ev.github_user : shortAddr(ev.claimer || ev.creator);
+ if (s.isFirstClaim) {
+ // Tiered first-claim variants — credibility ladders the dance.
+ if (s.ghCredible && s.ghVerified) {
+ return {
+ variant: 'claim_first_verified_credible',
+ icon: '🚨✅',
+ emote: { trigger: 'celebration', weight: 1.0 },
+ gesture: { name: 'thriller', duration: 6000 },
+ speak: { text: `Verified first claim by @${s.ghUser}${s.aiTake ? ' — ' + s.aiTake : ''}.`, sentiment: 0.85 },
+ lookAt: 'camera',
+ priority: 88,
+ };
+ }
+ if (s.ghLinked && s.ghVerified) {
+ return {
+ variant: 'claim_first_verified',
+ icon: '🚨',
+ emote: { trigger: 'celebration', weight: 0.95 },
+ gesture: { name: 'silly', duration: 5500 },
+ speak: { text: `First claim by @${s.ghUser || 'dev'}${s.aiTake ? ' — ' + s.aiTake : ''}.`, sentiment: 0.8 },
+ lookAt: 'camera',
+ priority: 86,
+ };
+ }
+ if (s.ghLinked) {
+ return {
+ variant: 'claim_first_unverified_gh',
+ icon: '🚨❓',
+ emote: { trigger: 'curiosity', weight: 0.7 },
+ gesture: { name: 'capoeira', duration: 4500 },
+ speak: { text: `First claim — @${s.ghUser || 'dev'} unverified. Watch closely.`, sentiment: 0.4 },
+ lookAt: 'token',
+ priority: 82,
+ };
+ }
+ if (s.isWhaleClaim) {
+ return {
+ variant: 'claim_first_whale',
+ icon: '🐋',
+ emote: { trigger: 'celebration', weight: 0.85 },
+ gesture: { name: 'taunt', duration: 3000 },
+ speak: { text: `Whale claimer — ${fmtSol(s.lifetimeSol)} lifetime on $${s.symbol || 'this'}.`, sentiment: 0.6 },
+ lookAt: 'token',
+ priority: 80,
+ };
+ }
return {
- emote: { trigger: 'celebration', weight: 0.95 },
- gesture: { name: gestureName, duration: 5000 },
- speak: {
- text: `First-time claim by ${who}${sym ? ' on $' + sym : ''}${ev.ai_take ? ' — ' + ev.ai_take : ''}.`,
- sentiment: 0.75,
- },
- priority: 85,
+ variant: 'claim_first_raw',
+ icon: '🚨',
+ emote: { trigger: 'celebration', weight: 0.85 },
+ gesture: { name: 'celebrate', duration: 4500 },
+ speak: { text: `First-time claim on $${s.symbol || 'a new token'}.`, sentiment: 0.7 },
+ lookAt: 'camera',
+ priority: 78,
};
}
- // Tiered repeat claims — quieter, no full dance.
- const tier = ev.tier;
- if (tier === 'mega') {
+ // Repeat claims — calm, no full dance.
+ if (s.isWhaleClaim) {
return {
+ variant: 'claim_whale_repeat',
+ icon: '🐋',
+ emote: { trigger: 'curiosity', weight: 0.6 },
+ gesture: { name: 'taunt', duration: 2200 },
+ speak: { text: `Whale claim — ${fmtSol(s.amountSol)} on $${s.symbol || 'token'}.`, sentiment: 0.4 },
+ lookAt: 'token',
+ priority: 55,
+ };
+ }
+ if (s.tier === 'mega') {
+ return {
+ variant: 'claim_tier_mega',
+ icon: '🔥🔥',
emote: { trigger: 'celebration', weight: 0.7 },
gesture: { name: 'taunt', duration: 2500 },
+ speak: { text: `Mega claim — ${fmtSol(s.amountSol)}.`, sentiment: 0.5 },
+ lookAt: 'token',
priority: 50,
};
}
- if (tier === 'influencer') {
+ if (s.tier === 'influencer') {
return {
+ variant: 'claim_tier_influencer',
+ icon: '🔥',
emote: { trigger: 'curiosity', weight: 0.55 },
gesture: { name: 'reaction', duration: 1800 },
+ speak: { text: `Influencer claim on $${s.symbol || 'token'}.`, sentiment: 0.3 },
+ lookAt: 'token',
priority: 35,
};
}
- if (tier === 'notable') {
+ if (s.tier === 'notable') {
return {
+ variant: 'claim_tier_notable',
+ icon: '⭐',
emote: { trigger: 'curiosity', weight: 0.4 },
+ speak: { text: `Notable claim seen.`, sentiment: 0.2 },
+ lookAt: 'token',
priority: 20,
};
}
return null;
}
-function mintReaction(ev) {
- // Mints fire constantly. Only react to ones with notable initial buy or
- // that come pre-tiered, otherwise the avatar would never stop reacting.
- const initialSol = num(ev.initial_buy_sol);
- if (ev.tier === 'mega' || (initialSol && initialSol >= 5)) {
+function mintReaction(s) {
+ if (s.initialBuySol >= 20) {
+ return {
+ variant: 'mint_giant_buy',
+ icon: '🚀💸',
+ emote: { trigger: 'curiosity', weight: 0.85 },
+ gesture: { name: 'jump', duration: 2000 },
+ speak: { text: `Massive launch: $${s.symbol || 'new token'} opens with ${fmtSol(s.initialBuySol)}.`, sentiment: 0.6 },
+ lookAt: 'camera',
+ priority: 60,
+ };
+ }
+ if (s.isDevRelaunch) {
+ return {
+ variant: 'mint_dev_relaunch',
+ icon: '🔁',
+ emote: { trigger: 'concern', weight: 0.5 },
+ gesture: { name: 'reaction', duration: 1600 },
+ speak: { text: `Dev's back — ${s.creatorLaunches} launches, 0 grads. $${s.symbol}.`, sentiment: -0.2 },
+ lookAt: 'down',
+ priority: 40,
+ };
+ }
+ if (s.isSerialCreator) {
return {
+ variant: 'mint_serial_creator',
+ icon: '👑',
+ emote: { trigger: 'curiosity', weight: 0.7 },
+ gesture: { name: 'wave', duration: 1500 },
+ speak: { text: `Pro dev launching $${s.symbol || 'a new token'} — ${s.creatorGraduated} prior grads.`, sentiment: 0.5 },
+ lookAt: 'camera',
+ priority: 45,
+ };
+ }
+ if (s.tier === 'mega' || s.initialBuySol >= 5) {
+ return {
+ variant: 'mint_notable',
+ icon: '🌱🔥',
emote: { trigger: 'curiosity', weight: 0.55 },
gesture: { name: 'wave', duration: 1500 },
+ speak: { text: `New token $${s.symbol || '?'} — ${fmtSol(s.initialBuySol)} initial.`, sentiment: 0.3 },
+ lookAt: 'token',
priority: 25,
};
}
- if (ev.tier === 'influencer' || (initialSol && initialSol >= 1)) {
+ if (s.tier === 'influencer' || s.initialBuySol >= 1) {
return {
+ variant: 'mint_warm',
+ icon: '🌱',
emote: { trigger: 'curiosity', weight: 0.35 },
+ lookAt: 'token',
priority: 10,
};
}
return null;
}
+function tradeReaction(s, ev) {
+ const usd = Number(ev?.amount_usd) || 0;
+ const isBuy = ev?.is_buy ?? ev?.isBuy ?? (ev?.txType === 'buy') ?? (ev?.type === 'buy');
+ if (usd < 1000) return null;
+ if (isBuy) {
+ if (usd >= 50_000) {
+ return {
+ variant: 'trade_whale_buy',
+ icon: '🐋💚',
+ emote: { trigger: 'celebration', weight: 0.85 },
+ gesture: { name: 'jump', duration: 2200 },
+ speak: { text: `Whale buy — ${fmtUsd(usd)} into $${s.symbol || 'token'}.`, sentiment: 0.7 },
+ lookAt: 'camera',
+ priority: 65,
+ };
+ }
+ return {
+ variant: 'trade_big_buy',
+ icon: '💚',
+ emote: { trigger: 'celebration', weight: 0.55 },
+ gesture: { name: 'wave', duration: 1200 },
+ speak: { text: `Big buy on $${s.symbol || 'token'}.`, sentiment: 0.4 },
+ lookAt: 'token',
+ priority: 30,
+ };
+ }
+ // Sells
+ if (usd >= 50_000) {
+ return {
+ variant: 'trade_whale_sell',
+ icon: '🐋💀',
+ emote: { trigger: 'concern', weight: 0.85 },
+ gesture: { name: 'shoved', duration: 1800 },
+ speak: { text: `Whale dump — ${fmtUsd(usd)} out of $${s.symbol || 'token'}.`, sentiment: -0.7 },
+ lookAt: 'down',
+ priority: 65,
+ };
+ }
+ return {
+ variant: 'trade_big_sell',
+ icon: '🩸',
+ emote: { trigger: 'concern', weight: 0.5 },
+ gesture: { name: 'dodge', duration: 1300 },
+ speak: { text: `Big sell on $${s.symbol || 'token'}.`, sentiment: -0.4 },
+ lookAt: 'down',
+ priority: 30,
+ };
+}
+
+// ── Dispatcher ───────────────────────────────────────────────────────────────
+
/**
- * Stateful dispatcher: dedupes reactions per (kind,mint), enforces a global
- * cooldown so a flood of claims doesn't lock the avatar into a 5s loop, and
- * lets a higher-priority reaction (graduation > first-claim > tier) preempt
- * a lower one already in flight.
+ * Stateful dispatcher: dedupes per (kind,mint), enforces a global cooldown,
+ * supports priority preemption, queues high-priority events that arrive
+ * mid-gesture, and tracks telemetry.
*
- * @param {{ now?: () => number, cooldownMs?: number }} [opts]
+ * @param {{
+ * now?: () => number,
+ * cooldownMs?: number,
+ * dedupeWindowMs?: number,
+ * mood?: Mood,
+ * maxQueue?: number,
+ * maxHistory?: number,
+ * onFire?: (reaction: Reaction, kind: string, ev: object) => void,
+ * }} [opts]
*/
export function createReactionDispatcher(opts = {}) {
const now = opts.now || (() => Date.now());
const cooldownMs = opts.cooldownMs ?? 2200;
- const dedupeWindowMs = 30_000;
+ const dedupeWindowMs = opts.dedupeWindowMs ?? 30_000;
+ const maxQueue = opts.maxQueue ?? 6;
+ const maxHistory = opts.maxHistory ?? 50;
+ let mood = opts.mood || 'normal';
+
/** @type {Map<string, number>} */
const seen = new Map();
let activeUntil = 0;
let activePriority = 0;
+ /** @type {{ kind: string, ev: object, priority: number, enqueuedAt: number, runner: (r: Reaction)=>void }[]} */
+ const queue = [];
+ /** @type {{ at: number, kind: string, variant: string, mint: string }[]} */
+ const history = [];
+ const stats = Object.create(null); // variant → count
+ let queueTimer = null;
- return {
+ function record(reaction, kind, ev) {
+ stats[reaction.variant] = (stats[reaction.variant] || 0) + 1;
+ history.push({
+ at: now(),
+ kind,
+ variant: reaction.variant,
+ mint: ev?.mint || ev?.token_mint || '',
+ });
+ while (history.length > maxHistory) history.shift();
+ try { opts.onFire?.(reaction, kind, ev); } catch {}
+ // Toast overlays attach themselves via dispatcher._toastHook.
+ try { dispatcherSelf._toastHook?.(reaction, kind, ev); } catch {}
+ }
+
+ let dispatcherSelf;
+
+ function tryDrainQueue() {
+ queueTimer = null;
+ if (!queue.length) return;
+ const t = now();
+ if (t < activeUntil) {
+ scheduleDrain();
+ return;
+ }
+ queue.sort((a, b) => b.priority - a.priority);
+ const next = queue.shift();
+ const reaction = reactionFor(next.kind, next.ev, { mood });
+ if (!reaction) {
+ scheduleDrain();
+ return;
+ }
+ fire(reaction, next.kind, next.ev, next.runner);
+ scheduleDrain();
+ }
+
+ function scheduleDrain() {
+ if (queueTimer != null || !queue.length) return;
+ const wait = Math.max(0, activeUntil - now());
+ queueTimer = setTimeout(tryDrainQueue, wait + 5);
+ }
+
+ function fire(reaction, kind, ev, runner) {
+ const dur = reaction.gesture?.duration ?? cooldownMs;
+ activeUntil = now() + Math.max(cooldownMs, dur);
+ activePriority = reaction.priority ?? 0;
+ record(reaction, kind, ev);
+ try { runner(reaction); } catch (err) {
+ console.warn('[pumpfun-reactions] runner threw:', err);
+ }
+ }
+
+ dispatcherSelf = {
/**
* @param {string} kind
* @param {object} ev
* @param {(reaction: Reaction) => void} run
- * @returns {boolean} whether the reaction was dispatched
+ * @returns {'fired'|'queued'|'deduped'|'dropped'|'silent'}
*/
dispatch(kind, ev, run) {
- const reaction = reactionFor(kind, ev);
- if (!reaction) return false;
+ const reaction = reactionFor(kind, ev, { mood });
+ if (!reaction) return 'silent';
const t = now();
const key = dedupeKey(kind, ev);
if (key) {
const last = seen.get(key);
- if (last != null && t - last < dedupeWindowMs) return false;
+ if (last != null && t - last < dedupeWindowMs) return 'deduped';
seen.set(key, t);
- // Prune: keep map bounded.
if (seen.size > 200) {
- for (const [k, v] of seen) {
- if (t - v > dedupeWindowMs) seen.delete(k);
- }
+ for (const [k, v] of seen) if (t - v > dedupeWindowMs) seen.delete(k);
}
}
const priority = reaction.priority ?? 0;
- if (t < activeUntil && priority <= activePriority) return false;
+ if (t < activeUntil) {
+ if (priority > activePriority) {
+ fire(reaction, kind, ev, run);
+ return 'fired';
+ }
+ if (priority >= 30 && queue.length < maxQueue) {
+ queue.push({ kind, ev, priority, enqueuedAt: t, runner: run });
+ scheduleDrain();
+ return 'queued';
+ }
+ return 'dropped';
+ }
- const dur = reaction.gesture?.duration ?? cooldownMs;
- activeUntil = t + Math.max(cooldownMs, dur);
- activePriority = priority;
- run(reaction);
- return true;
- },
- _state() {
- return { activeUntil, activePriority, seen };
+ fire(reaction, kind, ev, run);
+ return 'fired';
},
+ setMood(next) { if (MOOD_PROFILE[next]) mood = next; },
+ mood: () => mood,
+ history: () => history.slice(),
+ stats: () => ({ ...stats }),
+ queueDepth: () => queue.length,
+ _state() { return { activeUntil, activePriority, seen, queue, history, stats }; },
};
+ return dispatcherSelf;
}
/**
* Apply a Reaction by emitting protocol actions. Caller controls which
- * channels are live via `flags` so a muted host can still drive gestures.
+ * channels are live so a muted host can still drive gestures.
*
* @param {{ emit: (a: any) => void } | null} protocol
* @param {Reaction} reaction
- * @param {{ emote?: boolean, gesture?: boolean, speak?: boolean }} [flags]
+ * @param {{ emote?: boolean, gesture?: boolean, speak?: boolean, lookAt?: boolean }} [flags]
*/
export function applyReaction(protocol, reaction, flags = {}) {
if (!protocol || !reaction) return;
- const want = { emote: true, gesture: true, speak: true, ...flags };
+ const want = { emote: true, gesture: true, speak: true, lookAt: true, ...flags };
if (want.emote && reaction.emote) {
protocol.emit({ type: 'emote', payload: reaction.emote });
}
+ if (want.lookAt && reaction.lookAt) {
+ protocol.emit({ type: 'look-at', payload: { target: reaction.lookAt } });
+ }
if (want.gesture && reaction.gesture) {
protocol.emit({ type: 'gesture', payload: reaction.gesture });
}
@@ -217,26 +583,90 @@ export function applyReaction(protocol, reaction, flags = {}) {
}
}
+/**
+ * Mount a small overlay near the avatar that flashes the reaction icon and
+ * variant label whenever the avatar reacts. Returns a destroy function.
+ *
+ * @param {HTMLElement} container
+ * @param {ReturnType<createReactionDispatcher>} dispatcher
+ */
+export function mountReactionToast(container, dispatcher) {
+ if (!container) return () => {};
+ const root = document.createElement('div');
+ root.className = 'pumpfun-reaction-toast';
+ root.style.cssText = [
+ 'position:absolute', 'left:16px', 'top:16px',
+ 'display:flex', 'flex-direction:column', 'gap:6px',
+ 'pointer-events:none', 'z-index:6',
+ 'font-family:ui-sans-serif,system-ui,-apple-system,sans-serif',
+ ].join(';');
+ container.appendChild(root);
+
+ const original = dispatcher._state().history;
+ const onFire = (reaction, kind, ev) => {
+ const el = document.createElement('div');
+ el.style.cssText = [
+ 'background:rgba(20,20,28,0.85)',
+ 'border:1px solid rgba(255,255,255,0.12)',
+ 'border-radius:999px',
+ 'padding:6px 12px',
+ 'color:#fff', 'font-size:12px',
+ 'display:flex', 'gap:8px', 'align-items:center',
+ 'box-shadow:0 4px 14px rgba(0,0,0,0.45)',
+ 'opacity:0', 'transform:translateY(-4px)',
+ 'transition:opacity .22s ease, transform .22s ease',
+ 'max-width:260px',
+ ].join(';');
+ const sym = ev?.symbol || ev?.token_symbol || ev?.name || '';
+ el.innerHTML = `<span style="font-size:16px">${reaction.icon || '✨'}</span><span style="font-weight:600">${reaction.variant.replace(/_/g, ' ')}</span>${sym ? `<span style="opacity:0.7">$${escapeHtml(sym)}</span>` : ''}`;
+ root.appendChild(el);
+ requestAnimationFrame(() => { el.style.opacity = '1'; el.style.transform = 'translateY(0)'; });
+ setTimeout(() => {
+ el.style.opacity = '0';
+ el.style.transform = 'translateY(-4px)';
+ setTimeout(() => el.remove(), 250);
+ }, Math.max(2200, (reaction.gesture?.duration || 1500) - 500));
+ // Cap visible toasts so a flood doesn't stack forever.
+ while (root.children.length > 4) root.firstChild?.remove();
+ void original; // keep reference happy
+ };
+
+ // Wrap dispatcher.onFire — expose by re-wiring through a hook.
+ dispatcher._toastHook = onFire;
+ return () => { root.remove(); dispatcher._toastHook = null; };
+}
+
+// ── Helpers ──────────────────────────────────────────────────────────────────
+
function dedupeKey(kind, ev) {
const mint = ev?.mint || ev?.token_mint;
if (!mint) return null;
if (kind === 'claim') return `claim:${mint}:${ev?.tx_signature || ev?.signature || ev?.claim_number || ''}`;
+ if (kind === 'trade') return `trade:${mint}:${ev?.tx_signature || ev?.signature || ev?.ts || ''}`;
return `${kind}:${mint}`;
}
-function num(x) {
- if (x == null) return 0;
- const n = Number(x);
- return Number.isFinite(n) ? n : 0;
+function clampDur(v, lo, hi) {
+ return Math.max(lo, Math.min(hi, Math.round(v)));
}
-function clamp(v, lo, hi) {
- return Math.max(lo, Math.min(hi, v));
+function fmtUsd(n) {
+ if (!Number.isFinite(n) || n <= 0) return '$0';
+ if (n >= 1_000_000) return `$${(n / 1_000_000).toFixed(2)}M`;
+ if (n >= 1_000) return `$${(n / 1_000).toFixed(1)}k`;
+ return `$${Math.round(n)}`;
}
-
-function shortAddr(s) {
- const str = String(s || '');
- if (!str) return 'unknown';
- if (str.length <= 12) return str;
- return `${str.slice(0, 4)}…${str.slice(-4)}`;
+function fmtSol(n) {
+ if (!Number.isFinite(n) || n <= 0) return '0 SOL';
+ if (n >= 1000) return `${Math.round(n)} SOL`;
+ return `${n.toFixed(2)} SOL`;
+}
+function fmtMult(m) {
+ if (!Number.isFinite(m) || m <= 0) return '—';
+ if (m >= 100) return `${Math.round(m)}×`;
+ if (m >= 10) return `${m.toFixed(0)}×`;
+ return `${m.toFixed(1)}×`;
+}
+function escapeHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
diff --git a/tests/api-validate.test.js b/tests/api-validate.test.js
new file mode 100644
index 000000000..a788324b5
--- /dev/null
+++ b/tests/api-validate.test.js
@@ -0,0 +1,93 @@
+// Coverage for api/_lib/validate.js — the zod helpers that gate every API
+// endpoint's input. We verify:
+//
+// 1. parse() returns parsed data on success
+// 2. parse() throws a structured 400 with `issues` on failure
+// 3. validateQuery() correctly extracts and parses URL search params
+// 4. validateBody() round-trips through readJson + parse and surfaces the
+// same structured error envelope on bad input
+
+import { describe, it, expect } from 'vitest';
+import { z } from 'zod';
+import { parse, validateQuery, validateBody } from '../api/_lib/validate.js';
+
+const schema = z.object({
+ name: z.string().min(1),
+ count: z.coerce.number().int().min(0).max(100),
+});
+
+describe('validate.parse', () => {
+ it('returns parsed data on success', () => {
+ const res = parse(schema, { name: 'a', count: 5 });
+ expect(res).toEqual({ name: 'a', count: 5 });
+ });
+
+ it('throws structured 400 with issues on failure', () => {
+ try {
+ parse(schema, { name: '', count: 999 });
+ expect.fail('parse should have thrown');
+ } catch (err) {
+ expect(err.status).toBe(400);
+ expect(err.code).toBe('validation_error');
+ expect(Array.isArray(err.issues)).toBe(true);
+ expect(err.issues.length).toBeGreaterThan(0);
+ expect(err.issues[0]).toHaveProperty('path');
+ expect(err.issues[0]).toHaveProperty('message');
+ }
+ });
+});
+
+describe('validate.validateQuery', () => {
+ it('parses search params, coercing numerics', () => {
+ const req = { url: '/x?name=foo&count=42' };
+ expect(validateQuery(req, schema)).toEqual({ name: 'foo', count: 42 });
+ });
+
+ it('throws with issues on bad query', () => {
+ const req = { url: '/x?name=&count=-1' };
+ try {
+ validateQuery(req, schema);
+ expect.fail('validateQuery should have thrown');
+ } catch (err) {
+ expect(err.code).toBe('validation_error');
+ expect(err.issues.length).toBeGreaterThan(0);
+ }
+ });
+});
+
+describe('validate.validateBody', () => {
+ function makeReq(body, ct = 'application/json') {
+ const buf = Buffer.from(JSON.stringify(body));
+ return {
+ headers: { 'content-type': ct },
+ on(evt, cb) {
+ if (evt === 'data') queueMicrotask(() => cb(buf));
+ if (evt === 'end') queueMicrotask(() => cb());
+ },
+ destroy() {},
+ };
+ }
+
+ it('parses a JSON body through the schema', async () => {
+ const req = makeReq({ name: 'x', count: 7 });
+ const res = await validateBody(req, schema);
+ expect(res).toEqual({ name: 'x', count: 7 });
+ });
+
+ it('throws structured error on bad JSON body', async () => {
+ const req = makeReq({ name: '', count: 'not-a-number' });
+ try {
+ await validateBody(req, schema);
+ expect.fail('validateBody should have thrown');
+ } catch (err) {
+ expect(err.status).toBe(400);
+ expect(err.code).toBe('validation_error');
+ expect(err.issues.length).toBeGreaterThan(0);
+ }
+ });
+
+ it('refuses non-JSON content-type', async () => {
+ const req = makeReq({ name: 'x', count: 1 }, 'text/plain');
+ await expect(validateBody(req, schema)).rejects.toThrow(/content-type/);
+ });
+});
diff --git a/tests/api/pump-curve.test.js b/tests/api/pump-curve.test.js
new file mode 100644
index 000000000..2251ba772
--- /dev/null
+++ b/tests/api/pump-curve.test.js
@@ -0,0 +1,177 @@
+// Handler tests for /api/pump/curve and /api/pump/quote-sdk. The sdk-bridge
+// helpers are mocked at module-boundary so the test runs purely against the
+// validation + response layer — no real RPC traffic.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../../api/_lib/solana/sdk-bridge.js', () => ({
+ getBondingCurveState: vi.fn(),
+ getTokenPrice: vi.fn(),
+ getGraduationProgress: vi.fn(),
+ getBuyQuote: vi.fn(),
+ getSellQuote: vi.fn(),
+}));
+
+vi.mock('../../api/_lib/solana/rpc-fallback.js', () => ({
+ rpcFallbackFromEnv: vi.fn(() => ({
+ withFallback: async (fn) => fn({}),
+ })),
+ createRpcFallback: vi.fn(),
+ deriveWsUrl: vi.fn(),
+ RpcFallback: class {},
+}));
+
+vi.mock('../../api/_lib/zauth.js', () => ({
+ instrument: () => {},
+ drain: async () => {},
+}));
+
+vi.mock('../../api/_lib/sentry.js', () => ({
+ captureException: () => {},
+}));
+
+import {
+ getBondingCurveState, getTokenPrice, getGraduationProgress,
+ getBuyQuote, getSellQuote,
+} from '../../api/_lib/solana/sdk-bridge.js';
+
+import curveHandler from '../../api/pump/curve.js';
+import quoteSdkHandler from '../../api/pump/quote-sdk.js';
+
+const VALID_MINT = 'So11111111111111111111111111111111111111112';
+
+function makeReq({ url = '/', method = 'GET', headers = {} } = {}) {
+ return { url, method, headers };
+}
+function makeRes() {
+ const res = {
+ statusCode: 200,
+ _headers: {},
+ _body: null,
+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this._headers[k.toLowerCase()]; },
+ end(body) { this._body = body; },
+ };
+ return res;
+}
+function getJson(res) { return JSON.parse(res._body); }
+
+describe('GET /api/pump/curve', () => {
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ it('400 when mint missing', async () => {
+ const res = makeRes();
+ await curveHandler(makeReq({ url: '/api/pump/curve' }), res);
+ expect(res.statusCode).toBe(400);
+ expect(getJson(res).error).toBe('bad_mint');
+ });
+
+ it('400 when mint not base58', async () => {
+ const res = makeRes();
+ await curveHandler(makeReq({ url: '/api/pump/curve?mint=NOT_VALID!!!' }), res);
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('404 when no bonding curve found', async () => {
+ getBondingCurveState.mockResolvedValueOnce(null);
+ getTokenPrice.mockResolvedValueOnce(null);
+ getGraduationProgress.mockResolvedValueOnce(null);
+ const res = makeRes();
+ await curveHandler(makeReq({ url: `/api/pump/curve?mint=${VALID_MINT}` }), res);
+ expect(res.statusCode).toBe(404);
+ expect(getJson(res).error).toBe('no_curve');
+ });
+
+ it('200 with curve, price, graduation', async () => {
+ getBondingCurveState.mockResolvedValueOnce({
+ virtualSolReserves: '1', virtualTokenReserves: '2',
+ realSolReserves: '3', realTokenReserves: '4',
+ tokenTotalSupply: '5', complete: false,
+ creator: 'CRE', isMayhemMode: false,
+ });
+ getTokenPrice.mockResolvedValueOnce({ priceSol: '0.0001', marketCapSol: '1000' });
+ getGraduationProgress.mockResolvedValueOnce({ progressBps: 4500 });
+ const res = makeRes();
+ await curveHandler(makeReq({ url: `/api/pump/curve?mint=${VALID_MINT}` }), res);
+ expect(res.statusCode).toBe(200);
+ const body = getJson(res);
+ expect(body.mint).toBe(VALID_MINT);
+ expect(body.curve.creator).toBe('CRE');
+ expect(body.price.priceSol).toBe('0.0001');
+ expect(body.graduation.progressBps).toBe(4500);
+ expect(res.getHeader('cache-control')).toMatch(/s-maxage=10/);
+ });
+
+ it('honors network=devnet', async () => {
+ getBondingCurveState.mockResolvedValueOnce({ creator: 'X' });
+ getTokenPrice.mockResolvedValueOnce(null);
+ getGraduationProgress.mockResolvedValueOnce(null);
+ const res = makeRes();
+ await curveHandler(makeReq({ url: `/api/pump/curve?mint=${VALID_MINT}&network=devnet` }), res);
+ expect(getJson(res).network).toBe('devnet');
+ });
+});
+
+describe('GET /api/pump/quote-sdk', () => {
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ it('400 when mint invalid', async () => {
+ const res = makeRes();
+ await quoteSdkHandler(makeReq({ url: '/api/pump/quote-sdk?side=buy&amount=1' }), res);
+ expect(res.statusCode).toBe(400);
+ expect(getJson(res).error).toBe('bad_mint');
+ });
+
+ it('400 when side invalid', async () => {
+ const res = makeRes();
+ await quoteSdkHandler(makeReq({ url: `/api/pump/quote-sdk?mint=${VALID_MINT}&side=foo&amount=1` }), res);
+ expect(res.statusCode).toBe(400);
+ expect(getJson(res).error).toBe('bad_side');
+ });
+
+ it('400 when amount missing or non-positive', async () => {
+ const res = makeRes();
+ await quoteSdkHandler(makeReq({ url: `/api/pump/quote-sdk?mint=${VALID_MINT}&side=buy&amount=0` }), res);
+ expect(res.statusCode).toBe(400);
+ expect(getJson(res).error).toBe('bad_amount');
+ });
+
+ it('404 when bonding curve missing', async () => {
+ getBuyQuote.mockResolvedValueOnce(null);
+ getTokenPrice.mockResolvedValueOnce(null);
+ const res = makeRes();
+ await quoteSdkHandler(makeReq({ url: `/api/pump/quote-sdk?mint=${VALID_MINT}&side=buy&amount=1` }), res);
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('200 buy returns tokens out + impact + market context', async () => {
+ getBuyQuote.mockResolvedValueOnce({ tokens: { toString: () => '123456789' }, priceImpact: 1.25 });
+ getTokenPrice.mockResolvedValueOnce({ priceSol: '0.0002', marketCapSol: '500' });
+ const res = makeRes();
+ await quoteSdkHandler(makeReq({ url: `/api/pump/quote-sdk?mint=${VALID_MINT}&side=buy&amount=0.5` }), res);
+ expect(res.statusCode).toBe(200);
+ const body = getJson(res);
+ expect(body.side).toBe('buy');
+ expect(body.input.sol).toBe(0.5);
+ expect(body.input.lamports).toBe('500000000');
+ expect(body.output.tokens).toBe('123456789');
+ expect(body.output.tokensUi).toBeCloseTo(123.456789, 5);
+ expect(body.priceImpactPct).toBe(1.25);
+ expect(body.marketContext.priceSol).toBe('0.0002');
+ });
+
+ it('200 sell returns sol out + impact', async () => {
+ getSellQuote.mockResolvedValueOnce({ sol: { toString: () => '750000000' }, priceImpact: 0.5 });
+ getTokenPrice.mockResolvedValueOnce(null);
+ const res = makeRes();
+ await quoteSdkHandler(makeReq({ url: `/api/pump/quote-sdk?mint=${VALID_MINT}&side=sell&amount=100` }), res);
+ expect(res.statusCode).toBe(200);
+ const body = getJson(res);
+ expect(body.side).toBe('sell');
+ expect(body.input.tokens).toBe(100);
+ expect(body.input.baseUnits).toBe('100000000');
+ expect(body.output.sol).toBe(0.75);
+ expect(body.output.lamports).toBe('750000000');
+ expect(body.priceImpactPct).toBe(0.5);
+ });
+});
diff --git a/tests/embed-bridge-roundtrip.test.js b/tests/embed-bridge-roundtrip.test.js
new file mode 100644
index 000000000..eb18835b2
--- /dev/null
+++ b/tests/embed-bridge-roundtrip.test.js
@@ -0,0 +1,150 @@
+// End-to-end round trip between EmbedHostBridge (parent) and EmbedActionBridge
+// (iframe). Wires the two against an in-memory "wormhole" that mirrors the
+// browser's postMessage event with origin metadata, so we can verify:
+//
+// 1. The handshake (host:hello → agent:ready → host:ping → agent:pong) runs
+// end-to-end with strict origin targeting on every hop.
+// 2. host.speak() → iframe's protocol.emit() actually fires.
+// 3. Action events bubble back when the host subscribes.
+
+import { describe, it, expect, vi } from 'vitest';
+import { EmbedHostBridge } from '../src/embed-host-bridge.js';
+import { EmbedActionBridge } from '../src/embed-action-bridge.js';
+
+function makeProtocol() {
+ const handlers = new Set();
+ const wildcards = new Set();
+ return {
+ on(evt, fn) { (evt === '*' ? wildcards : handlers).add(fn); },
+ off(evt, fn) { (evt === '*' ? wildcards : handlers).delete(fn); },
+ emit(action) {
+ for (const fn of handlers) fn(action);
+ for (const fn of wildcards) fn(action);
+ },
+ };
+}
+
+// "Wormhole" — links the parent window's listeners to the iframe's listeners
+// and vice versa, propagating origin and source on each side.
+function wireWormhole({ hostOrigin, iframeOrigin }) {
+ const hostListeners = new Set();
+ const iframeListeners = new Set();
+
+ // Note: `event.source` from the iframe's perspective must be `iframe._win.parent`
+ // (the parent reference the iframe holds), and from the host's perspective
+ // must be `iframe.contentWindow` (what the host stored). We back both with
+ // concrete objects and re-use them as event.source on each hop.
+ const iframeContentWindow = {
+ postMessage(data, targetOrigin) {
+ // host → iframe
+ expect(targetOrigin).not.toBe('*');
+ expect(targetOrigin).toBe(iframeOrigin);
+ for (const fn of iframeListeners) {
+ fn({ source: hostParent, origin: hostOrigin, data });
+ }
+ },
+ };
+
+ const hostParent = {
+ postMessage(data, targetOrigin) {
+ // iframe → host
+ expect(targetOrigin).not.toBe('*');
+ expect(targetOrigin).toBe(hostOrigin);
+ for (const fn of hostListeners) {
+ fn({ source: iframeContentWindow, origin: iframeOrigin, data });
+ }
+ },
+ };
+
+ const iframe = {
+ tagName: 'IFRAME',
+ src: `${iframeOrigin}/agent/abc/embed`,
+ contentWindow: iframeContentWindow,
+ };
+
+ const fakeIframeWindow = {
+ _listeners: iframeListeners,
+ parent: hostParent,
+ document: { referrer: `${hostOrigin}/` },
+ location: { origin: iframeOrigin },
+ addEventListener(t, fn) { if (t === 'message') iframeListeners.add(fn); },
+ removeEventListener(t, fn) { if (t === 'message') iframeListeners.delete(fn); },
+ };
+
+ return {
+ iframe,
+ fakeIframeWindow,
+ dispatchHostMessage(ev) {
+ for (const fn of hostListeners) fn(ev);
+ },
+ hostListenersSet: hostListeners,
+ };
+}
+
+describe('Bridge — host ↔ iframe round trip', () => {
+ it('completes handshake and dispatches a speak action with strict origins', async () => {
+ const hostOrigin = 'https://host.example';
+ const iframeOrigin = 'https://iframe.example';
+ const wormhole = wireWormhole({ hostOrigin, iframeOrigin });
+
+ // Stub global window for the host bridge to register its listener on.
+ const originalWindow = globalThis.window;
+ globalThis.window = {
+ _listeners: wormhole.hostListenersSet,
+ addEventListener(t, fn) { if (t === 'message') wormhole.hostListenersSet.add(fn); },
+ removeEventListener(t, fn) { wormhole.hostListenersSet.delete(fn); },
+ };
+
+ try {
+ // Iframe side first — it announces ready as soon as start() runs.
+ const protocol = makeProtocol();
+ const speakHandler = vi.fn();
+ protocol.on('speak', speakHandler);
+
+ const action = new EmbedActionBridge({
+ protocol,
+ manifest: { id: { agentId: 'a1' } },
+ window: wormhole.fakeIframeWindow,
+ });
+
+ // Host side — must construct *before* iframe.start() so it catches the
+ // 'ready' announcement. Otherwise we'd miss the handshake step 1.
+ const host = new EmbedHostBridge({
+ iframe: wormhole.iframe,
+ agentId: 'a1',
+ allowedOrigin: iframeOrigin,
+ });
+
+ action.start();
+ await host.ready;
+
+ // Round trip a speak request.
+ await host.speak('hello world');
+ expect(speakHandler).toHaveBeenCalledTimes(1);
+ expect(speakHandler).toHaveBeenCalledWith({
+ type: 'speak',
+ payload: { text: 'hello world' },
+ });
+
+ // Subscribe and verify the action event echoes back to the host.
+ const onAction = vi.fn();
+ // 'subscribe' is a request — must round-trip; do it explicitly via the
+ // bridge's internal channel.
+ await host._request('subscribe');
+ host.on('action', onAction);
+ onAction.mockClear();
+ protocol.emit({ type: 'gesture', payload: { name: 'wave' } });
+ expect(onAction).toHaveBeenCalled();
+ const lastCall = onAction.mock.calls[onAction.mock.calls.length - 1][0];
+ expect(lastCall).toMatchObject({
+ type: 'gesture',
+ payload: { name: 'wave' },
+ });
+
+ host.destroy();
+ action.stop();
+ } finally {
+ globalThis.window = originalWindow;
+ }
+ });
+});
diff --git a/three-ws-issue.md b/three-ws-issue.md
deleted file mode 100644
index 733398e2b..000000000
--- a/three-ws-issue.md
+++ /dev/null
@@ -1,86 +0,0 @@
-# three.ws endpoint issue
-
-## Problem
-
-Your x402 endpoint at `https://three.ws/api/mcp` returns a valid 402 challenge but fails when processing payments.
-
-**What works:**
-
-```
-GET https://three.ws/api/mcp → 402 (correct)
-```
-
-Returns proper x402 payment requirements for both Solana and Base.
-
-**What fails:**
-When a client sends a signed payment via `X-PAYMENT` header, the server returns:
-
-```
-"facilitator /verify 500: No facilitator registered for scheme: exact and network: base"
-```
-
-This means your x402 middleware can issue 402 challenges but has no facilitator configured to verify incoming payments on-chain.
-
-## How to fix
-
-You need to point your x402 middleware at a working facilitator. The public Coinbase facilitator works:
-
-```
-https://facilitator.payai.network
-```
-
-### If you're using `@x402/server` (Node/Express)
-
-```js
-import { x402 } from '@x402/server';
-
-app.use(x402({
- payTo: '0x0C70c0e8453C5667739E41acdF6eC5787B8ff542',
- facilitatorUrl: 'https://facilitator.payai.network', // ← add this
- network: 'base',
- // ... your other config
-}));
-```
-
-### If you're using `@x402/next` (Next.js/Vercel)
-
-```js
-import { paymentMiddleware } from '@x402/next';
-
-export default paymentMiddleware({
- payTo: '0x0C70c0e8453C5667739E41acdF6eC5787B8ff542',
- facilitatorUrl: 'https://facilitator.payai.network', // ← add this
- network: 'base',
- // ... your other config
-});
-```
-
-### If you support multiple networks (Solana + Base)
-
-The same facilitator handles both:
-
-```js
-facilitatorUrl: 'https://facilitator.payai.network'
-```
-
-No separate setup needed — it supports `exact` scheme on both `base` and `solana`.
-
-## How we verified
-
-```bash
-# Your 402 challenge works fine
-curl -s https://three.ws/api/mcp
-# → 402 with valid accepts array (solana + base)
-
-# But payment verification fails
-curl -s -X POST https://three.ws/api/mcp \
- -H "X-PAYMENT: <signed-payment>" \
- -d '{}'
-# → "No facilitator registered for scheme: exact and network: base"
-
-# The public facilitator at payai.network works
-curl -s -X POST https://facilitator.payai.network/verify \
- -H "Content-Type: application/json" \
- -d '{"paymentPayload":{...},"paymentRequirements":{...}}'
-# → proper validation response (not "unsupported network")
-```
diff --git a/vercel.json b/vercel.json
index 34805d9fb..5753a8fe1 100644
--- a/vercel.json
+++ b/vercel.json
@@ -539,10 +539,12 @@
{
"src": "/agent/([^/]+)/embed",
"headers": {
- "content-security-policy": "frame-ancestors *",
+ "content-security-policy": "frame-ancestors *; default-src 'self' https: data: blob:; img-src 'self' https: data: blob:; media-src 'self' https: data: blob:; connect-src 'self' https: wss: data: blob:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; style-src 'self' 'unsafe-inline' https:; font-src 'self' https: data:; worker-src 'self' blob:; object-src 'none'; base-uri 'self'",
"x-content-type-options": "nosniff",
+ "x-frame-options": "ALLOWALL",
"referrer-policy": "strict-origin-when-cross-origin",
- "permissions-policy": "microphone=(self), camera=(self), xr-spatial-tracking=*"
+ "permissions-policy": "microphone=(self), camera=(self), xr-spatial-tracking=*",
+ "cross-origin-resource-policy": "cross-origin"
},
"dest": "/agent-embed.html"
},