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.

14.8 KB
Raw Blame
// Play gate — the wallet sign-in screen that stands in front of /play.
//
// States (all honest, none a dead end):
//   no_wallet  — no Solana wallet installed, with a link to Phantom
//   connect    — wallet found, ready to connect + sign
//   working    — connecting / signing / verifying (with stage label)
//   low        — balance verified but below the floor; shows exact gap + buy link
//   granted    — cleared; brief confirmation before the world opens
//   error      — retryable error (network, expired nonce, etc.)
//
// Only mounts a DOM overlay when sign-in is actually needed. When /play is open
// (no token pinned) or a fresh pass is already cached, it resolves instantly with
// no visible interruption.

import { fetchPlayConfig, signInToPlay, loadStoredPass, clearStoredPass, hasWallet, PlayAuthError } from './play-auth.js';
import { log } from '../shared/log.js';

const PHANTOM_INSTALL = 'https://phantom.app/download';

// Monochrome line icons — the design language is strictly greyscale.
const SVG = {
	wallet: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 9h18"/><circle cx="16.5" cy="13" r="1.2"/></svg>',
	key:    '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="4.5"/><path d="M11.2 11.2 20 20"/><path d="M16.5 16.5 19 14"/></svg>',
	ticket: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7h16v3a2 2 0 0 0 0 4v3H4v-3a2 2 0 0 0 0-4z"/><path d="M14 7v10" stroke-dasharray="1.5 2"/></svg>',
	warn:   '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 4 2.5 20h19z"/><path d="M12 10v4"/><circle cx="12" cy="17" r="0.6" fill="currentColor"/></svg>',
};

/**
 * Ensure the player has cleared the token gate before the lobby opens.
 * @returns {Promise<{ required: boolean, wallet?: string, playPass?: string, balance?: number, symbol?: string }>}
 */
export function ensurePlayAccess() {
	return new Gate().run();
}

class Gate {
	constructor() {
		this.root = null;
		this.cfg = null;
		this._resolve = null;
		this._focusTrap = null;
		this._prevFocus = null;
	}

	run() {
		return new Promise((resolve) => {
			this._resolve = resolve;
			this._start();
		});
	}

	async _start() {
		// Read the session cache FIRST, because reading is also how it is reaped:
		// loadStoredPass() drops an entry that is expired or corrupt. Both early
		// exits below (the config probe failing open, and a world whose gate is
		// off) used to return before anything touched sessionStorage, so a dead
		// token outlived the boot that should have retired it and stayed there for
		// the rest of the tab's life, ready for the next reader to hand to a room
		// join the server can only refuse.
		const cached = loadStoredPass();
		// Probe the gate before mounting anything — no flash when /play is open or a
		// fresh cached pass exists. Only mount if sign-in is actually required.
		let cfg;
		try {
			cfg = await fetchPlayConfig();
		} catch (err) {
			// Fail OPEN, never closed: when we can't even read the gate config we don't
			// know whether a token is pinned, and /play is almost always open. Bricking
			// the world with a blocking error overlay on a transient blip (a 429 from a
			// shared NAT, a network hiccup) would dead-end the 99% case. The server is
			// the real authority — a genuinely-gated world refuses any unsigned room
			// join, so the worst case here is an honest bounce at join, not free entry.
			// This honors the self-healing contract documented at _ensurePlayAccess.
			// Telemetry for a designed path, so it logs at info through the gated
			// logger: a raw console.warn here announced our own fail-open branch as a
			// defect in every visitor's console, including the ones this branch exists
			// to serve (a venue filter or an ad blocker eating /api/play/config).
			log.info('[play-gate] gate probe failed, opening /play:', err?.message || err);
			this._finish({ required: false });
			return;
		}
		this.cfg = cfg;

		if (!cfg.required) {
			this._finish({ required: false });
			return;
		}

		// A still-fresh cached pass for this exact mint skips the wallet prompt.
		if (cached && cached.mint === cfg.mint) {
			this._finish({ required: true, wallet: cached.wallet, playPass: cached.playPass, balance: cached.balance, symbol: cached.symbol });
			return;
		}

		this._mount();
		if (!hasWallet()) {
			this._render({ state: 'no_wallet', onRetry: () => this._checkWalletThenConnect() });
		} else {
			this._render({ state: 'connect', onConnect: () => this._attempt(), onSwitch: () => this._switchWallet() });
		}
	}

	// Called when the player hits "I've installed one — retry": re-detect and
	// either show connect or the no-wallet screen again.
	_checkWalletThenConnect() {
		if (hasWallet()) {
			this._render({ state: 'connect', onConnect: () => this._attempt() });
		} else {
			this._render({ state: 'no_wallet', onRetry: () => this._checkWalletThenConnect() });
		}
	}

	// Drop the current wallet link and start a fresh sign-in so the player can pick
	// a different account. Clears any cached pass for the old wallet too, so the
	// new wallet is the one that gets verified and remembered.
	_switchWallet() {
		clearStoredPass();
		this._attempt({ forceReconnect: true });
	}

	async _attempt({ forceReconnect = false } = {}) {
		// Fetch a fresh nonce on each attempt (they're short-lived + single-use).
		this._render({ state: 'working', stage: 'connecting' });
		let nonce = this.cfg?.nonce;
		try {
			const fresh = await fetchPlayConfig();
			this.cfg = fresh;
			nonce = fresh.nonce;
		} catch {
			// Fall back to the nonce we have; verify will reject if stale.
		}

		try {
			const res = await signInToPlay({ nonce, forceReconnect, onStage: (stage) => this._render({ state: 'working', stage }) });
			if (res.ok && res.playPass) {
				this._render({ state: 'granted', symbol: res.symbol, balance: res.balance });
				setTimeout(() => this._finish({ required: true, wallet: res.wallet, playPass: res.playPass, balance: res.balance, symbol: res.symbol }), 700);
				return;
			}
			// Signature verified but balance is short. Offer a recheck (same wallet,
			// after a top-up) and a switch (try a different wallet entirely).
			this._render({
				state: 'low',
				data: res,
				onRecheck: () => this._attempt(),
				onSwitch: () => this._switchWallet(),
				onAcquire: res.acquireUrl ? () => window.open(res.acquireUrl, '_blank', 'noopener noreferrer') : null,
			});
		} catch (err) {
			const code = err instanceof PlayAuthError ? err.code : 'error';
			if (code === 'no_wallet') {
				this._render({ state: 'no_wallet', onRetry: () => this._checkWalletThenConnect() });
				return;
			}
			if (code === 'rejected') {
				// Wallet cancelled — drop back to the connect screen with the reason.
				this._render({ state: 'connect', error: err.message, onConnect: () => this._attempt(), onSwitch: () => this._switchWallet() });
				return;
			}
			this._render({ state: 'error', error: err?.message || 'Sign-in failed. Please try again.', onRetry: () => this._attempt(), onSwitch: () => this._switchWallet() });
		}
	}

	// ── DOM ──────────────────────────────────────────────────────────────────

	_mount() {
		if (this.root) return;
		this._prevFocus = document.activeElement;
		const root = document.createElement('div');
		root.className = 'pg-root';
		root.setAttribute('role', 'dialog');
		root.setAttribute('aria-modal', 'true');
		root.setAttribute('aria-label', 'Sign in to play');
		// Prevent the background lobby receiving Tab events while the gate is up.
		root.setAttribute('tabindex', '-1');
		document.body.appendChild(root);
		this.root = root;
		this._installFocusTrap();
	}

	_installFocusTrap() {
		const FOCUSABLE = 'button:not([disabled]), a[href], input:not([disabled]), [tabindex]:not([tabindex="-1"])';
		const trap = (e) => {
			if (e.key !== 'Tab' || !this.root) return;
			const els = Array.from(this.root.querySelectorAll(FOCUSABLE));
			if (!els.length) { e.preventDefault(); return; }
			const first = els[0], last = els[els.length - 1];
			if (e.shiftKey) {
				if (document.activeElement === first) { e.preventDefault(); last.focus(); }
			} else {
				if (document.activeElement === last) { e.preventDefault(); first.focus(); }
			}
		};
		document.addEventListener('keydown', trap);
		this._focusTrap = trap;
	}

	_finish(result) {
		if (this._focusTrap) { document.removeEventListener('keydown', this._focusTrap); this._focusTrap = null; }
		if (this.root) {
			this.root.classList.add('pg-leaving');
			const el = this.root;
			setTimeout(() => el.remove(), 320);
			this.root = null;
		}
		// Restore focus to where it was before the gate appeared.
		try { this._prevFocus?.focus?.(); } catch {}
		this._resolve?.(result);
		this._resolve = null;
	}

	_render(view) {
		if (!this.root) return;
		this.root.innerHTML = this._html(view);
		// Wire actions to freshly-rendered elements.
		const q = (sel) => this.root.querySelector(sel);
		q('[data-act="connect"]')?.addEventListener('click', () => view.onConnect?.());
		q('[data-act="retry"]')?.addEventListener('click', () => view.onRetry?.());
		q('[data-act="recheck"]')?.addEventListener('click', () => view.onRecheck?.());
		q('[data-act="acquire"]')?.addEventListener('click', () => view.onAcquire?.());
		q('[data-act="switch"]')?.addEventListener('click', () => view.onSwitch?.());
		// Move keyboard focus onto the primary CTA.
		setTimeout(() => (q('.pg-btn-primary') || q('.pg-btn'))?.focus(), 50);
	}

	_html(view) {
		const card = (inner) => `
			<div class="pg-backdrop"></div>
			<div class="pg-card" data-state="${esc(view.state)}">
				<div class="pg-brand"><img loading="eager" decoding="async" src="/three.svg" alt="" width="30" height="30"><span>COIN COMMUNITIES</span></div>
				${inner}
			</div>`;

		const min = this.cfg?.minBalance ?? 1;
		const sym = this.cfg?.symbol || '';
		const tokenLabel = sym ? `$${esc(sym)}` : 'the game token';

		switch (view.state) {
			case 'no_wallet':
				return card(`
					<div class="pg-icon">${SVG.wallet}</div>
					<h1 class="pg-title">Install a Solana wallet</h1>
					<p class="pg-sub">Your wallet is your account — no email, no password. Install <strong>Phantom</strong>, then come back and retry.</p>
					<a class="pg-btn pg-btn-primary" href="${PHANTOM_INSTALL}" target="_blank" rel="noopener noreferrer">Get Phantom</a>
					<button class="pg-btn pg-btn-ghost" data-act="retry">I've installed it — retry</button>`);

			case 'connect':
				return card(`
					<div class="pg-icon">${SVG.key}</div>
					<h1 class="pg-title">Sign in to play</h1>
					<p class="pg-sub">Connect your wallet and sign a message to prove ownership. You'll need at least <strong>${esc(String(min))} ${tokenLabel}</strong>. Nothing moves on-chain.</p>
					${view.error ? `<p class="pg-error" role="alert">${esc(view.error)}</p>` : ''}
					<button class="pg-btn pg-btn-primary" data-act="connect">Connect wallet</button>
					${view.onSwitch ? `<button class="pg-link" data-act="switch">Use a different wallet</button>` : ''}
					<p class="pg-fine">We will never ask for your seed phrase.</p>`);

			case 'working': {
				const stageIndex = { connecting: 0, signing: 1, verifying: 2 }[view.stage] ?? 0;
				const dots = [0, 1, 2].map((i) => {
					const cls = i < stageIndex ? 'pg-dot pg-dot-done' : i === stageIndex ? 'pg-dot pg-dot-active' : 'pg-dot';
					return `<span class="${cls}" aria-hidden="true"></span>`;
				}).join('');
				const labels = {
					connecting: 'Connecting your wallet…',
					signing: 'Approve the signature…',
					verifying: 'Checking your balance…',
				};
				const subs = {
					connecting: 'Opening your wallet — this only takes a moment.',
					signing: 'Your wallet is waiting for your approval.',
					verifying: 'Reading on-chain balance — almost there.',
				};
				const label = labels[view.stage] || 'Working…';
				return card(`
					<div class="pg-steps" aria-label="Step ${stageIndex + 1} of 3">${dots}</div>
					<div class="pg-spinner" aria-live="polite" aria-label="${esc(label)}"></div>
					<h1 class="pg-title">${esc(label)}</h1>
					<p class="pg-sub">${esc(subs[view.stage] || 'This only takes a moment.')}</p>`);
			}

			case 'low': {
				const d = view.data || {};
				const bal = fmt(d.balance ?? 0);
				const need = fmt(d.minBalance ?? min);
				const displaySym = d.symbol ? `$${esc(d.symbol)}` : tokenLabel;
				return card(`
					<div class="pg-icon">${SVG.ticket}</div>
					<h1 class="pg-title">Not enough ${displaySym}</h1>
					<p class="pg-sub">You need <strong>${need} ${displaySym}</strong> to enter. Top up, then recheck — no need to sign again.</p>
					<div class="pg-balance" aria-label="Balance comparison">
						<div><span class="pg-balance-k">You have</span><span class="pg-balance-v pg-balance-low">${bal}</span></div>
						<div class="pg-balance-sep" aria-hidden="true">→</div>
						<div><span class="pg-balance-k">Required</span><span class="pg-balance-v pg-balance-need">${need}</span></div>
					</div>
					${view.onAcquire ? `<button class="pg-btn pg-btn-primary" data-act="acquire">Get ${displaySym}</button>` : ''}
					<button class="pg-btn ${view.onAcquire ? 'pg-btn-ghost' : 'pg-btn-primary'}" data-act="recheck">Recheck balance</button>
					${view.onSwitch ? `<button class="pg-link" data-act="switch">Try a different wallet</button>` : ''}`);
			}

			case 'granted':
				return card(`
					<div class="pg-check" aria-label="Access granted">✓</div>
					<h1 class="pg-title">You're in</h1>
					<p class="pg-sub">Verified${view.balance != null ? ` · ${fmt(view.balance)} ${view.symbol ? '$' + esc(view.symbol) : tokenLabel}` : ''}. Entering the world…</p>`);

			case 'error':
			default:
				return card(`
					<div class="pg-icon">${SVG.warn}</div>
					<h1 class="pg-title">Sign-in failed</h1>
					<p class="pg-sub" role="alert">${esc(view.error || 'Please try again.')}</p>
					<button class="pg-btn pg-btn-primary" data-act="retry">Try again</button>
					${view.onSwitch ? `<button class="pg-link" data-act="switch">Try a different wallet</button>` : ''}`);
		}
	}
}

function esc(s) {
	return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}

function fmt(n) {
	const v = Number(n) || 0;
	if (v >= 1_000_000) return v.toLocaleString(undefined, { maximumFractionDigits: 0 });
	if (v >= 1000) return v.toLocaleString(undefined, { maximumFractionDigits: 0 });
	if (v >= 1) return v.toLocaleString(undefined, { maximumFractionDigits: 2 });
	return v.toLocaleString(undefined, { maximumFractionDigits: 6 });
}