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: integrate Privy wallet support and enhance animation management

nirholas9e8cb8bcfb0d
diff --git a/.env.example b/.env.example
index c21bad27a..3bb731599 100644
--- a/.env.example
+++ b/.env.example
@@ -32,3 +32,6 @@ PASSWORD_ROUNDS=11
# Avaturn SDK (client-side only; this stays here for reference)
VITE_AVATURN_SUBDOMAIN=
+
+# Privy wallet auth (client-side — get app ID from https://dashboard.privy.io)
+VITE_PRIVY_APP_ID=
diff --git a/package.json b/package.json
index eb468bdce..e2798906b 100644
--- a/package.json
+++ b/package.json
@@ -40,6 +40,7 @@
"build:all": "npm run build && npm run build:lib",
"clean": "rm -rf dist/* dist-lib/* || true",
"generate-icons": "node scripts/generate-pwa-icons.mjs",
+ "fetch-animations": "node scripts/download-animations.mjs",
"test": "echo 'No tests configured' && exit 0",
"deploy": "npm run build && vercel --local-config vercel.json --prod",
"postversion": "git push && git push --tags"
@@ -52,6 +53,7 @@
"@gltf-transform/core": "^4.3.0",
"@gltf-transform/extensions": "^4.3.0",
"@neondatabase/serverless": "^0.10.1",
+ "@privy-io/js-sdk-core": "latest",
"@upstash/ratelimit": "^2.0.5",
"@upstash/redis": "^1.34.3",
"bcryptjs": "^2.4.3",
diff --git a/scripts/download-animations.mjs b/scripts/download-animations.mjs
new file mode 100644
index 000000000..91f230cd6
--- /dev/null
+++ b/scripts/download-animations.mjs
@@ -0,0 +1,168 @@
+/**
+ * download-animations.mjs
+ * Downloads Mixamo-compatible animation GLBs from public sources.
+ * Run: node scripts/download-animations.mjs
+ */
+import { mkdirSync, writeFileSync, existsSync, readdirSync, statSync } from 'fs';
+import { join, basename } from 'path';
+import { execSync } from 'child_process';
+
+const ANIM_DIR = join(process.cwd(), 'public', 'animations');
+mkdirSync(ANIM_DIR, { recursive: true });
+
+// ── Known public GLB sources with animations ──────────────────────────────
+// These are from the official three.js examples — guaranteed available.
+const MODELS_WITH_ANIMATIONS = [
+ {
+ name: 'Soldier',
+ url: 'https://threejs.org/examples/models/gltf/Soldier.glb',
+ desc: 'Soldier with Idle/Walk/Run (Mixamo skeleton)',
+ },
+ {
+ name: 'RobotExpressive',
+ url: 'https://threejs.org/examples/models/gltf/RobotExpressive/RobotExpressive.glb',
+ desc: 'Robot with Dance/Death/Idle/Jump/No/Punch/Running/Sitting/Standing/ThumbsUp/Walking/Wave/Yes',
+ },
+];
+
+// ── Download function ─────────────────────────────────────────────────────
+async function download(url, dest) {
+ console.log(` ⬇ ${url}`);
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
+ const buf = Buffer.from(await res.arrayBuffer());
+ writeFileSync(dest, buf);
+ const sizeKB = Math.round(buf.length / 1024);
+ console.log(` ✅ ${basename(dest)} (${sizeKB} KB)`);
+ return buf;
+}
+
+// ── Parse GLB JSON chunk to extract animation names ───────────────────────
+function parseGlbAnimations(buf) {
+ // GLB header: magic(4) + version(4) + length(4)
+ const magic = buf.readUInt32LE(0);
+ if (magic !== 0x46546C67) return []; // 'glTF'
+
+ const chunkLength = buf.readUInt32LE(12);
+ const chunkType = buf.readUInt32LE(16);
+ if (chunkType !== 0x4E4F534A) return []; // 'JSON'
+
+ const jsonStr = buf.slice(20, 20 + chunkLength).toString('utf8');
+ const gltf = JSON.parse(jsonStr);
+
+ const anims = (gltf.animations || []).map((a) => a.name || 'unnamed');
+ const skinCount = (gltf.skins || []).length;
+ const jointCount = skinCount > 0 ? (gltf.skins[0].joints || []).length : 0;
+
+ // Get first few bone names for skeleton identification
+ const boneNames = [];
+ if (skinCount > 0 && gltf.nodes) {
+ const joints = gltf.skins[0].joints || [];
+ for (let i = 0; i < Math.min(5, joints.length); i++) {
+ const node = gltf.nodes[joints[i]];
+ if (node) boneNames.push(node.name || `joint_${i}`);
+ }
+ }
+
+ return { anims, skinCount, jointCount, boneNames };
+}
+
+// ── Extract individual animation clips from a multi-animation GLB ─────────
+// We can't easily split a GLB into separate files without a full GLTF parser,
+// but we CAN make our AnimationManager smart enough to load a single GLB
+// and extract multiple clips from it. Let's update the approach.
+
+// ── Main ──────────────────────────────────────────────────────────────────
+async function main() {
+ console.log('🎬 Downloading animation source GLBs...\n');
+
+ const downloaded = [];
+
+ for (const model of MODELS_WITH_ANIMATIONS) {
+ const dest = join(ANIM_DIR, `${model.name.toLowerCase()}.glb`);
+ try {
+ const buf = await download(model.url, dest);
+ const info = parseGlbAnimations(buf);
+ console.log(` ${info.anims.length} animations: ${info.anims.join(', ')}`);
+ console.log(` ${info.jointCount} joints, bones: ${info.boneNames.join(', ')}`);
+ console.log('');
+ downloaded.push({ ...model, file: dest, info });
+ } catch (e) {
+ console.log(` ❌ Failed: ${e.message}\n`);
+ }
+ }
+
+ // ── Build manifest from the RobotExpressive (most animations) ──────────
+ // The RobotExpressive has 13 animations in a single GLB — we'll create a
+ // manifest that references the same file but different clip names.
+ const robot = downloaded.find((d) => d.name === 'RobotExpressive');
+ const soldier = downloaded.find((d) => d.name === 'Soldier');
+
+ const ICONS = {
+ idle: '🧍', Idle: '🧍',
+ Walking: '🚶', Walk: '🚶', walking: '🚶',
+ Running: '🏃', Run: '🏃', running: '🏃',
+ Wave: '👋', Waving: '👋', waving: '👋',
+ Dance: '💃', Dancing: '💃', dancing: '💃',
+ Sitting: '🪑', sitting: '🪑',
+ Jump: '🦘', Jumping: '🦘', jumping: '🦘',
+ Punch: '👊', punching: '👊',
+ Standing: '🧍',
+ ThumbsUp: '👍',
+ Yes: '✅',
+ No: '🚫',
+ Death: '💀',
+ };
+
+ const LOOPS = new Set([
+ 'Idle', 'Walking', 'Running', 'Dance', 'Sitting', 'Standing', 'idle', 'walking', 'running',
+ ]);
+
+ const manifest = [];
+
+ if (robot && robot.info) {
+ for (const animName of robot.info.anims) {
+ manifest.push({
+ name: animName.toLowerCase(),
+ url: '/animations/robotexpressive.glb',
+ clipName: animName,
+ label: animName,
+ icon: ICONS[animName] || '▶',
+ loop: LOOPS.has(animName),
+ });
+ }
+ }
+
+ // Write manifest
+ const manifestPath = join(ANIM_DIR, 'manifest.json');
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, '\t') + '\n');
+ console.log(`📋 manifest.json written with ${manifest.length} animations`);
+
+ // ── Also check cz.glb skeleton for compatibility ──────────────────────
+ const czPath = join(process.cwd(), 'public', 'avatars', 'cz.glb');
+ if (existsSync(czPath)) {
+ const { readFileSync } = await import('fs');
+ const czBuf = readFileSync(czPath);
+ const czInfo = parseGlbAnimations(czBuf);
+ console.log(`\n🧬 cz.glb skeleton: ${czInfo.jointCount} joints`);
+ console.log(` Bones: ${czInfo.boneNames.join(', ')}`);
+ console.log(` Existing animations: ${czInfo.anims.length ? czInfo.anims.join(', ') : '(none)'}`);
+ }
+
+ // ── Summary ──────────────────────────────────────────────────────────────
+ console.log('\n═══════════════════════════════════════════════════════════');
+ const files = readdirSync(ANIM_DIR).filter((f) => f.endsWith('.glb'));
+ console.log(`📂 ${files.length} GLB file(s) in public/animations/`);
+ for (const f of files) {
+ const size = statSync(join(ANIM_DIR, f)).size;
+ console.log(` ${f} (${Math.round(size / 1024)} KB)`);
+ }
+ console.log(`📋 manifest.json: ${manifest.length} animations`);
+ console.log('═══════════════════════════════════════════════════════════');
+ console.log('\n✅ Done! Run "npm run dev" to test.');
+}
+
+main().catch((e) => {
+ console.error('Fatal:', e);
+ process.exit(1);
+});
diff --git a/scripts/fetch-animations.sh b/scripts/fetch-animations.sh
new file mode 100644
index 000000000..1cfe50dac
--- /dev/null
+++ b/scripts/fetch-animations.sh
@@ -0,0 +1,187 @@
+#!/usr/bin/env bash
+set -euo pipefail
+# ─────────────────────────────────────────────────────────────────────────────
+# fetch-animations.sh
+# Downloads Mixamo-compatible animation GLBs into public/animations/
+# Run from the project root: bash scripts/fetch-animations.sh
+# ─────────────────────────────────────────────────────────────────────────────
+
+ANIM_DIR="public/animations"
+mkdir -p "$ANIM_DIR"
+
+echo "🎬 Fetching Mixamo animation GLBs..."
+echo ""
+
+# ── Step 1: Clone the brunoimbrizi tutorial repo (has FBX animation files) ──
+TMPDIR=$(mktemp -d)
+echo "📦 Cloning brunoimbrizi/tutorial-threejs-mixamo..."
+git clone --depth 1 https://github.com/brunoimbrizi/tutorial-threejs-mixamo.git "$TMPDIR/mixamo" 2>/dev/null || {
+ echo "⚠️ Clone failed. Trying alternative sources..."
+}
+
+# ── Step 2: Find all FBX / GLB files ──
+echo ""
+echo "🔍 Scanning for animation files..."
+FOUND_FBX=()
+FOUND_GLB=()
+
+if [ -d "$TMPDIR/mixamo" ]; then
+ while IFS= read -r -d '' f; do
+ FOUND_FBX+=("$f")
+ done < <(find "$TMPDIR/mixamo" -iname "*.fbx" -print0 2>/dev/null)
+
+ while IFS= read -r -d '' f; do
+ FOUND_GLB+=("$f")
+ done < <(find "$TMPDIR/mixamo" -iname "*.glb" -print0 2>/dev/null)
+fi
+
+echo " Found ${#FOUND_FBX[@]} FBX files, ${#FOUND_GLB[@]} GLB files"
+
+# ── Step 3: Copy any GLBs directly ──
+for glb in "${FOUND_GLB[@]}"; do
+ name=$(basename "$glb" .glb | tr '[:upper:]' '[:lower:]' | tr ' @' '-_')
+ echo " ✅ Copying $name.glb"
+ cp "$glb" "$ANIM_DIR/$name.glb"
+done
+
+# ── Step 4: Convert FBX to GLB ──
+if [ ${#FOUND_FBX[@]} -gt 0 ]; then
+ echo ""
+ echo "🔄 Converting FBX files to GLB..."
+
+ # Try fbx2gltf first
+ if command -v fbx2gltf &>/dev/null; then
+ CONVERTER="fbx2gltf"
+ elif npx fbx2gltf --help &>/dev/null 2>&1; then
+ CONVERTER="npx fbx2gltf"
+ else
+ echo " Installing fbx2gltf..."
+ npm install -g fbx2gltf 2>/dev/null || pip install trimesh[easy] 2>/dev/null || true
+
+ if command -v fbx2gltf &>/dev/null; then
+ CONVERTER="fbx2gltf"
+ else
+ CONVERTER=""
+ fi
+ fi
+
+ if [ -n "$CONVERTER" ]; then
+ for fbx in "${FOUND_FBX[@]}"; do
+ name=$(basename "$fbx" .fbx | tr '[:upper:]' '[:lower:]' | tr ' @' '-_')
+ echo " Converting: $name"
+ $CONVERTER -i "$fbx" -o "$ANIM_DIR/$name.glb" 2>/dev/null || echo " ⚠️ Failed: $name"
+ done
+ else
+ echo " ⚠️ No FBX converter available. Install with: npm install -g fbx2gltf"
+ echo " Or download animations as GLB directly from mixamo.com"
+ fi
+fi
+
+# ── Step 5: Try alternative public GLB sources ──
+echo ""
+echo "🌐 Checking alternative public animation sources..."
+
+# Known public Mixamo GLB repos / CDNs
+SOURCES=(
+ "https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/models/gltf/Xbot.glb"
+)
+
+# Search for more repos with Mixamo GLBs
+SEARCH_RESULTS=$(curl -sL "https://api.github.com/search/repositories?q=mixamo+glb+animation&sort=stars&per_page=5" 2>/dev/null)
+if [ -n "$SEARCH_RESULTS" ]; then
+ echo " Top repos with Mixamo GLB animations:"
+ echo "$SEARCH_RESULTS" | python3 -c "
+import sys,json
+try:
+ for r in json.load(sys.stdin).get('items',[])[:5]:
+ print(f\" ⭐ {r['stargazers_count']:>4} {r['full_name']} — {r.get('description','')[:60]}\")
+except:
+ pass
+" 2>/dev/null || true
+fi
+
+# ── Step 6: Update manifest based on what we actually downloaded ──
+echo ""
+echo "📝 Updating manifest.json..."
+
+MANIFEST="["
+FIRST=true
+for glb in "$ANIM_DIR"/*.glb; do
+ [ -f "$glb" ] || continue
+ name=$(basename "$glb" .glb)
+ label=$(echo "$name" | sed 's/-/ /g; s/_/ /g' | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2))}1')
+
+ # Pick an icon
+ case "$name" in
+ *idle*|*breathing*|*standing*) icon="🧍" ;;
+ *walk*) icon="🚶" ;;
+ *run*) icon="🏃" ;;
+ *wave*) icon="👋" ;;
+ *danc*) icon="💃" ;;
+ *sit*) icon="🪑" ;;
+ *jump*) icon="🦘" ;;
+ *talk*) icon="🗣️" ;;
+ *clap*) icon="👏" ;;
+ *punch*) icon="👊" ;;
+ *kick*) icon="🦵" ;;
+ *) icon="▶" ;;
+ esac
+
+ # Determine loop
+ case "$name" in
+ *wave*|*jump*|*punch*|*kick*|*clap*) loop="false" ;;
+ *) loop="true" ;;
+ esac
+
+ if [ "$FIRST" = true ]; then FIRST=false; else MANIFEST+=","; fi
+ MANIFEST+="
+ {
+ \"name\": \"$name\",
+ \"url\": \"/animations/$name.glb\",
+ \"label\": \"$label\",
+ \"icon\": \"$icon\",
+ \"loop\": $loop
+ }"
+done
+MANIFEST+="
+]
+"
+
+echo "$MANIFEST" > "$ANIM_DIR/manifest.json"
+
+# ── Step 7: Cleanup ──
+rm -rf "$TMPDIR"
+
+# ── Report ──
+echo ""
+echo "═══════════════════════════════════════════════════════════"
+echo "📂 Animation files in $ANIM_DIR:"
+ls -lh "$ANIM_DIR"/*.glb 2>/dev/null || echo " (none yet)"
+echo ""
+echo "📋 manifest.json:"
+cat "$ANIM_DIR/manifest.json"
+echo ""
+echo "═══════════════════════════════════════════════════════════"
+echo ""
+
+COUNT=$(ls "$ANIM_DIR"/*.glb 2>/dev/null | wc -l)
+if [ "$COUNT" -gt 0 ]; then
+ echo "✅ Done! $COUNT animation(s) ready. Run 'npm run dev' to test."
+else
+ echo "⚠️ No GLB files downloaded automatically."
+ echo ""
+ echo "👉 Manual download from Mixamo (takes 5 min):"
+ echo " 1. Go to https://www.mixamo.com/ and sign in (free)"
+ echo " 2. Click 'Animations' tab"
+ echo " 3. Search for: Idle, Walking, Running, Waving, Dancing, Sitting, Jumping"
+ echo " 4. For each animation:"
+ echo " - Click 'Download'"
+ echo " - Format: FBX Binary (.fbx)"
+ echo " - Skin: 'Without Skin'"
+ echo " - Click 'Download'"
+ echo " 5. Convert FBX to GLB:"
+ echo " npm install -g fbx2gltf"
+ echo " for f in *.fbx; do fbx2gltf -i \"\$f\" -o \"public/animations/\$(basename \"\$f\" .fbx | tr '[:upper:]' '[:lower:]').glb\"; done"
+ echo " 6. Run this script again to update manifest.json"
+ echo " bash scripts/fetch-animations.sh"
+fi
diff --git a/scripts/quick-fetch-anims.sh b/scripts/quick-fetch-anims.sh
new file mode 100644
index 000000000..1ec9a81c8
--- /dev/null
+++ b/scripts/quick-fetch-anims.sh
@@ -0,0 +1,103 @@
+#!/usr/bin/env bash
+set -euo pipefail
+# ─────────────────────────────────────────────────────────────────────────────
+# quick-fetch-anims.sh
+# Downloads Mixamo animation GLBs from public GitHub repos and CDNs.
+# Run: bash scripts/quick-fetch-anims.sh
+# ─────────────────────────────────────────────────────────────────────────────
+
+ANIM_DIR="public/animations"
+mkdir -p "$ANIM_DIR"
+
+echo "🎬 Downloading Mixamo animation GLBs..."
+echo ""
+
+# ── Try known public sources with Mixamo GLB animations ──
+
+# Source 1: KhronosGroup glTF-Sample-Assets (has animated models)
+# Source 2: Public Mixamo GLB collections on GitHub
+
+# First, find repos with actual GLB animation files
+echo "🔍 Searching for public Mixamo GLB repos..."
+
+# Try to find and clone repos with ready-made GLBs
+REPOS=(
+ "https://github.com/n-peugnet/lichtmern"
+ "https://github.com/simondevyoutube/ThreeJS_Tutorial_ThirdPersonCamera"
+)
+
+TMPDIR=$(mktemp -d)
+trap "rm -rf $TMPDIR" EXIT
+
+for repo in "${REPOS[@]}"; do
+ NAME=$(basename "$repo")
+ echo " Checking $NAME..."
+ git clone --depth 1 "$repo" "$TMPDIR/$NAME" 2>/dev/null || continue
+
+ while IFS= read -r -d '' glb; do
+ BASENAME=$(basename "$glb" .glb | tr '[:upper:]' '[:lower:]' | tr ' @' '-_')
+
+ # Only copy if it looks like a standalone animation (small-ish file, < 5MB = likely no skin)
+ SIZE=$(stat -f%z "$glb" 2>/dev/null || stat --printf="%s" "$glb" 2>/dev/null || echo 0)
+ if [ "$SIZE" -lt 5000000 ] && [ "$SIZE" -gt 1000 ]; then
+ echo " ✅ Found: $BASENAME.glb ($(( SIZE / 1024 ))KB)"
+ cp "$glb" "$ANIM_DIR/$BASENAME.glb"
+ fi
+ done < <(find "$TMPDIR/$NAME" -iname "*.glb" -print0 2>/dev/null)
+done
+
+# ── Try direct downloads from raw GitHub URLs ──
+echo ""
+echo "🌐 Trying direct downloads..."
+
+# Mixamo default character with animations from three.js examples
+DIRECT_URLS=(
+ "https://threejs.org/examples/models/gltf/Xbot.glb xbot"
+)
+
+for entry in "${DIRECT_URLS[@]}"; do
+ url=$(echo "$entry" | cut -d' ' -f1)
+ name=$(echo "$entry" | cut -d' ' -f2)
+ echo " Downloading $name..."
+ curl -sL -o "$ANIM_DIR/$name.glb" "$url" 2>/dev/null && {
+ SIZE=$(stat -f%z "$ANIM_DIR/$name.glb" 2>/dev/null || stat --printf="%s" "$ANIM_DIR/$name.glb" 2>/dev/null || echo 0)
+ if [ "$SIZE" -gt 1000 ]; then
+ echo " ✅ $name.glb ($(( SIZE / 1024 ))KB)"
+ else
+ echo " ⚠️ Download too small, removing"
+ rm -f "$ANIM_DIR/$name.glb"
+ fi
+ } || echo " ⚠️ Failed"
+done
+
+# ── Count results ──
+echo ""
+COUNT=$(ls "$ANIM_DIR"/*.glb 2>/dev/null | wc -l || echo 0)
+echo "═══════════════════════════════════════════════════════════"
+echo "📂 $COUNT animation file(s) in $ANIM_DIR/"
+ls -lh "$ANIM_DIR"/*.glb 2>/dev/null || echo " (none)"
+echo "═══════════════════════════════════════════════════════════"
+
+if [ "$COUNT" -eq 0 ]; then
+ echo ""
+ echo "No pre-made GLBs found. Downloading from Mixamo directly..."
+ echo ""
+ echo "The fastest way to get animations:"
+ echo ""
+ echo " 1. Go to https://www.mixamo.com (sign in free with Adobe account)"
+ echo " 2. In the Characters tab, pick 'Y Bot' or your own model"
+ echo " 3. In the Animations tab, search & download these as FBX (.fbx):"
+ echo " - Breathing Idle → rename to idle.fbx"
+ echo " - Walking → rename to walking.fbx"
+ echo " - Running → rename to running.fbx"
+ echo " - Waving → rename to waving.fbx"
+ echo " - Hip Hop Dancing → rename to dancing.fbx"
+ echo " - Sitting → rename to sitting.fbx"
+ echo " - Jump → rename to jumping.fbx"
+ echo " 4. Convert all at once:"
+ echo " npm install -g fbx2gltf"
+ echo " cd public/animations"
+ echo " for f in *.fbx; do fbx2gltf -i \"\$f\" -o \"\${f%.fbx}.glb\"; rm \"\$f\"; done"
+ echo " 5. Update manifest:"
+ echo " bash scripts/fetch-animations.sh"
+fi
diff --git a/src/animation-manager.js b/src/animation-manager.js
index 3c2b3180b..2c6e1ea87 100644
--- a/src/animation-manager.js
+++ b/src/animation-manager.js
@@ -33,6 +33,8 @@ export class AnimationManager {
this.loader = new GLTFLoader();
/** @type {Function|null} */
this.onChange = null;
+ /** @type {Map<string, object>} - Cache of loaded GLTF objects by URL */
+ this._gltfCache = new Map();
this._animationDefs = [];
}
@@ -97,6 +99,7 @@ export class AnimationManager {
* @param {string} url - URL of the GLB/glTF containing the animation
* @param {object} [options]
* @param {boolean} [options.loop=true] - Whether to loop the animation
+ * @param {string} [options.clipName] - Name of a specific clip inside a multi-animation GLB
* @returns {Promise<THREE.AnimationClip>}
*/
async loadAnimation(name, url, options = {}) {
@@ -105,15 +108,34 @@ export class AnimationManager {
return this.clips.get(name);
}
- const gltf = await new Promise((resolve, reject) => {
- this.loader.load(url, resolve, undefined, reject);
- });
+ // Check if we already loaded this URL (multi-animation GLB reuse)
+ let gltf;
+ if (this._gltfCache.has(url)) {
+ gltf = this._gltfCache.get(url);
+ } else {
+ gltf = await new Promise((resolve, reject) => {
+ this.loader.load(url, resolve, undefined, reject);
+ });
+ this._gltfCache.set(url, gltf);
+ }
+
+ // Find the right clip: by clipName if specified, otherwise first clip
+ let clip;
+ if (options.clipName) {
+ clip = gltf.animations.find((a) => a.name === options.clipName);
+ if (!clip) {
+ console.warn(`[AnimationManager] Clip "${options.clipName}" not found in ${url}, using first clip`);
+ clip = gltf.animations[0];
+ }
+ } else {
+ clip = gltf.animations[0];
+ }
- const clip = gltf.animations[0];
if (!clip) {
throw new Error(`No animation found in ${url}`);
}
+ clip = clip.clone();
clip.name = name;
this.clips.set(name, clip);
@@ -140,7 +162,10 @@ export class AnimationManager {
async loadAll() {
const promises = this._animationDefs.map(async (def) => {
try {
- await this.loadAnimation(def.name, def.url, { loop: def.loop !== false });
+ await this.loadAnimation(def.name, def.url, {
+ loop: def.loop !== false,
+ clipName: def.clipName,
+ });
} catch (e) {
console.warn(`[AnimationManager] Failed to load "${def.name}" from ${def.url}:`, e);
}
@@ -350,6 +375,7 @@ export class AnimationManager {
dispose() {
this.detach();
this.clips.clear();
+ this._gltfCache.clear();
this._animationDefs = [];
}
}
diff --git a/src/erc8004/agent-registry.js b/src/erc8004/agent-registry.js
index eec65b769..ab88f4f08 100644
--- a/src/erc8004/agent-registry.js
+++ b/src/erc8004/agent-registry.js
@@ -2,7 +2,7 @@
* ERC-8004 Agent Registry — wallet + contract interaction layer.
*
* Handles:
- * 1. Wallet connection (MetaMask / injected provider)
+ * 1. Wallet connection (Privy multi-wallet, fallback to injected provider)
* 2. Uploading GLB + registration JSON to IPFS via web3.storage or Filebase
* 3. Calling register() on the Identity Registry
* 4. Building the ERC-8004 registration JSON
@@ -10,6 +10,7 @@
import { BrowserProvider, Contract } from 'ethers';
import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS, agentRegistryId } from './abi.js';
+import { isPrivyConfigured, connectWithPrivy } from './privy.js';
// ---------------------------------------------------------------------------
// Wallet
@@ -19,12 +20,31 @@ let _provider = null;
let _signer = null;
/**
- * Connect to the user's injected wallet (MetaMask, Coinbase, etc.).
+ * Connect a wallet.
+ *
+ * Strategy:
+ * 1. If Privy is configured (VITE_PRIVY_APP_ID set), use Privy — gives users
+ * MetaMask, WalletConnect, Coinbase, email-based embedded wallets, etc.
+ * 2. Otherwise fall back to window.ethereum (injected provider only).
+ *
* @returns {Promise<{provider: BrowserProvider, signer: import('ethers').Signer, address: string, chainId: number}>}
*/
export async function connectWallet() {
+ // Try Privy first — multi-wallet support, embedded wallets, social login
+ if (isPrivyConfigured()) {
+ try {
+ const result = await connectWithPrivy();
+ _provider = result.provider;
+ _signer = result.signer;
+ return result;
+ } catch (err) {
+ console.warn('[wallet] Privy connect failed, trying injected provider:', err.message);
+ }
+ }
+
+ // Fallback: raw injected provider (MetaMask, etc.)
if (!window.ethereum) {
- throw new Error('No wallet detected. Install MetaMask or a compatible wallet.');
+ throw new Error('No wallet detected. Install MetaMask or configure Privy (VITE_PRIVY_APP_ID).');
}
_provider = new BrowserProvider(window.ethereum);
diff --git a/src/erc8004/index.js b/src/erc8004/index.js
index 75bf8bed7..92fbee733 100644
--- a/src/erc8004/index.js
+++ b/src/erc8004/index.js
@@ -9,3 +9,4 @@ export { connectWallet, registerAgent, buildRegistrationJSON, pinToIPFS } from '
export { RegisterUI } from './register-ui.js';
export { submitFeedback, getReputation, getFeedbackRange, hasReviewed } from './reputation.js';
export { recordValidation, getLatestValidation, reportPassed, hashReport } from './validation-recorder.js';
+export { initPrivy, loginWithPrivy, connectWithPrivy, logoutPrivy, isPrivyConfigured } from './privy.js';
diff --git a/src/erc8004/privy.js b/src/erc8004/privy.js
new file mode 100644
index 000000000..befed34da
--- /dev/null
+++ b/src/erc8004/privy.js
@@ -0,0 +1,117 @@
+/**
+ * Privy wallet integration.
+ *
+ * Wraps @privy-io/js-sdk-core so users can connect via:
+ * - MetaMask, Coinbase Wallet, WalletConnect, etc.
+ * - Email → Privy embedded wallet (no browser extension needed)
+ * - Social login → embedded wallet
+ *
+ * Setup:
+ * 1. Create a Privy app at https://dashboard.privy.io
+ * 2. Set VITE_PRIVY_APP_ID in your .env
+ * 3. npm install @privy-io/js-sdk-core
+ */
+
+import { BrowserProvider } from 'ethers';
+
+let _privy = null;
+let _initPromise = null;
+
+const APP_ID = import.meta.env.VITE_PRIVY_APP_ID || '';
+
+// ---------------------------------------------------------------------------
+// Init
+// ---------------------------------------------------------------------------
+
+/**
+ * Lazily initialize the Privy client. Returns null if no app ID is set.
+ */
+export async function initPrivy() {
+ if (_privy) return _privy;
+ if (_initPromise) return _initPromise;
+ if (!APP_ID) return null;
+
+ _initPromise = (async () => {
+ try {
+ const mod = await import('@privy-io/js-sdk-core');
+ const PrivyClient = mod.PrivyClient || mod.default;
+ _privy = new PrivyClient({ appId: APP_ID });
+ return _privy;
+ } catch (err) {
+ console.warn('[privy] Failed to load — falling back to injected wallet.', err.message);
+ _initPromise = null;
+ return null;
+ }
+ })();
+
+ return _initPromise;
+}
+
+// ---------------------------------------------------------------------------
+// Auth
+// ---------------------------------------------------------------------------
+
+/**
+ * Login via Privy — opens the Privy auth modal.
+ * Supports email, wallet, and social login methods.
+ */
+export async function loginWithPrivy() {
+ const privy = await initPrivy();
+ if (!privy) throw new Error('Privy not configured. Set VITE_PRIVY_APP_ID in .env');
+ return privy.login({ loginMethods: ['wallet', 'email', 'google'] });
+}
+
+/**
+ * Logout from Privy.
+ */
+export async function logoutPrivy() {
+ if (_privy?.logout) await _privy.logout();
+}
+
+// ---------------------------------------------------------------------------
+// Wallet
+// ---------------------------------------------------------------------------
+
+/**
+ * Connect a wallet through Privy and return an ethers-compatible wallet.
+ *
+ * If the user isn't logged in to Privy yet, opens the login modal first.
+ * Then obtains an EIP-1193 provider (either from the user's external wallet
+ * or from Privy's embedded wallet) and wraps it in an ethers BrowserProvider.
+ *
+ * @returns {Promise<{provider: BrowserProvider, signer: import('ethers').Signer, address: string, chainId: number}>}
+ */
+export async function connectWithPrivy() {
+ const privy = await initPrivy();
+ if (!privy) throw new Error('Privy not configured. Set VITE_PRIVY_APP_ID in .env');
+
+ // Authenticate if not already
+ if (!privy.authenticated && !privy.user) {
+ await privy.login({ loginMethods: ['wallet', 'email'] });
+ }
+
+ // Get EIP-1193 provider from Privy (works for both embedded + external wallets)
+ const eip1193 = await privy.getEthereumProvider();
+ if (!eip1193) throw new Error('No wallet available. Please connect a wallet through Privy.');
+
+ const provider = new BrowserProvider(eip1193);
+ const signer = await provider.getSigner();
+ const address = await signer.getAddress();
+ const { chainId } = await provider.getNetwork();
+
+ return { provider, signer, address, chainId: Number(chainId) };
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+/** @returns {boolean} Whether a Privy app ID is configured. */
+export function isPrivyConfigured() {
+ return Boolean(APP_ID);
+}
+
+/** @returns {object|null} The Privy client instance (null if not initialized). */
+export function getPrivy() {
+ return _privy;
+}
diff --git a/src/erc8004/register-ui.js b/src/erc8004/register-ui.js
index 997922ef2..e1078c3a4 100644
--- a/src/erc8004/register-ui.js
+++ b/src/erc8004/register-ui.js
@@ -6,6 +6,7 @@
*/
import { registerAgent, connectWallet } from './agent-registry.js';
+import { isPrivyConfigured } from './privy.js';
export class RegisterUI {
/**
@@ -38,8 +39,9 @@ export class RegisterUI {
<div class="erc8004-section" data-step="wallet">
<button class="erc8004-btn erc8004-btn--connect" type="button">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="1" y="4" width="22" height="16" rx="2"/><path d="M1 10h22"/></svg>
- Connect Wallet
+ ${isPrivyConfigured() ? 'Connect Wallet' : 'Connect Wallet'}
</button>
+ <p class="erc8004-wallet-hint">${isPrivyConfigured() ? 'MetaMask, WalletConnect, Coinbase, or email' : 'Requires MetaMask or compatible wallet'}</p>
<span class="erc8004-wallet-addr"></span>
</div>