Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(x402): BSC direct-scheme payments + demo prod promotion
nirholasd8ce7b4324a0
diff --git a/api/_lib/env.js b/api/_lib/env.jsindex ade027c5b..fd2ac2e23 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -226,6 +226,25 @@ export const env = {get X402_ASSET_ADDRESS_ARBITRUM() {return opt('X402_ASSET_ADDRESS_ARBITRUM', '0xaf88d065e77c8cC2239327C5EDb3A432268e5831');},+ // Binance-Peg USD Coin (USDC) on BSC mainnet. Standard ERC-20; does NOT+ // implement EIP-3009 transferWithAuthorization, which is why BSC x402+ // payments use the contract-mediated "direct" scheme (see x402-bsc-direct.js).+ get X402_ASSET_ADDRESS_BSC() {+ return opt('X402_ASSET_ADDRESS_BSC', '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d');+ },+ // ThreeWSPayments x402 receiver contract on BSC. Client calls+ // pay(bytes32 ref) after approving USDC; the contract pulls pricePerCall+ // (1000 base units = $0.001) and emits Payment(payer, amount, ref).+ // Source + deploy tx: contracts/DEPLOYMENTS.md+ get X402_PAY_TO_BSC() {+ return opt('X402_PAY_TO_BSC', '0x00000000381f09742a30a5a49975514AeC1B72Cc');+ },+ // Optional operator EOA private key for scripts/erc8004-mint-bsc.mjs.+ // Used to register marketplace agents on the BSC IdentityRegistry. Never+ // referenced by request handlers — keep it out of the serverless surface.+ get BSC_OPERATOR_KEY() {+ return opt('BSC_OPERATOR_KEY');+ },// zauthx402 SDK — optional telemetry for x402 endpoints. When unset,// the SDK is not initialized and request monitoring is skipped.diff --git a/api/_lib/x402-bsc-direct.js b/api/_lib/x402-bsc-direct.jsnew file mode 100644index 000000000..057c927bb--- /dev/null+++ b/api/_lib/x402-bsc-direct.js@@ -0,0 +1,180 @@+// x402 "direct" scheme for BNB Smart Chain (chain 56).+//+// Standard x402 settles via a facilitator that submits an EIP-3009+// transferWithAuthorization on the user's behalf. Binance-Peg USDC on BSC+// (0x8AC76a51cc...) does NOT implement EIP-3009, and no public facilitator+// advertises eip155:56, so payments route through the on-chain+// ThreeWSPayments contract instead.+//+// Wire flow:+// 1. Server emits 402 with an accepts entry shaped like:+// { scheme: 'direct', network: 'eip155:56', payTo: <ThreeWSPayments>,+// asset: <USDC>, amount: '1000',+// extra: { contract, method: 'pay(bytes32)', eventTopic } }+// 2. The client wallet (e.g. MetaMask) calls USDC.approve(contract, amount)+// then contract.pay(ref). The payer broadcasts both txs and pays gas.+// 3. The client retries the resource with X-PAYMENT decoding to+// { scheme: 'direct', network: 'eip155:56', txHash, ref, payer? }.+// 4. verifyDirectPayment() fetches the receipt from BSC RPC and confirms:+// status=success, to=contract, Payment(payer, amount, ref) event matches,+// amount ≥ required, and txHash hasn't been consumed before.+// 5. Settlement is a no-op — the tx is already on-chain. The caller emits+// a synthetic { success, transaction: txHash, network, payer } so the+// X-PAYMENT-RESPONSE flow stays identical to the facilitator path.++import {+ createPublicClient,+ decodeEventLog,+ getAddress,+ http,+ parseAbiItem,+} from 'viem';+import { bsc } from 'viem/chains';++import { env } from './env.js';+import { X402Error } from './x402-errors.js';++export const PAYMENT_EVENT = parseAbiItem(+ 'event Payment(address indexed payer, uint256 amount, bytes32 indexed ref)',+);++// keccak256("Payment(address,uint256,bytes32)") — advertised in the 402 extra so+// clients can locate the log without parsing the contract ABI.+export const PAYMENT_EVENT_TOPIC =+ '0xd17e8b542e550255f0bc5a7b2230f59fdc24847d2003255bf6199ab46ad8f300';++// In-process anti-replay set keyed by txHash. Vercel cold starts forget, so a+// rapidly-replayed payload could briefly slip through across function instances.+// The pay() event is public on BSC, so any abuse is auditable on-chain; for the+// launch demo (where per-call cost is $0.001) this trade-off is acceptable.+// Production hardening: persist to Postgres in a (tx_hash PRIMARY KEY) table.+const seenTx = new Map();+const SEEN_TTL_MS = 10 * 60 * 1000;++function pruneSeen() {+ const now = Date.now();+ for (const [k, exp] of seenTx) if (exp < now) seenTx.delete(k);+}+function rememberTx(key) {+ pruneSeen();+ seenTx.set(key, Date.now() + SEEN_TTL_MS);+}+function isReplay(key) {+ pruneSeen();+ return seenTx.has(key);+}++let cachedClient = null;+function bscClient() {+ if (cachedClient) return cachedClient;+ const rpc = env.getRpcUrl(56) || 'https://bsc-dataseed.binance.org';+ cachedClient = createPublicClient({ chain: bsc, transport: http(rpc) });+ return cachedClient;+}++function requireHex32(value, field) {+ if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(value)) {+ throw new X402Error(+ 'invalid_payment',+ `direct payment ${field} must be a 0x-prefixed 32-byte hex string`,+ 402,+ );+ }+ return value.toLowerCase();+}++export async function verifyDirectPayment({ paymentPayload, requirement }) {+ const ref = requireHex32(paymentPayload?.ref, 'ref');+ const txHash = requireHex32(paymentPayload?.txHash, 'txHash');++ if (isReplay(txHash)) {+ throw new X402Error(+ 'invalid_payment',+ `tx ${txHash} has already been consumed by an earlier paid request`,+ 402,+ );+ }++ const client = bscClient();+ let receipt;+ try {+ receipt = await client.getTransactionReceipt({ hash: txHash });+ } catch (err) {+ // viem throws TransactionReceiptNotFoundError before the tx is mined.+ if (err.name === 'TransactionReceiptNotFoundError') {+ throw new X402Error('invalid_payment', `tx ${txHash} not yet mined`, 402);+ }+ throw new X402Error(+ 'verify_failed',+ `BSC RPC getReceipt failed: ${err.shortMessage || err.message}`,+ 502,+ );+ }+ if (!receipt) {+ throw new X402Error('invalid_payment', `tx ${txHash} not yet mined`, 402);+ }+ if (receipt.status !== 'success') {+ throw new X402Error('invalid_payment', `tx ${txHash} reverted on-chain`, 402);+ }++ const expectedTo = getAddress(requirement.payTo);+ const actualTo = receipt.to ? getAddress(receipt.to) : null;+ if (actualTo !== expectedTo) {+ throw new X402Error(+ 'invalid_payment',+ `tx.to mismatch; expected ${expectedTo}, got ${actualTo}`,+ 402,+ );+ }++ let payer = null;+ let amount = 0n;+ for (const log of receipt.logs) {+ if (getAddress(log.address) !== expectedTo) continue;+ try {+ const decoded = decodeEventLog({+ abi: [PAYMENT_EVENT],+ data: log.data,+ topics: log.topics,+ });+ if (decoded.eventName !== 'Payment') continue;+ const eventRef = String(decoded.args.ref).toLowerCase();+ if (eventRef !== ref) continue;+ payer = getAddress(decoded.args.payer);+ amount = decoded.args.amount;+ break;+ } catch {+ // Not the Payment event — keep scanning.+ }+ }+ if (!payer) {+ throw new X402Error(+ 'invalid_payment',+ `no Payment(*, *, ref=${ref}) event found in tx ${txHash} on ${expectedTo}`,+ 402,+ );+ }++ const required = BigInt(requirement.amount);+ if (amount < required) {+ throw new X402Error(+ 'invalid_payment',+ `paid amount ${amount.toString()} is below required ${required.toString()}`,+ 402,+ );+ }++ rememberTx(txHash);+ return { isValid: true, payer, txHash, amount: amount.toString() };+}++// Synthesise the same shape PayAI/CDP /settle returns, so callers in+// x402-spec.js can emit X-PAYMENT-RESPONSE identically.+export function settleDirectPayment({ verified, requirement }) {+ return {+ success: true,+ transaction: verified.txHash,+ network: requirement.network,+ payer: verified.payer,+ };+}diff --git a/api/_lib/x402-errors.js b/api/_lib/x402-errors.jsnew file mode 100644index 000000000..2eca2d1dc--- /dev/null+++ b/api/_lib/x402-errors.js@@ -0,0 +1,10 @@+// Shared X402Error type, kept in its own module so that the BSC direct-payment+// verifier (api/_lib/x402-bsc-direct.js) can throw it without creating an+// import cycle with x402-spec.js (which itself imports the verifier).+export class X402Error extends Error {+ constructor(code, message, status = 402) {+ super(message);+ this.code = code;+ this.status = status;+ }+}diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.jsindex f5d4b5506..e25e6f6b2 100644--- a/api/_lib/x402-paid-endpoint.js+++ b/api/_lib/x402-paid-endpoint.js@@ -14,8 +14,10 @@import { cors, error } from './http.js';import { env } from './env.js';+import { PAYMENT_EVENT_TOPIC as BSC_PAYMENT_EVENT_TOPIC } from './x402-bsc-direct.js';import {NETWORK_BASE_MAINNET,+ NETWORK_BSC_MAINNET,NETWORK_SOLANA_MAINNET,X402Error,encodePaymentResponseHeader,@@ -28,6 +30,8 @@ import {const NETWORK_ALIASES = {base: NETWORK_BASE_MAINNET,'base-mainnet': NETWORK_BASE_MAINNET,+ bsc: NETWORK_BSC_MAINNET,+ 'bsc-mainnet': NETWORK_BSC_MAINNET,solana: NETWORK_SOLANA_MAINNET,'solana-mainnet': NETWORK_SOLANA_MAINNET,};@@ -64,6 +68,24 @@ function buildAccept(network, priceAtomics, resourceUrl) {extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },};}+ if (network === NETWORK_BSC_MAINNET) {+ // Contract-mediated "direct" scheme — the client calls+ // ThreeWSPayments.pay(bytes32) from their own wallet (see x402-bsc-direct.js).+ return {+ ...common,+ scheme: 'direct',+ network: NETWORK_BSC_MAINNET,+ payTo: env.X402_PAY_TO_BSC,+ asset: env.X402_ASSET_ADDRESS_BSC,+ extra: {+ name: 'Binance-Peg USD Coin',+ decimals: 6,+ contract: env.X402_PAY_TO_BSC,+ method: 'pay(bytes32)',+ eventTopic: BSC_PAYMENT_EVENT_TOPIC,+ },+ };+ }throw new X402Error('unsupported_network', `paidEndpoint: unsupported network ${network}`, 500);}@@ -73,6 +95,7 @@ function buildRequirements({ priceAtomics, networks, resourceUrl }) {const net = resolveNetwork(name);if (net === NETWORK_BASE_MAINNET && !env.X402_PAY_TO_BASE) continue;if (net === NETWORK_SOLANA_MAINNET && !env.X402_PAY_TO_SOLANA) continue;+ if (net === NETWORK_BSC_MAINNET && !env.X402_PAY_TO_BSC) continue;out.push(buildAccept(net, priceAtomics, resourceUrl));}if (!out.length) {@@ -167,6 +190,7 @@ export function paidEndpoint(spec) {settled = await settlePayment({paymentPayload: verified.paymentPayload,requirement: verified.requirement,+ directVerified: verified.directVerified,});} catch (err) {return error(res, err.status || 502, err.code || 'settle_failed', err.message);diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.jsindex 1e8bcd60c..2249f8f88 100644--- a/api/_lib/x402-spec.js+++ b/api/_lib/x402-spec.js@@ -34,6 +34,14 @@import { createCdpAuthHeaders } from '@coinbase/x402';import { env } from './env.js';+import { X402Error } from './x402-errors.js';+import {+ PAYMENT_EVENT_TOPIC as BSC_PAYMENT_EVENT_TOPIC,+ settleDirectPayment,+ verifyDirectPayment,+} from './x402-bsc-direct.js';++export { X402Error };export const X402_VERSION = 2;@@ -43,6 +51,7 @@ export const NETWORK_BASE_MAINNET = 'eip155:8453';export const NETWORK_BASE_SEPOLIA = 'eip155:84532';export const NETWORK_ARBITRUM_MAINNET = 'eip155:42161';export const NETWORK_OPTIMISM_MAINNET = 'eip155:10';+export const NETWORK_BSC_MAINNET = 'eip155:56';export const NETWORK_SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';export const NETWORK_SOLANA_DEVNET = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';@@ -54,13 +63,10 @@ const CDP_EVM_NETWORKS = new Set([NETWORK_OPTIMISM_MAINNET,]);-export class X402Error extends Error {- constructor(code, message, status = 402) {- super(message);- this.code = code;- this.status = status;- }-}+// Networks that settle via on-chain pay(bytes32) calls rather than a+// facilitator (see x402-bsc-direct.js). The accept entry uses scheme='direct'+// and the client is responsible for broadcasting the tx + paying gas.+const DIRECT_NETWORKS = new Set([NETWORK_BSC_MAINNET]);// One v2 PaymentRequirements entry per supported network. Base mainnet first// — agentic.market's validator inspects the first entry for its supported-network@@ -100,6 +106,25 @@ export function paymentRequirements(resourceUrl) {extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },});}+ if (env.X402_PAY_TO_BSC) {+ // BSC uses the contract-mediated "direct" scheme — see x402-bsc-direct.js+ // for the wire flow. Clients call ThreeWSPayments.pay(ref) themselves and+ // hand back the resulting tx hash via the X-PAYMENT header.+ out.push({+ ...common,+ scheme: 'direct',+ network: NETWORK_BSC_MAINNET,+ payTo: env.X402_PAY_TO_BSC,+ asset: env.X402_ASSET_ADDRESS_BSC,+ extra: {+ name: 'Binance-Peg USD Coin',+ decimals: 6,+ contract: env.X402_PAY_TO_BSC,+ method: 'pay(bytes32)',+ eventTopic: BSC_PAYMENT_EVENT_TOPIC,+ },+ });+ }return out;}@@ -123,6 +148,12 @@ function facilitatorFor(network) {network === 'solana')return { url: env.X402_FACILITATOR_URL_SOLANA, token: env.X402_FACILITATOR_TOKEN_SOLANA };+ // BSC settles via on-chain pay() — no facilitator needed. The {direct:true}+ // marker tells verifyPayment/settlePayment to bypass HTTP entirely and call+ // the local verifier in x402-bsc-direct.js.+ if (DIRECT_NETWORKS.has(network) || network === 'bsc') {+ return { direct: true };+ }// EVM mainnets supported by Coinbase CDP. When CDP keys are set, route all// of them through CDP (required for CDP Bazaar / agentic.market — only// endpoints whose first verify+settle is processed by CDP get cataloged).@@ -339,11 +370,24 @@ function selectRequirement(paymentPayload, allRequirements) {}// Verify a base64 X-PAYMENT header against the offered requirements.-// Returns { paymentPayload, requirement, payer } on success.+// Returns { paymentPayload, requirement, payer, directVerified? } on success.+// For direct-scheme networks (BSC), the on-chain verification result is stashed+// on `directVerified` so settlePayment can synthesise a response without+// re-hitting the RPC.export async function verifyPayment({ paymentHeader, requirements }) {const all = Array.isArray(requirements) ? requirements : [requirements];const paymentPayload = decodePaymentHeader(paymentHeader);const requirement = selectRequirement(paymentPayload, all);+ const config = facilitatorFor(requirement.network);+ if (config.direct) {+ const directVerified = await verifyDirectPayment({ paymentPayload, requirement });+ return {+ paymentPayload,+ requirement,+ payer: directVerified.payer,+ directVerified,+ };+ }const result = await callFacilitator(requirement.network, '/verify', {x402Version: X402_VERSION,paymentPayload,@@ -360,7 +404,20 @@ export async function verifyPayment({ paymentHeader, requirements }) {}// Settle the verified payment on-chain via the matching facilitator.-export async function settlePayment({ paymentPayload, requirement }) {+// For direct-scheme networks (BSC), the user already broadcast the tx during+// verifyPayment — settle just synthesises the response shape callers expect.+export async function settlePayment({ paymentPayload, requirement, directVerified }) {+ const config = facilitatorFor(requirement.network);+ if (config.direct) {+ if (!directVerified) {+ throw new X402Error(+ 'settle_failed',+ 'direct-scheme settle requires the verify step to run first',+ 500,+ );+ }+ return settleDirectPayment({ verified: directVerified, requirement });+ }const result = await callFacilitator(requirement.network, '/settle', {x402Version: X402_VERSION,paymentPayload,diff --git a/public/demos/brain.html b/public/demos/brain.htmlindex 083137d44..93f90f3ef 100644--- a/public/demos/brain.html+++ b/public/demos/brain.html@@ -3,9 +3,13 @@<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />- <title>Multi-LLM brain · three.ws lab</title>+ <title>Multi-LLM brain · three.ws</title><meta name="description" content="Send the same prompt to Claude, GPT, Qwen on Alibaba DashScope, Qwen3-Coder on ModelScope, and Llama on Groq. Compare streaming responses, latency, and token usage side-by-side." />- <meta name="robots" content="noindex" />+ <link rel="canonical" href="https://three.ws/brain" />+ <meta property="og:title" content="Multi-LLM brain · three.ws" />+ <meta property="og:description" content="Compare Claude, GPT, Qwen, ModelScope, and Groq side-by-side. Same prompt, real streaming, real token counts." />+ <meta property="og:url" content="https://three.ws/brain" />+ <meta name="twitter:card" content="summary_large_image" /><link rel="stylesheet" href="/style.css" /><link rel="stylesheet" href="/nav.css" /><style>@@ -49,7 +53,7 @@<header><div id="nav-container"></div></header><main class="stage">- <p class="crumb"><a href="/demos/">← lab</a></p>+ <p class="crumb"><a href="/">three.ws</a> · <a href="/demos/">labs</a> · brain</p><h1>Multi-LLM brain</h1><p class="sub">Send the same prompt to multiple providers at once. Side-by-side streamingdiff --git a/public/demos/index.html b/public/demos/index.htmlindex 280a967e8..d77b4099d 100644--- a/public/demos/index.html+++ b/public/demos/index.html@@ -46,6 +46,7 @@}.demo-status.live { background: rgba(214,255,61,0.12); color: #d6ff3d; border: 1px solid rgba(214,255,61,0.35); }.demo-status.beta { background: rgba(255,184,77,0.12); color: #ffb84d; border: 1px solid rgba(255,184,77,0.35); }+ .demo-status.prod { background: rgba(154,212,255,0.12); color: #9ad4ff; border: 1px solid rgba(154,212,255,0.35); }.warning {margin: 32px 0 0;padding: 14px 16px;@@ -86,25 +87,25 @@<p>Drop-in <code><agent-3d></code> web component loaded from the npm SDK bundle, plus the programmatic <code>AvatarCreator</code> iframe.</p><span class="demo-status beta">Beta</span></a>- <a class="demo-card" href="/demos/lipsync-mic.html">- <h2>Audio-driven lipsync</h2>+ <a class="demo-card" href="/lipsync/mic">+ <h2>Audio-driven lipsync → <code>/lipsync/mic</code></h2><p>Feed live mic audio through the viseme analyser and watch the avatar's mouth track your voice in real time.</p>- <span class="demo-status live">Live</span>+ <span class="demo-status prod">In prod</span></a>- <a class="demo-card" href="/demos/brain.html">- <h2>Multi-LLM brain</h2>+ <a class="demo-card" href="/brain">+ <h2>Multi-LLM brain → <code>/brain</code></h2><p>Send the same prompt to Claude, GPT, Qwen on Alibaba DashScope, Qwen3-Coder on ModelScope, and Llama on Groq. Side-by-side streaming, latency, and token usage.</p>- <span class="demo-status live">Live</span>+ <span class="demo-status prod">In prod</span></a>- <a class="demo-card" href="/demos/lipsync-tts.html">- <h2>TTS-driven lipsync</h2>+ <a class="demo-card" href="/lipsync">+ <h2>TTS-driven lipsync → <code>/lipsync</code></h2><p>Type any text, stream it through OpenAI TTS, and the avatar's mouth animates in real time via <code>wawa-lipsync</code> viseme detection.</p>- <span class="demo-status live">Live</span>+ <span class="demo-status prod">In prod</span></a>- <a class="demo-card" href="/demos/walkaround.html">- <h2>3D walkaround</h2>+ <a class="demo-card" href="/walkaround">+ <h2>3D walkaround → <code>/walkaround</code></h2><p>WASD + mobile joystick navigation with real <strong>Rapier</strong> physics and <strong>Recast</strong> navmesh. Click the ground to autopilot your agent there.</p>- <span class="demo-status live">Live</span>+ <span class="demo-status prod">In prod</span></a><a class="demo-card" href="/demos/erc8004.html"><h2>ERC-8004 registry browser</h2>diff --git a/public/demos/lipsync-mic.html b/public/demos/lipsync-mic.htmlindex 7e6babfef..8b488afca 100644--- a/public/demos/lipsync-mic.html+++ b/public/demos/lipsync-mic.html@@ -3,8 +3,13 @@<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />- <title>Audio-driven lipsync · three.ws lab</title>- <meta name="robots" content="noindex" />+ <title>Audio-driven lipsync · three.ws</title>+ <meta name="description" content="Real-time mic → viseme analyser → avatar morph targets. The exact pipeline that drives ElevenLabs-streamed TTS in three.ws chat, sourced from your microphone." />+ <link rel="canonical" href="https://three.ws/lipsync/mic" />+ <meta property="og:title" content="Audio-driven lipsync · three.ws" />+ <meta property="og:description" content="Speak into your mic and watch the avatar's mouth track your voice in real time." />+ <meta property="og:url" content="https://three.ws/lipsync/mic" />+ <meta name="twitter:card" content="summary_large_image" /><link rel="stylesheet" href="/style.css" /><link rel="stylesheet" href="/nav.css" /><style>@@ -52,7 +57,7 @@<header><div id="nav-container"></div></header><main class="stage">- <p class="crumb"><a href="/demos">← lab</a></p>+ <p class="crumb"><a href="/">three.ws</a> · <a href="/lipsync">lipsync</a> · mic</p><h1>Audio-driven lipsync</h1><p class="sub">Real-time test of the three.ws viseme analyserdiff --git a/public/demos/lipsync-tts.html b/public/demos/lipsync-tts.htmlindex d385d7cab..f75bb7b17 100644--- a/public/demos/lipsync-tts.html+++ b/public/demos/lipsync-tts.html@@ -3,9 +3,13 @@<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />- <title>TTS-driven lipsync · three.ws lab</title>+ <title>TTS-driven lipsync · three.ws</title><meta name="description" content="Type text, stream it through OpenAI TTS, and watch a 3D avatar's mouth animate in real time via wawa-lipsync viseme detection. No server-side audio processing." />- <meta name="robots" content="noindex" />+ <link rel="canonical" href="https://three.ws/lipsync" />+ <meta property="og:title" content="TTS-driven lipsync · three.ws" />+ <meta property="og:description" content="Type any text → OpenAI TTS → in-browser viseme detection → 3D avatar lipsync. Zero server-side audio processing." />+ <meta property="og:url" content="https://three.ws/lipsync" />+ <meta name="twitter:card" content="summary_large_image" /><link rel="stylesheet" href="/style.css" /><link rel="stylesheet" href="/nav.css" /><style>@@ -42,7 +46,7 @@<header><div id="nav-container"></div></header><main class="stage">- <p class="crumb"><a href="/demos/">← lab</a></p>+ <p class="crumb"><a href="/">three.ws</a> · lipsync · <a href="/lipsync/mic">mic mode</a></p><h1>TTS-driven lipsync</h1><p class="sub">Type any text, stream it through OpenAI TTS, and the avatar's mouth animates indiff --git a/public/demos/walkaround.html b/public/demos/walkaround.htmlindex 16ed40848..67cd19510 100644--- a/public/demos/walkaround.html+++ b/public/demos/walkaround.html@@ -3,9 +3,13 @@<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />- <title>3D walkaround · three.ws lab</title>+ <title>3D walkaround · three.ws</title><meta name="description" content="A WASD + mobile-joystick walkaround scene with real physics (Rapier) and navmesh pathfinding (Recast). Click anywhere on the ground to autopilot your agent there." />- <meta name="robots" content="noindex" />+ <link rel="canonical" href="https://three.ws/walkaround" />+ <meta property="og:title" content="3D walkaround · three.ws" />+ <meta property="og:description" content="WASD + joystick walkaround scene with real Rapier physics and Recast navmesh pathfinding. Click ground to autopilot." />+ <meta property="og:url" content="https://three.ws/walkaround" />+ <meta name="twitter:card" content="summary_large_image" /><link rel="stylesheet" href="/style.css" /><link rel="stylesheet" href="/nav.css" /><style>@@ -38,7 +42,7 @@<body><div class="stage"><header class="head">- <a href="/demos/">← lab</a>+ <a href="/">three.ws</a><h1>3D walkaround</h1><div class="spacer"></div><button id="toggleNavmesh">Show navmesh</button>diff --git a/public/nav.html b/public/nav.htmlindex c0b86096b..5efc2df94 100644--- a/public/nav.html+++ b/public/nav.html@@ -48,6 +48,9 @@>Pay<span class="nav-badge">NEW</span></a></li>+ <li class="nav-item" role="none">+ <a href="/marketplace" role="menuitem">Marketplace</a>+ </li><li class="nav-item nav-has-menu" role="none"><buttontype="button"@@ -169,9 +172,21 @@></li><li role="none">- <a href="/marketplace" role="menuitem"- ><span class="nav-mi-title">Marketplace</span- ><span class="nav-mi-sub">Browse agents · buy · list</span></a+ <a href="/walkaround" role="menuitem"+ ><span class="nav-mi-title">3D Walkaround<span class="nav-pill" aria-hidden="true">NEW</span></span+ ><span class="nav-mi-sub">WASD + joystick · Rapier physics · Recast navmesh</span></a+ >+ </li>+ <li role="none">+ <a href="/brain" role="menuitem"+ ><span class="nav-mi-title">Multi-LLM brain<span class="nav-pill" aria-hidden="true">NEW</span></span+ ><span class="nav-mi-sub">Claude · GPT · Qwen · ModelScope · Groq, side-by-side</span></a+ >+ </li>+ <li role="none">+ <a href="/lipsync" role="menuitem"+ ><span class="nav-mi-title">Lipsync<span class="nav-pill" aria-hidden="true">NEW</span></span+ ><span class="nav-mi-sub">TTS or mic → in-browser viseme → avatar mouth</span></a></li><li role="none">diff --git a/public/pay/index.html b/public/pay/index.htmlindex 02909bc53..971468c5e 100644--- a/public/pay/index.html+++ b/public/pay/index.html@@ -579,6 +579,91 @@.gen-modal .cancel { color: var(--muted); margin-top: 8px; font-size: 12px; text-align: center; cursor: pointer; }.gen-modal .cancel:hover { color: var(--text); }.gen-modal .spinner { font-size: 18px; animation: spin 1.2s linear infinite; }++ /* Chain tabs — Solana (default) vs BNB Chain. Toggles which payment surface+ the .chat section renders. */+ .chain-tabs {+ display: flex; gap: 8px;+ padding: 10px 28px 0;+ border-bottom: 1px solid var(--border);+ }+ .chain-tab {+ background: transparent; border: 1px solid transparent;+ color: var(--muted); font-size: 13px; font-weight: 600;+ padding: 8px 14px; border-radius: 8px 8px 0 0;+ cursor: pointer; transition: color .15s, background .15s, border-color .15s;+ border-bottom: 1px solid var(--border);+ margin-bottom: -1px;+ }+ .chain-tab:hover { color: var(--text); }+ .chain-tab.active {+ color: var(--text);+ background: var(--panel);+ border-color: var(--border-strong) var(--border-strong) var(--panel);+ }+ .chain-tab .chip {+ font-family: var(--mono); font-size: 10px; color: var(--muted);+ margin-left: 6px; opacity: .7;+ }++ /* BSC panel — sits inside section.chat as a sibling of .conv + .composer.+ Hidden by default; .active flips display:flex when the BSC tab is chosen. */+ .bsc-panel { display: none; flex-direction: column; min-height: 0; flex: 1; }+ .bsc-panel.active { display: flex; }+ .bsc-panel .bsc-header {+ display: flex; align-items: center; justify-content: space-between;+ gap: 16px; padding: 18px 28px 8px;+ }+ .bsc-panel .bsc-header strong { font-size: 15px; }+ .bsc-panel .bsc-sub { font-size: 12px; color: var(--muted); margin-top: 4px; }+ .bsc-connect {+ background: linear-gradient(135deg, #F3BA2F, #E89C0C);+ color: #1a1d29; font-weight: 700; font-size: 13px;+ padding: 9px 16px; border-radius: 8px; border: none;+ cursor: pointer; transition: filter .15s;+ white-space: nowrap;+ }+ .bsc-connect:hover { filter: brightness(1.08); }+ .bsc-connect:disabled { opacity: .5; cursor: not-allowed; }+ .bsc-info {+ display: flex; flex-wrap: wrap; gap: 18px;+ padding: 6px 28px 12px;+ font-size: 12px; color: var(--muted);+ }+ .bsc-info code { color: var(--text); font-family: var(--mono); }+ .bsc-quick {+ display: flex; flex-wrap: wrap; gap: 8px;+ padding: 4px 28px 14px;+ border-bottom: 1px solid var(--border);+ }+ .bsc-chip {+ background: var(--panel-2); color: var(--text);+ border: 1px solid var(--border); border-radius: 999px;+ padding: 6px 12px; font-size: 12px; font-family: var(--mono);+ cursor: pointer; transition: border-color .15s;+ }+ .bsc-chip:hover { border-color: var(--accent-2); }+ .bsc-log {+ flex: 1; overflow-y: auto;+ padding: 18px 28px;+ display: flex; flex-direction: column; gap: 10px;+ }+ .bsc-step {+ font-size: 13px; line-height: 1.55;+ padding: 10px 14px;+ background: var(--panel); border: 1px solid var(--border);+ border-radius: 10px;+ word-break: break-all;+ }+ .bsc-step.muted { color: var(--muted); border-style: dashed; }+ .bsc-step.err { border-color: var(--red); color: #fca5a5; }+ .bsc-step.result { background: var(--bg-2); }+ .bsc-step.result pre {+ margin: 0; font-size: 11.5px; line-height: 1.5;+ color: var(--text); white-space: pre-wrap; word-break: break-all;+ }+ .bsc-step code { font-family: var(--mono); font-size: 11.5px; }+ .bsc-step a { color: var(--accent-2); }</style></head><body>@@ -611,6 +696,10 @@<main><section class="chat">+ <div class="chain-tabs" id="chainTabs">+ <button class="chain-tab active" data-chain="solana">⚡ Solana <span class="chip">USDC</span></button>+ <button class="chain-tab" data-chain="bsc">⛓ BNB Chain <span class="chip">USDC</span></button>+ </div><div class="agent-bar" id="agentBar"><span class="label">agent wallet</span><div class="agent-list" id="agentList">@@ -631,7 +720,7 @@</div></div></div>- <div class="composer">+ <div class="composer" id="composer"><div class="quick" id="quick"><button data-cmd="tools/list">/list_tools</button><button data-cmd="validate_model:demo">/validate DamagedHelmet.glb</button>@@ -644,6 +733,31 @@<button id="send" class="send">Pay & Run</button></div></div>++ <div class="bsc-panel" id="bscPanel">+ <div class="bsc-header">+ <div>+ <strong>Pay on BNB Smart Chain</strong>+ <div class="bsc-sub">You sign the payment in MetaMask. <code>ThreeWSPayments.pay($0.001 USDC)</code> on-chain — no facilitator, no server-held key.</div>+ </div>+ <button class="bsc-connect" id="bscConnect">Connect MetaMask</button>+ </div>+ <div class="bsc-info" id="bscInfo" style="display:none">+ <span>wallet <code id="bscAddr">…</code></span>+ <span>USDC <code id="bscBal">…</code></span>+ <span>allowance <code id="bscAllow">…</code></span>+ <span>contract <a target="_blank" rel="noopener" href="https://bscscan.com/address/0x00000000381f09742a30a5a49975514AeC1B72Cc"><code>0x00000000…1B72Cc</code></a></span>+ </div>+ <div class="bsc-quick">+ <button class="bsc-chip" data-bsctool="validate_model">/validate DamagedHelmet.glb</button>+ <button class="bsc-chip" data-bsctool="inspect_model">/inspect DamagedHelmet.glb</button>+ <button class="bsc-chip" data-bsctool="search_public_avatars">/search_avatars</button>+ <button class="bsc-chip" data-bsctool="tools_list">/list_tools</button>+ </div>+ <div class="bsc-log" id="bscLog">+ <div class="bsc-step muted">Connect MetaMask, then click a tool above. You'll sign two transactions: one <code>approve</code> (once per wallet) and one <code>pay(bytes32)</code> per MCP call. The page then POSTs <code>/api/mcp</code> with an <code>X-PAYMENT</code> header proving the on-chain payment.</div>+ </div>+ </div></section><aside class="status">@@ -1330,5 +1444,255 @@ if (params.get('list') === '1') queueMicrotask(() => run({ tool: 'tools/list', apromptEl.focus();</script>+<script type="module">+// ---- BNB Smart Chain x402 "direct" flow --------------------------------+//+// The Solana script above pays from a server-held demo wallet. On BSC the+// browser user is the payer: MetaMask signs USDC.approve + ThreeWSPayments.pay,+// then the page POSTs /api/mcp with the resulting tx as an X-PAYMENT header.+// Server-side verification happens in api/_lib/x402-bsc-direct.js.++const BSC_CHAIN_HEX = '0x38'; // 56+const BSC_USDC = '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d';+const BSC_PAYMENTS = '0x00000000381f09742a30a5a49975514AeC1B72Cc';+const PRICE = 1000n; // $0.001 USDC (6 decimals)++const $b = (id) => document.getElementById(id);+const conv_ = $b('conv');+const composer_ = $b('composer');+const agentBar_ = $b('agentBar');+const bscPanel_ = $b('bscPanel');++function activateChain(chain) {+ document.querySelectorAll('.chain-tab').forEach((b) => {+ b.classList.toggle('active', b.dataset.chain === chain);+ });+ const bsc = chain === 'bsc';+ if (agentBar_) agentBar_.style.display = bsc ? 'none' : '';+ if (conv_) conv_.style.display = bsc ? 'none' : '';+ if (composer_) composer_.style.display = bsc ? 'none' : '';+ bscPanel_.classList.toggle('active', bsc);+}++document.querySelectorAll('.chain-tab').forEach((btn) => {+ btn.addEventListener('click', () => activateChain(btn.dataset.chain));+});++// ---- low-level wallet helpers -----------------------------------------++let bscAccount = null;++async function eth(method, params = []) {+ if (!window.ethereum) {+ throw new Error('MetaMask not detected. Install it at metamask.io or use a wallet extension that exposes window.ethereum.');+ }+ return await window.ethereum.request({ method, params });+}++async function ensureBscNetwork() {+ try {+ await eth('wallet_switchEthereumChain', [{ chainId: BSC_CHAIN_HEX }]);+ } catch (err) {+ // 4902 = chain not added to the wallet.+ if (err && (err.code === 4902 || err.code === -32603)) {+ await eth('wallet_addEthereumChain', [{+ chainId: BSC_CHAIN_HEX,+ chainName: 'BNB Smart Chain',+ nativeCurrency: { name: 'BNB', symbol: 'BNB', decimals: 18 },+ rpcUrls: ['https://bsc-dataseed.binance.org'],+ blockExplorerUrls: ['https://bscscan.com'],+ }]);+ } else {+ throw err;+ }+ }+}++function pad32Addr(addr) {+ return addr.toLowerCase().replace(/^0x/, '').padStart(64, '0');+}++async function readUsdcBalance(account) {+ const data = '0x70a08231' + pad32Addr(account);+ const raw = await eth('eth_call', [{ to: BSC_USDC, data }, 'latest']);+ return BigInt(raw && raw !== '0x' ? raw : '0x0');+}++async function readUsdcAllowance(owner, spender) {+ const data = '0xdd62ed3e' + pad32Addr(owner) + pad32Addr(spender);+ const raw = await eth('eth_call', [{ to: BSC_USDC, data }, 'latest']);+ return BigInt(raw && raw !== '0x' ? raw : '0x0');+}++function fmtUsdc(n) {+ const s = n.toString().padStart(7, '0');+ return s.slice(0, -6) + '.' + s.slice(-6, -2);+}++async function refreshBalances() {+ if (!bscAccount) return;+ try {+ const [bal, allow] = await Promise.all([+ readUsdcBalance(bscAccount),+ readUsdcAllowance(bscAccount, BSC_PAYMENTS),+ ]);+ $b('bscBal').textContent = '$' + fmtUsdc(bal) + ' USDC';+ $b('bscAllow').textContent = allow >= PRICE ? '✓ ready' : 'needs approve';+ } catch (err) {+ $b('bscBal').textContent = '—';+ $b('bscAllow').textContent = '—';+ }+}++function logStep(html, kind = 'info') {+ const div = document.createElement('div');+ div.className = 'bsc-step' + (kind !== 'info' ? ' ' + kind : '');+ div.innerHTML = html;+ $b('bscLog').appendChild(div);+ div.scrollIntoView({ behavior: 'smooth', block: 'end' });+ return div;+}++async function waitForReceipt(txHash, timeoutMs = 60000) {+ const started = Date.now();+ while (Date.now() - started < timeoutMs) {+ const rcpt = await eth('eth_getTransactionReceipt', [txHash]);+ if (rcpt) {+ if (rcpt.status !== '0x1') throw new Error(`tx ${txHash} reverted on-chain`);+ return rcpt;+ }+ await new Promise((r) => setTimeout(r, 1500));+ }+ throw new Error(`tx ${txHash} did not confirm within ${timeoutMs / 1000}s — check BscScan.`);+}++async function bscConnect() {+ const accts = await eth('eth_requestAccounts');+ bscAccount = accts && accts[0];+ if (!bscAccount) throw new Error('No account returned from wallet');+ await ensureBscNetwork();+ const short = bscAccount.slice(0, 6) + '…' + bscAccount.slice(-4);+ $b('bscAddr').textContent = short;+ $b('bscConnect').style.display = 'none';+ $b('bscInfo').style.display = '';+ logStep(`🔗 Connected as <code>${short}</code> on BNB Smart Chain.`);+ await refreshBalances();+}++async function approveIfNeeded() {+ const allow = await readUsdcAllowance(bscAccount, BSC_PAYMENTS);+ if (allow >= PRICE) return false;+ logStep('🔑 Approving USDC for ThreeWSPayments (one-time per wallet)…');+ // approve(spender, type(uint256).max)+ const data = '0x095ea7b3' + pad32Addr(BSC_PAYMENTS) + 'f'.repeat(64);+ const txHash = await eth('eth_sendTransaction', [{+ from: bscAccount, to: BSC_USDC, data,+ }]);+ logStep(`📝 Approve tx: <a target="_blank" rel="noopener" href="https://bscscan.com/tx/${txHash}"><code>${txHash}</code></a>`);+ await waitForReceipt(txHash);+ logStep('✅ Approval confirmed.');+ return true;+}++function randomRef() {+ const bytes = crypto.getRandomValues(new Uint8Array(32));+ return '0x' + Array.from(bytes).map((b) => b.toString(16).padStart(2, '0')).join('');+}++async function payOnChain(ref) {+ logStep(`💳 Calling <code>ThreeWSPayments.pay(${ref.slice(0, 10)}…)</code> — sign in MetaMask.`);+ const data = '0x8609cad1' + ref.replace(/^0x/, '');+ const txHash = await eth('eth_sendTransaction', [{+ from: bscAccount, to: BSC_PAYMENTS, data,+ }]);+ const rowDiv = logStep(`📝 Pay tx: <a target="_blank" rel="noopener" href="https://bscscan.com/tx/${txHash}"><code>${txHash}</code></a> — waiting for confirmation…`);+ const rcpt = await waitForReceipt(txHash);+ rowDiv.innerHTML = `✅ Payment confirmed in block ${parseInt(rcpt.blockNumber, 16)}: <a target="_blank" rel="noopener" href="https://bscscan.com/tx/${txHash}"><code>${txHash}</code></a>`;+ return txHash;+}++async function callMcp(toolName, toolArgs, txHash, ref) {+ const payload = {+ scheme: 'direct',+ network: 'eip155:56',+ txHash,+ ref,+ payer: bscAccount,+ };+ const xPayment = btoa(JSON.stringify(payload));+ logStep(`🚀 POST <code>/api/mcp</code> with <code>X-PAYMENT</code> proving the BSC tx…`);++ const isToolsList = toolName === 'tools/list';+ const body = isToolsList+ ? { jsonrpc: '2.0', id: 1, method: 'tools/list' }+ : { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: toolName, arguments: toolArgs } };++ const res = await fetch('/api/mcp', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'accept': 'application/json',+ 'x-payment': xPayment,+ },+ body: JSON.stringify(body),+ });+ if (!res.ok) {+ const text = await res.text();+ throw new Error(`MCP ${res.status}: ${text.slice(0, 300)}`);+ }+ const data = await res.json();+ if (data.error) throw new Error(`MCP error: ${data.error.message || JSON.stringify(data.error)}`);+ return data;+}++const BSC_TOOL_PRESETS = {+ validate_model: { name: 'validate_model', args: { url: 'https://modelviewer.dev/shared-assets/models/DamagedHelmet/glTF-Binary/DamagedHelmet.glb' } },+ inspect_model: { name: 'inspect_model', args: { url: 'https://modelviewer.dev/shared-assets/models/DamagedHelmet/glTF-Binary/DamagedHelmet.glb' } },+ search_public_avatars: { name: 'search_public_avatars', args: { limit: 5 } },+ tools_list: { name: 'tools/list', args: {} },+};++async function runBscFlow(toolKey) {+ try {+ if (!bscAccount) await bscConnect();+ if (!bscAccount) return;+ const preset = BSC_TOOL_PRESETS[toolKey];+ if (!preset) throw new Error('Unknown tool: ' + toolKey);++ await approveIfNeeded();+ const ref = randomRef();+ const txHash = await payOnChain(ref);+ const result = await callMcp(preset.name, preset.args, txHash, ref);++ const pretty = JSON.stringify(result, null, 2);+ const truncated = pretty.length > 4000 ? pretty.slice(0, 4000) + '\n…(truncated)' : pretty;+ logStep(`📦 MCP result:<pre>${escapeHtml(truncated)}</pre>`, 'result');+ await refreshBalances();+ } catch (err) {+ const msg = err && (err.shortMessage || err.message) ? (err.shortMessage || err.message) : String(err);+ logStep('❌ ' + escapeHtml(msg), 'err');+ }+}++function escapeHtml(s) {+ return String(s)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>');+}++$b('bscConnect').addEventListener('click', () => {+ bscConnect().catch((err) => logStep('❌ ' + escapeHtml(err.message || String(err)), 'err'));+});+document.querySelectorAll('[data-bsctool]').forEach((btn) => {+ btn.addEventListener('click', () => runBscFlow(btn.dataset.bsctool));+});++// Auto-switch into the BSC tab when navigated as /pay?chain=bsc — used by+// the DappBay listing link so visitors land directly on the BNB-Chain flow.+const bscParams = new URLSearchParams(location.search);+if (bscParams.get('chain') === 'bsc') activateChain('bsc');+</script>+</body></html>diff --git a/public/sitemap.xml b/public/sitemap.xmlindex 17b3807f8..ccb1528c8 100644--- a/public/sitemap.xml+++ b/public/sitemap.xml@@ -2,229 +2,229 @@<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><url><loc>https://three.ws/</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>1.0</priority></url><url><loc>https://three.ws/discover</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>daily</changefreq><priority>0.9</priority></url><url><loc>https://three.ws/gallery</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url><url><loc>https://three.ws/walk</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>monthly</changefreq><priority>0.7</priority></url><url><loc>https://three.ws/marketplace</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url><url><loc>https://three.ws/community</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>0.6</priority></url><url><loc>https://three.ws/sitemap</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>0.4</priority></url><url><loc>https://three.ws/create</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>0.9</priority></url><url><loc>https://three.ws/app</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>monthly</changefreq><priority>0.7</priority></url><url><loc>https://three.ws/validation</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>monthly</changefreq><priority>0.6</priority></url><url><loc>https://three.ws/studio</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>0.8</priority></url><url><loc>https://three.ws/artifact</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>monthly</changefreq><priority>0.5</priority></url><url><loc>https://three.ws/widgets</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>0.7</priority></url><url><loc>https://three.ws/hydrate</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>0.7</priority></url><url><loc>https://three.ws/pay</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>0.9</priority></url><url><loc>https://three.ws/pumpfun</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url><url><loc>https://three.ws/pump-live</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url><url><loc>https://three.ws/pump-dashboard</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url><url><loc>https://three.ws/strategy-lab</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>0.7</priority></url><url><loc>https://three.ws/vanity-wallet</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>monthly</changefreq><priority>0.6</priority></url><url><loc>https://three.ws/eth-vanity</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>monthly</changefreq><priority>0.6</priority></url><url><loc>https://three.ws/chat</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>0.8</priority></url><url><loc>https://three.ws/agent</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>0.7</priority></url><url><loc>https://three.ws/agents</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url><url><loc>https://three.ws/reputation</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>0.6</priority></url><url><loc>https://three.ws/login</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>yearly</changefreq><priority>0.4</priority></url><url><loc>https://three.ws/register</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>yearly</changefreq><priority>0.4</priority></url><url><loc>https://three.ws/forgot-password</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>yearly</changefreq><priority>0.2</priority></url><url><loc>https://three.ws/docs</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>0.9</priority></url><url><loc>https://three.ws/docs/quick-start</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>weekly</changefreq><priority>0.8</priority></url><url><loc>https://three.ws/docs/agent-system</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod></url><url><loc>https://three.ws/docs/erc8004</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod></url><url><loc>https://three.ws/docs/embedding</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod></url><url><loc>https://three.ws/docs/web-component</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod></url><url><loc>https://three.ws/docs/mcp</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod></url><url><loc>https://three.ws/docs/skills</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod></url><url><loc>https://three.ws/docs/widgets</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod></url><url><loc>https://three.ws/docs/api-reference</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod></url><url><loc>https://three.ws/docs/sdk</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod></url><url><loc>https://three.ws/docs/listings</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>monthly</changefreq><priority>0.5</priority></url><url><loc>https://three.ws/tutorials</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod></url><url><loc>https://three.ws/blog</loc>@@ -252,13 +252,13 @@</url><url><loc>https://three.ws/legal/privacy</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>yearly</changefreq><priority>0.2</priority></url><url><loc>https://three.ws/legal/tos</loc>- <lastmod>2026-05-18</lastmod>+ <lastmod>2026-05-19</lastmod><changefreq>yearly</changefreq><priority>0.2</priority></url>diff --git a/scripts/erc8004-mint-bsc.mjs b/scripts/erc8004-mint-bsc.mjsnew file mode 100644index 000000000..bfdf8fabd--- /dev/null+++ b/scripts/erc8004-mint-bsc.mjs@@ -0,0 +1,303 @@+#!/usr/bin/env node+// scripts/erc8004-mint-bsc.mjs+//+// Mint ERC-8004 agent identities on BNB Smart Chain (chain 56) using the+// canonical IdentityRegistry deployment at 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432.+// Pairs with the BSC x402 work in api/_lib/x402-bsc-direct.js — every mint here+// is a real tx on the same chain that the /pay demo settles payments on.+//+// One-off mode:+// node scripts/erc8004-mint-bsc.mjs \+// --name "Three.ws Aria" \+// --description "Lead community agent — onboards new visitors." \+// --image https://three.ws/agents/aria/avatar.png \+// --website https://three.ws/m/aria+//+// Bulk mode (queries agent_identities via DATABASE_URL):+// node scripts/erc8004-mint-bsc.mjs --from-db --limit 50+//+// Required env:+// BSC_OPERATOR_KEY hex private key (0x… or raw) of the EOA that signs+// register() — must hold BNB for gas. The minted+// NFTs are owned by this address until transferred.+// Optional env:+// RPC_URL_56 BSC RPC; defaults to https://bsc-dataseed.binance.org+// PUBLIC_APP_ORIGIN used to build agentURI links; defaults to https://three.ws+// DATABASE_URL required for --from-db+// DRY_RUN=1 same as --dry-run++import process from 'node:process';+import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { ethers } from 'ethers';++const REGISTRY = '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432';+const CHAIN_ID = 56;++const IDENTITY_REGISTRY_ABI = [+ 'function register(string agentURI) external returns (uint256 agentId)',+ 'function totalSupply() external view returns (uint256)',+ 'function tokenURI(uint256 tokenId) external view returns (string)',+ 'function ownerOf(uint256 tokenId) external view returns (address)',+ 'event Registered(uint256 indexed agentId, string agentURI, address indexed owner)',+];++const __dirname = dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = resolve(__dirname, '..');+const LEDGER_PATH = resolve(REPO_ROOT, 'data/erc8004-bsc-mint-ledger.json');++function parseArgs(argv) {+ const args = {};+ for (let i = 2; i < argv.length; i++) {+ const a = argv[i];+ if (a === '--dry-run') args.dryRun = true;+ else if (a === '--from-db') args.fromDb = true;+ else if (a === '--yes') args.yes = true;+ else if (a.startsWith('--')) {+ const key = a.slice(2);+ const val = argv[i + 1];+ if (val !== undefined && !val.startsWith('--')) {+ args[key] = val;+ i++;+ } else {+ args[key] = true;+ }+ }+ }+ return args;+}++function loadEnv() {+ // Best-effort .env loader — used so the script picks up the same vars the+ // Vite dev proxy uses without making @vercel/cli or dotenv a hard dep.+ const path = resolve(REPO_ROOT, '.env');+ if (!existsSync(path)) return;+ const text = readFileSync(path, 'utf8');+ for (const raw of text.split('\n')) {+ const line = raw.trim();+ if (!line || line.startsWith('#')) continue;+ const eq = line.indexOf('=');+ if (eq < 0) continue;+ const key = line.slice(0, eq).trim();+ let val = line.slice(eq + 1).trim();+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {+ val = val.slice(1, -1);+ }+ if (process.env[key] === undefined) process.env[key] = val;+ }+}++function loadLedger() {+ if (!existsSync(LEDGER_PATH)) return { mints: [] };+ try {+ return JSON.parse(readFileSync(LEDGER_PATH, 'utf8'));+ } catch {+ return { mints: [] };+ }+}++function appendLedger(entry) {+ const ledger = loadLedger();+ ledger.mints.push({ ...entry, at: new Date().toISOString() });+ mkdirSync(dirname(LEDGER_PATH), { recursive: true });+ writeFileSync(LEDGER_PATH, JSON.stringify(ledger, null, 2) + '\n');+}++function ledgerHas({ chainId, sourceId }) {+ if (!sourceId) return false;+ const ledger = loadLedger();+ return ledger.mints.some((m) => m.chainId === chainId && m.sourceId === sourceId);+}++function buildAgentURI(agent) {+ // ERC-8004 agentURI must resolve to a metadata JSON. Order of preference:+ // 1. --uri/agent.uri → caller-supplied URL (ipfs://, ar://, https://…)+ // 2. agent.website → for one-off mints with a stable HTML page that+ // also serves JSON via content-negotiation+ // 3. data:application/json;base64,<…> → inline, fully self-contained;+ // heavier calldata (~16 gas/byte) but no external dependency. Used+ // until /api/agents/<id>/erc8004 ships as a canonical resolver.+ if (agent.uri) return agent.uri;+ if (agent.website) return agent.website;+ const origin = (process.env.PUBLIC_APP_ORIGIN || 'https://three.ws').replace(/\/$/, '');+ const meta = {+ name: agent.name,+ description: agent.description || '',+ image: agent.image || '',+ website: agent.sourceId ? `${origin}/m/agent/${agent.sourceId}` : origin,+ schema: 'erc-8004',+ };+ const b64 = Buffer.from(JSON.stringify(meta), 'utf8').toString('base64');+ return `data:application/json;base64,${b64}`;+}++async function fetchAgentsFromDb(limit) {+ const url = process.env.DATABASE_URL;+ if (!url) throw new Error('--from-db requires DATABASE_URL');+ const { neon } = await import('@neondatabase/serverless').catch(async () => {+ // Fallback to postgres.js — already a dep of the project.+ const pg = await import('postgres');+ const sql = pg.default(url, { ssl: 'require' });+ return {+ neon: () => async (strings, ...values) => {+ return sql(strings, ...values);+ },+ };+ });+ const sql = typeof neon === 'function' ? neon(url) : neon;+ const rows = await sql`+ SELECT ai.id, ai.name, ai.description, ai.category, av.thumbnail_key+ FROM agent_identities ai+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL+ WHERE ai.is_published = true+ AND ai.deleted_at IS NULL+ ORDER BY ai.published_at DESC NULLS LAST+ LIMIT ${limit}+ `;+ const publicDomain = (process.env.S3_PUBLIC_DOMAIN || '').replace(/\/$/, '');+ return rows.map((r) => ({+ sourceId: r.id,+ name: r.name,+ description: r.description,+ image: r.thumbnail_key && publicDomain ? `${publicDomain}/${r.thumbnail_key}` : '',+ }));+}++async function mintOne(contract, wallet, agent, opts) {+ const agentURI = buildAgentURI(agent);+ if (ledgerHas({ chainId: CHAIN_ID, sourceId: agent.sourceId })) {+ console.log(`[skip] ${agent.name} — already in ledger for chain ${CHAIN_ID}`);+ return null;+ }++ console.log(`[mint] ${agent.name}`);+ console.log(` agentURI: ${agentURI.length > 80 ? agentURI.slice(0, 77) + '…' : agentURI}`);++ const fn = contract.getFunction('register(string)');+ if (opts.dryRun) {+ const gas = await fn.estimateGas(agentURI);+ console.log(` [dry-run] est. gas = ${gas.toString()}`);+ return { dryRun: true, gas: gas.toString() };+ }++ const tx = await fn.send(agentURI);+ console.log(` tx: https://bscscan.com/tx/${tx.hash}`);+ const receipt = await tx.wait();+ if (!receipt || receipt.status !== 1) {+ throw new Error(`tx ${tx.hash} did not succeed (status ${receipt?.status})`);+ }++ const iface = contract.interface;+ let agentId = null;+ let owner = null;+ for (const log of receipt.logs) {+ if (log.address.toLowerCase() !== REGISTRY.toLowerCase()) continue;+ try {+ const parsed = iface.parseLog(log);+ if (parsed.name === 'Registered') {+ agentId = parsed.args.agentId.toString();+ owner = parsed.args.owner;+ break;+ }+ } catch {+ // not our event+ }+ }+ if (!agentId) throw new Error(`Registered event not found in tx ${tx.hash}`);++ const gasUsed = receipt.gasUsed?.toString?.() ?? null;+ const effectiveGasPrice = receipt.gasPrice?.toString?.() ?? receipt.effectiveGasPrice?.toString?.() ?? null;+ const gasCostWei =+ gasUsed && effectiveGasPrice ? (BigInt(gasUsed) * BigInt(effectiveGasPrice)).toString() : null;++ console.log(` agentId: ${agentId} owner: ${owner} gas: ${gasUsed}`);++ appendLedger({+ chainId: CHAIN_ID,+ sourceId: agent.sourceId || null,+ agentId,+ owner,+ agentURI,+ txHash: tx.hash,+ blockNumber: receipt.blockNumber,+ gasUsed,+ gasCostWei,+ });++ return { agentId, owner, txHash: tx.hash, gasUsed, gasCostWei };+}++async function main() {+ loadEnv();+ const args = parseArgs(process.argv);+ const dryRun = !!args.dryRun || process.env.DRY_RUN === '1';++ const pk = process.env.BSC_OPERATOR_KEY;+ if (!pk) {+ console.error('error: BSC_OPERATOR_KEY env var is required (hex private key of the operator EOA).');+ process.exit(1);+ }+ const rpc = process.env.RPC_URL_56 || 'https://bsc-dataseed.binance.org';+ const provider = new ethers.JsonRpcProvider(rpc, CHAIN_ID);+ const wallet = new ethers.Wallet(pk.startsWith('0x') ? pk : '0x' + pk, provider);+ const contract = new ethers.Contract(REGISTRY, IDENTITY_REGISTRY_ABI, wallet);++ const bnb = await provider.getBalance(wallet.address);+ const bnbStr = ethers.formatEther(bnb);+ console.log(`operator: ${wallet.address}`);+ console.log(`balance: ${bnbStr} BNB`);+ console.log(`registry: ${REGISTRY} (chain ${CHAIN_ID})`);+ console.log(`mode: ${dryRun ? 'DRY RUN' : 'LIVE'}\n`);++ let agents;+ if (args.fromDb) {+ const limit = Number(args.limit || 50);+ console.log(`loading up to ${limit} published agents from DB…`);+ agents = await fetchAgentsFromDb(limit);+ console.log(`found ${agents.length} agents\n`);+ } else {+ if (!args.name) {+ console.error('error: one-off mint requires --name "Agent Name". Use --from-db to mint from the marketplace.');+ process.exit(1);+ }+ agents = [+ {+ name: args.name,+ description: args.description || '',+ image: args.image || '',+ website: args.website || '',+ uri: args.uri || '',+ },+ ];+ }++ if (!dryRun && !args.yes && agents.length > 1) {+ console.log(`about to send ${agents.length} live mint transactions on BSC mainnet.`);+ console.log('re-run with --yes to confirm.');+ process.exit(0);+ }++ let ok = 0;+ let failed = 0;+ for (const a of agents) {+ try {+ await mintOne(contract, wallet, a, { dryRun });+ ok++;+ } catch (err) {+ failed++;+ console.error(` [fail] ${err.shortMessage || err.message}`);+ }+ // brief pause to avoid nonce races on slow RPCs+ if (!dryRun) await new Promise((r) => setTimeout(r, 1500));+ }++ console.log(`\ndone. ok=${ok} failed=${failed}`);+ if (!dryRun) console.log(`ledger: ${LEDGER_PATH}`);+}++main().catch((err) => {+ console.error('fatal:', err.shortMessage || err.message || err);+ process.exit(1);+});diff --git a/scripts/vanity-wallet.mjs b/scripts/vanity-wallet.mjsnew file mode 100644index 000000000..1cf066eb0--- /dev/null+++ b/scripts/vanity-wallet.mjs@@ -0,0 +1,41 @@+#!/usr/bin/env node+import { Wallet } from 'ethers';+import { writeFileSync, existsSync, readFileSync, appendFileSync } from 'node:fs';+import { resolve } from 'node:path';++const prefix = (process.argv[2] || '333').toLowerCase().replace(/^0x/, '');+if (!/^[0-9a-f]+$/.test(prefix)) {+ console.error(`Invalid hex prefix: ${prefix}`);+ process.exit(1);+}++const target = '0x' + prefix;+const expected = Math.pow(16, prefix.length);+console.error(`Hunting for ${target}... ~${expected.toLocaleString()} avg attempts`);++const start = Date.now();+let attempts = 0;+let last = start;++while (true) {+ const w = Wallet.createRandom();+ attempts++;+ if (w.address.toLowerCase().startsWith(target)) {+ const secs = ((Date.now() - start) / 1000).toFixed(2);+ console.error(`Found in ${attempts.toLocaleString()} attempts (${secs}s)`);+ const out = {+ address: w.address,+ privateKey: w.privateKey,+ mnemonic: w.mnemonic?.phrase || null,+ prefix: target,+ generatedAt: new Date().toISOString(),+ };+ process.stdout.write(JSON.stringify(out, null, 2) + '\n');+ break;+ }+ if (Date.now() - last > 2000) {+ const rate = Math.round(attempts / ((Date.now() - start) / 1000));+ console.error(` ${attempts.toLocaleString()} tried, ${rate.toLocaleString()}/s`);+ last = Date.now();+ }+}diff --git a/vercel.json b/vercel.jsonindex 76c4ced97..b66c89f53 100644--- a/vercel.json+++ b/vercel.json@@ -184,6 +184,14 @@"src": "/vanity-wallet/","dest": "/vanity-wallet.html"},+ {+ "src": "/eth-vanity",+ "dest": "/eth-vanity.html"+ },+ {+ "src": "/eth-vanity/",+ "dest": "/eth-vanity.html"+ },{"src": "/pump-visualizer/?","dest": "/pump-visualizer.html"@@ -204,6 +212,22 @@"src": "/walk/?","dest": "/walk.html"},+ {+ "src": "/walkaround/?",+ "dest": "/demos/walkaround.html"+ },+ {+ "src": "/brain/?",+ "dest": "/demos/brain.html"+ },+ {+ "src": "/lipsync/mic/?",+ "dest": "/demos/lipsync-mic.html"+ },+ {+ "src": "/lipsync/?",+ "dest": "/demos/lipsync-tts.html"+ },{"src": "/pretext-demo/?","dest": "/pretext-demo.html"diff --git a/vite.config.js b/vite.config.jsindex 107fbed6c..27c461796 100644--- a/vite.config.js+++ b/vite.config.js@@ -170,6 +170,7 @@ const appConfig = {'avatar-os-combined': resolve(__dirname, 'public/demo/avatar-os/combined.html'),'demos-brain': resolve(__dirname, 'public/demos/brain.html'),'demos-lipsync-tts': resolve(__dirname, 'public/demos/lipsync-tts.html'),+ 'demos-lipsync-mic': resolve(__dirname, 'public/demos/lipsync-mic.html'),'demos-walkaround': resolve(__dirname, 'public/demos/walkaround.html'),'demos-erc8004': resolve(__dirname, 'public/demos/erc8004.html'),'demos-button-jump': resolve(__dirname, 'public/demos/button-jump.html'),@@ -240,6 +241,14 @@ const appConfig = {'/avatar-artifact/': resolve(root, 'avatar-artifact.html'),'/walk': resolve(root, 'walk.html'),'/walk/': resolve(root, 'walk.html'),+ '/walkaround': resolve(root, 'public/demos/walkaround.html'),+ '/walkaround/': resolve(root, 'public/demos/walkaround.html'),+ '/brain': resolve(root, 'public/demos/brain.html'),+ '/brain/': resolve(root, 'public/demos/brain.html'),+ '/lipsync': resolve(root, 'public/demos/lipsync-tts.html'),+ '/lipsync/': resolve(root, 'public/demos/lipsync-tts.html'),+ '/lipsync/mic': resolve(root, 'public/demos/lipsync-mic.html'),+ '/lipsync/mic/': resolve(root, 'public/demos/lipsync-mic.html'),'/pretext-demo': resolve(root, 'pretext-demo.html'),'/pretext-demo/': resolve(root, 'pretext-demo.html'),'/launch-week': resolve(root, 'three-ws-launch-week.html'),@@ -565,11 +574,13 @@ const appConfig = {['dist/public/agent/index.html', 'dist/agent/index.html'],['dist/public/demos/brain.html', 'dist/demos/brain.html'],['dist/public/demos/lipsync-tts.html', 'dist/demos/lipsync-tts.html'],+ ['dist/public/demos/lipsync-mic.html', 'dist/demos/lipsync-mic.html'],['dist/public/demos/walkaround.html', 'dist/demos/walkaround.html'],['dist/public/demos/erc8004.html', 'dist/demos/erc8004.html'],['dist/public/demos/button-jump.html', 'dist/demos/button-jump.html'],['dist/public/demos/button.html', 'dist/demos/button.html'],['dist/public/demos/3d-home.html', 'dist/demos/3d-home.html'],+ ['dist/public/eth-vanity.html', 'dist/eth-vanity.html'],];for (const [from, to] of pairs) {const src = resolve(__dirname, from);