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.

Add persistent Solana wallet connect to marketplace + app chrome

nirholas86e162ce3307
diff --git a/pages/app.html b/pages/app.html
index ec39e4d31..f0ff18120 100644
--- a/pages/app.html
+++ b/pages/app.html
@@ -278,6 +278,32 @@
</button>
</div>
<a href="/dashboard" class="nav-dashboard">Dashboard</a>
+ <button
+ type="button"
+ class="nav-connect-wallet"
+ id="connect-wallet-btn"
+ title="Connect your Solana wallet"
+ aria-label="Connect your Solana wallet"
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ focusable="false"
+ >
+ <path d="M21 12V7H5a2 2 0 0 1 0-4h14v4" />
+ <path d="M3 5v14a2 2 0 0 0 2 2h16v-5" />
+ <path d="M18 12a2 2 0 0 0 0 4h4v-4z" />
+ </svg>
+ <span data-wallet-label>Connect Wallet</span>
+ </button>
<div class="nav-user-wrap" id="nav-user-wrap" hidden>
<button class="nav-user" id="nav-user-btn" aria-haspopup="true" aria-expanded="false" type="button">
<span id="nav-user-label">Account</span>
diff --git a/pages/marketplace.html b/pages/marketplace.html
index b46d9e3a6..d49435f1f 100644
--- a/pages/marketplace.html
+++ b/pages/marketplace.html
@@ -2679,6 +2679,10 @@
<img src="/three.svg" alt="three.ws" />
<span>Community</span>
</a>
+ <!-- Persistent Solana wallet connect. Shares the same connectedWallet
+ state as the in-modal purchase flow, so connecting here arrives
+ pre-connected at any Buy action. Rendered by src/marketplace.js. -->
+ <div class="mkt-wallet-slot mkt-wallet-slot--sidebar" data-wallet-connect></div>
<nav class="market-nav">
<a href="/" data-nav="home"><span class="ico">⌂</span> <span>Home</span></a>
<a href="/marketplace" data-nav="agent" class="active"
@@ -2811,6 +2815,9 @@
autocomplete="off"
aria-label="Search agents and avatars"
/>
+ <!-- Mobile-only wallet connect: the sidebar (its desktop home)
+ is hidden under 980px, so surface the same control here. -->
+ <div class="mkt-wallet-slot mkt-wallet-slot--topbar" data-wallet-connect></div>
<div
class="market-filter-chips"
id="market-filter-chips"
diff --git a/public/marketplace.css b/public/marketplace.css
index ae16ef519..f36d1720e 100644
--- a/public/marketplace.css
+++ b/public/marketplace.css
@@ -4656,3 +4656,198 @@ body.market-page > header {
.anim-buy-media { border-radius: 20px 20px 0 0; min-height: 200px; }
.anim-buy-media img { border-radius: 20px 20px 0 0; }
}
+
+/* ── Persistent wallet connect control ────────────────────────────────────
+ A single Solana connection surfaced in the marketplace chrome: the sidebar
+ on desktop, the topbar on mobile (where the sidebar is hidden). Both slots
+ read the same connectedWallet state, so only one is ever visible per
+ breakpoint and they stay in lockstep with the in-modal purchase flow. */
+.mkt-wallet-slot {
+ display: flex;
+}
+.mkt-wallet-slot--sidebar {
+ padding: 0 var(--space-sm);
+ margin-bottom: var(--space-3xs);
+}
+/* Topbar slot is desktop-hidden; the sidebar owns the control there. */
+.mkt-wallet-slot--topbar {
+ display: none;
+ margin-left: auto;
+ flex: 0 0 auto;
+}
+
+.mkt-wallet-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 7px;
+ width: 100%;
+ background: var(--accent);
+ color: #000000;
+ border: 0;
+ border-radius: var(--radius-sm);
+ padding: var(--space-xs) var(--space-md);
+ font-family: var(--font-display);
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 1.2;
+ cursor: pointer;
+ white-space: nowrap;
+ transition:
+ filter 0.15s ease,
+ border-color 0.15s ease,
+ opacity 0.15s ease;
+}
+.mkt-wallet-btn:hover {
+ filter: brightness(1.06);
+}
+.mkt-wallet-btn:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+}
+.mkt-wallet-btn:disabled,
+.mkt-wallet-btn.is-busy {
+ opacity: 0.7;
+ cursor: progress;
+}
+.mkt-wallet-btn .mkt-wallet-ico {
+ font-size: 14px;
+ line-height: 1;
+}
+.mkt-wallet-btn .mkt-wallet-label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+/* Connected: a neutral monospace address pill, not the accent CTA. */
+.mkt-wallet-btn.is-connected {
+ background: var(--surface-1);
+ color: var(--ink);
+ border: 1px solid var(--stroke);
+ font-family: var(--font-mono);
+ font-weight: 600;
+}
+.mkt-wallet-btn.is-connected:hover {
+ filter: none;
+ border-color: var(--stroke-strong);
+}
+.mkt-wallet-dot {
+ flex: 0 0 auto;
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: #34d399;
+ box-shadow: 0 0 0 3px rgba(52, 211, 153, 0.18);
+}
+.mkt-wallet-caret {
+ font-size: 9px;
+ color: var(--ink-dim);
+}
+
+/* Below the sidebar breakpoint, hand the control to the topbar. */
+@media (max-width: 980px) {
+ .mkt-wallet-slot--topbar {
+ display: flex;
+ }
+ .mkt-wallet-slot--topbar .mkt-wallet-btn {
+ width: auto;
+ }
+}
+
+/* Dropdown: wallet picker (multi-wallet) or connected actions. Anchored to the
+ button and appended to <body> so the sidebar/topbar can't clip it. */
+.mkt-wallet-menu {
+ position: fixed;
+ z-index: 5000;
+ min-width: 184px;
+ max-width: 260px;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 5px;
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: 10px;
+ box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
+ animation: mkt-wallet-pop 0.12s ease;
+}
+@keyframes mkt-wallet-pop {
+ from {
+ opacity: 0;
+ transform: translateY(-4px);
+ }
+ to {
+ opacity: 1;
+ transform: none;
+ }
+}
+.mkt-wallet-menu-item {
+ display: block;
+ width: 100%;
+ text-align: left;
+ background: transparent;
+ border: 0;
+ border-radius: 7px;
+ padding: 9px 11px;
+ font-family: var(--font-display);
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--ink);
+ text-decoration: none;
+ cursor: pointer;
+ transition: background 0.12s ease;
+}
+.mkt-wallet-menu-item:hover,
+.mkt-wallet-menu-item:focus-visible {
+ background: rgba(255, 255, 255, 0.07);
+ outline: none;
+}
+.mkt-wallet-menu-item.danger {
+ color: #f87171;
+}
+.mkt-wallet-menu-item.danger:hover,
+.mkt-wallet-menu-item.danger:focus-visible {
+ background: rgba(248, 113, 113, 0.12);
+}
+
+/* Transient feedback bubble (address copied / connect error). */
+.mkt-wallet-bubble {
+ position: fixed;
+ z-index: 5001;
+ padding: 7px 11px;
+ background: #0d0d0d;
+ color: var(--ink);
+ border: 1px solid var(--stroke);
+ border-radius: 8px;
+ font-family: var(--font-display);
+ font-size: 12px;
+ font-weight: 600;
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.45);
+ opacity: 0;
+ transform: translateY(-4px);
+ transition:
+ opacity 0.2s ease,
+ transform 0.2s ease;
+ pointer-events: none;
+}
+.mkt-wallet-bubble.show {
+ opacity: 1;
+ transform: none;
+}
+.mkt-wallet-bubble.ok {
+ border-color: rgba(52, 211, 153, 0.4);
+ color: #6ee7b7;
+}
+.mkt-wallet-bubble.err {
+ border-color: rgba(248, 113, 113, 0.4);
+ color: #fca5a5;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .mkt-wallet-btn,
+ .mkt-wallet-menu,
+ .mkt-wallet-bubble {
+ animation: none;
+ transition: none;
+ }
+}
diff --git a/public/style.css b/public/style.css
index aaba13db0..925e047ad 100644
--- a/public/style.css
+++ b/public/style.css
@@ -709,6 +709,65 @@ header h1 .wordmark-logo {
display: none;
}
+/* Connect Wallet — Solana wallet entry point in the app header. Bound by
+ src/wallet.js (initWalletButton); swaps its label for the truncated address
+ and gains .is-connected once a wallet connects. */
+.nav-connect-wallet {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2xs);
+ padding: 0.35rem 0.7rem;
+ font-family: var(--font-body);
+ font-size: var(--text-sm);
+ font-weight: var(--weight-medium);
+ letter-spacing: -0.005em;
+ color: var(--ink);
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ cursor: pointer;
+ white-space: nowrap;
+ -webkit-app-region: no-drag;
+ transition:
+ color var(--duration-fast) var(--ease-standard),
+ background var(--duration-fast) var(--ease-standard),
+ border-color var(--duration-fast) var(--ease-standard);
+}
+
+.nav-connect-wallet svg {
+ width: 14px;
+ height: 14px;
+ flex-shrink: 0;
+ opacity: 0.8;
+}
+
+.nav-connect-wallet:hover {
+ color: var(--ink-bright);
+ background: var(--surface-2);
+ border-color: var(--stroke-strong);
+}
+
+.nav-connect-wallet:active {
+ transform: translateY(0.5px);
+}
+
+.nav-connect-wallet:focus-visible {
+ outline: var(--focus-ring-width) solid var(--focus-ring-color);
+ outline-offset: var(--focus-ring-offset);
+}
+
+.nav-connect-wallet.is-connected {
+ color: var(--ink-bright);
+ background: var(--badge-success-bg);
+ border-color: var(--badge-success-border);
+ font-variant-numeric: tabular-nums;
+}
+
+.nav-connect-wallet.is-connected svg {
+ color: var(--success);
+ opacity: 1;
+}
+
.nav-user-wrap {
position: relative;
}
diff --git a/src/marketplace.js b/src/marketplace.js
index ff2d41dd8..d7b8810b4 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -5931,13 +5931,22 @@ async function connectWalletProvider(providerKey) {
name: entry.name,
publicKey: typeof pubKey === 'string' ? new web3.PublicKey(pubKey) : pubKey,
};
- updateWalletUI();
+ bindProviderEvents(provider, entry.name);
+ notifyWalletChanged();
}
function disconnectWallet() {
try { connectedWallet?.provider?.disconnect?.(); } catch {}
connectedWallet = null;
+ notifyWalletChanged();
+}
+
+// Single fan-out for every wallet state transition. Keeps the in-modal
+// purchase UI (`updateWalletUI`) and the persistent header control
+// (`renderHeaderWallet`) reading from the same `connectedWallet` source.
+function notifyWalletChanged() {
updateWalletUI();
+ renderHeaderWallet();
}
function updateWalletUI() {
@@ -5992,6 +6001,284 @@ function updateWalletUI() {
if (confirmBtn) confirmBtn.disabled = true;
}
+// ── Persistent header wallet control ───────────────────────────────────────
+//
+// Surfaces the wallet connection in the marketplace chrome (sidebar on
+// desktop, topbar on mobile) so a buyer can connect once and reach any Buy
+// action already-connected. Every `[data-wallet-connect]` slot renders from
+// the shared `connectedWallet`, so connecting in either the header or the
+// purchase modal updates both. Uses the real injected providers — Phantom,
+// Solflare, Backpack — same as the purchase flow; no separate wallet lib.
+
+const WALLET_EXPLORER = 'https://solscan.io/account/';
+const _walletEventsBound = new WeakSet();
+
+function walletInstallUrl(key) {
+ if (key === 'solflare') return 'https://solflare.com';
+ if (key === 'backpack') return 'https://backpack.app';
+ return 'https://phantom.app';
+}
+
+function shortWalletAddress(pk) {
+ return `${pk.slice(0, 4)}…${pk.slice(-4)}`;
+}
+
+function renderHeaderWallet() {
+ const slots = document.querySelectorAll('[data-wallet-connect]');
+ slots.forEach((slot) => {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'mkt-wallet-btn';
+ btn.setAttribute('aria-haspopup', 'menu');
+ btn.setAttribute('aria-expanded', 'false');
+
+ if (connectedWallet) {
+ const pk = connectedWallet.publicKey.toBase58();
+ btn.classList.add('is-connected');
+ btn.innerHTML =
+ '<span class="mkt-wallet-dot" aria-hidden="true"></span>' +
+ `<span class="mkt-wallet-label">${escapeHtml(shortWalletAddress(pk))}</span>` +
+ '<span class="mkt-wallet-caret" aria-hidden="true">▾</span>';
+ btn.setAttribute(
+ 'aria-label',
+ `${connectedWallet.name} wallet connected, ${pk}. Open wallet menu`,
+ );
+ btn.addEventListener('click', () => openConnectedWalletMenu(btn));
+ } else {
+ btn.innerHTML =
+ '<span class="mkt-wallet-ico" aria-hidden="true">◎</span>' +
+ '<span class="mkt-wallet-label">Connect Wallet</span>';
+ btn.setAttribute('aria-label', 'Connect a Solana wallet');
+ btn.addEventListener('click', () => onHeaderConnectClick(btn));
+ }
+
+ slot.replaceChildren(btn);
+ });
+}
+
+async function onHeaderConnectClick(btn) {
+ // Detect at click time — extensions can inject after page load.
+ const available = listAvailableWallets();
+ if (available.length === 1) {
+ await headerConnectWallet(available[0].key, btn);
+ return;
+ }
+ if (available.length > 1) {
+ openWalletMenu(
+ btn,
+ available.map((w) => ({
+ label: `Connect ${w.name}`,
+ onClick: () => headerConnectWallet(w.key, btn),
+ })),
+ );
+ return;
+ }
+ // No injected wallet — offer install links.
+ openWalletMenu(
+ btn,
+ WALLET_PROVIDERS.map((p) => ({
+ label: `Install ${p.name} ↗`,
+ href: walletInstallUrl(p.key),
+ })),
+ );
+}
+
+async function headerConnectWallet(key, btn) {
+ closeWalletMenu();
+ const label = btn.querySelector('.mkt-wallet-label');
+ const prev = label?.textContent;
+ if (label) label.textContent = 'Connecting…';
+ btn.classList.add('is-busy');
+ btn.disabled = true;
+ try {
+ // Sets connectedWallet then notifyWalletChanged() re-renders every slot.
+ await connectWalletProvider(key);
+ } catch (e) {
+ btn.disabled = false;
+ btn.classList.remove('is-busy');
+ if (label) label.textContent = prev || 'Connect Wallet';
+ const rejected = e?.code === 4001 || /reject|cancel/i.test(e?.message || '');
+ flashWalletBubble(btn, rejected ? 'Connection cancelled.' : e?.message || 'Could not connect wallet.', 'err');
+ }
+}
+
+function openConnectedWalletMenu(btn) {
+ if (!connectedWallet) return;
+ const pk = connectedWallet.publicKey.toBase58();
+ openWalletMenu(btn, [
+ { label: 'Copy address', onClick: () => copyWalletAddress(pk, btn) },
+ { label: 'View on Solscan ↗', href: WALLET_EXPLORER + pk },
+ { label: 'Disconnect', danger: true, onClick: () => disconnectWallet() },
+ ]);
+}
+
+async function copyWalletAddress(pk, btn) {
+ closeWalletMenu();
+ try {
+ await navigator.clipboard.writeText(pk);
+ flashWalletBubble(btn, 'Address copied', 'ok');
+ } catch {
+ flashWalletBubble(btn, 'Copy failed', 'err');
+ }
+}
+
+// Keep the header in sync when the user disconnects or switches accounts from
+// the wallet extension itself (not just via our UI). Bound once per provider.
+function bindProviderEvents(provider, name) {
+ if (!provider?.on || _walletEventsBound.has(provider)) return;
+ _walletEventsBound.add(provider);
+ provider.on('disconnect', () => {
+ if (connectedWallet?.provider === provider) {
+ connectedWallet = null;
+ notifyWalletChanged();
+ }
+ });
+ provider.on('accountChanged', async (pubKey) => {
+ if (connectedWallet?.provider !== provider) return;
+ if (!pubKey) {
+ connectedWallet = null;
+ notifyWalletChanged();
+ return;
+ }
+ const { web3 } = await loadSolanaModules();
+ connectedWallet = {
+ provider,
+ name,
+ publicKey: typeof pubKey === 'string' ? new web3.PublicKey(pubKey) : pubKey,
+ };
+ notifyWalletChanged();
+ });
+}
+
+// Silently restore a previously-authorized session on load — no popup. Phantom
+// & friends resolve connect({ onlyIfTrusted:true }) only when already trusted.
+async function eagerReconnectWallet() {
+ if (connectedWallet) return;
+ for (const entry of WALLET_PROVIDERS) {
+ const provider = entry.detect();
+ if (!provider?.connect) continue;
+ try {
+ const resp = await provider.connect({ onlyIfTrusted: true });
+ const pubKey = resp?.publicKey ?? provider.publicKey;
+ if (!pubKey) continue;
+ const { web3 } = await loadSolanaModules();
+ connectedWallet = {
+ provider,
+ name: entry.name,
+ publicKey: typeof pubKey === 'string' ? new web3.PublicKey(pubKey) : pubKey,
+ };
+ bindProviderEvents(provider, entry.name);
+ notifyWalletChanged();
+ return;
+ } catch {
+ // Not trusted for this origin — try the next provider silently.
+ }
+ }
+}
+
+function mountHeaderWallet() {
+ if (!document.querySelector('[data-wallet-connect]')) return;
+ renderHeaderWallet();
+ eagerReconnectWallet();
+}
+
+// ── Header wallet dropdown / feedback primitives ───────────────────────────
+//
+// A single body-mounted, viewport-clamped popover anchored to the wallet
+// button (so the sidebar/topbar can't clip it). Closes on outside-click,
+// Escape, scroll, or resize.
+
+let _walletMenuEl = null;
+let _walletMenuAnchor = null;
+
+function openWalletMenu(anchor, items) {
+ closeWalletMenu();
+ const menu = document.createElement('div');
+ menu.className = 'mkt-wallet-menu';
+ menu.setAttribute('role', 'menu');
+ for (const item of items) {
+ let el;
+ if (item.href) {
+ el = document.createElement('a');
+ el.href = item.href;
+ el.target = '_blank';
+ el.rel = 'noopener';
+ } else {
+ el = document.createElement('button');
+ el.type = 'button';
+ el.addEventListener('click', () => item.onClick?.());
+ }
+ el.className = 'mkt-wallet-menu-item' + (item.danger ? ' danger' : '');
+ el.setAttribute('role', 'menuitem');
+ el.textContent = item.label;
+ menu.appendChild(el);
+ }
+ document.body.appendChild(menu);
+ positionFloating(menu, anchor);
+ anchor.setAttribute('aria-expanded', 'true');
+ _walletMenuEl = menu;
+ _walletMenuAnchor = anchor;
+ requestAnimationFrame(() => menu.querySelector('.mkt-wallet-menu-item')?.focus());
+ // Defer binding so the click that opened the menu doesn't immediately close it.
+ setTimeout(() => {
+ document.addEventListener('click', onWalletMenuOutside, true);
+ document.addEventListener('keydown', onWalletMenuKeydown, true);
+ window.addEventListener('resize', closeWalletMenu);
+ window.addEventListener('scroll', closeWalletMenu, true);
+ }, 0);
+}
+
+function closeWalletMenu() {
+ _walletMenuAnchor?.setAttribute('aria-expanded', 'false');
+ _walletMenuEl?.remove();
+ _walletMenuEl = null;
+ _walletMenuAnchor = null;
+ document.removeEventListener('click', onWalletMenuOutside, true);
+ document.removeEventListener('keydown', onWalletMenuKeydown, true);
+ window.removeEventListener('resize', closeWalletMenu);
+ window.removeEventListener('scroll', closeWalletMenu, true);
+}
+
+function onWalletMenuOutside(e) {
+ if (!_walletMenuEl) return;
+ if (_walletMenuEl.contains(e.target)) return;
+ if (_walletMenuAnchor?.contains(e.target)) return;
+ closeWalletMenu();
+}
+
+function onWalletMenuKeydown(e) {
+ if (e.key === 'Escape') {
+ const anchor = _walletMenuAnchor;
+ closeWalletMenu();
+ anchor?.focus();
+ }
+}
+
+function positionFloating(el, anchor) {
+ const r = anchor.getBoundingClientRect();
+ const w = el.offsetWidth || 200;
+ let left = r.left;
+ if (left + w > window.innerWidth - 8) left = Math.max(8, r.right - w);
+ el.style.top = `${Math.round(r.bottom + 6)}px`;
+ el.style.left = `${Math.round(left)}px`;
+}
+
+let _walletBubbleTimer;
+function flashWalletBubble(anchor, text, kind) {
+ const bubble = document.createElement('div');
+ bubble.className = 'mkt-wallet-bubble' + (kind ? ` ${kind}` : '');
+ bubble.setAttribute('role', 'status');
+ bubble.textContent = text;
+ document.body.appendChild(bubble);
+ positionFloating(bubble, anchor);
+ requestAnimationFrame(() => bubble.classList.add('show'));
+ clearTimeout(_walletBubbleTimer);
+ _walletBubbleTimer = setTimeout(() => {
+ bubble.classList.remove('show');
+ setTimeout(() => bubble.remove(), 250);
+ }, 2600);
+}
+
function setStatus(text, kind) {
const el = $('payment-status');
if (!el) return;
@@ -7065,6 +7352,7 @@ function setupAccessibleDialogs() {
function init() {
bindEvents();
setupAccessibleDialogs();
+ mountHeaderWallet();
loadCategories();
loadList(true);
loadTheme();
diff --git a/src/wallet.js b/src/wallet.js
index 097595012..92542a0bf 100644
--- a/src/wallet.js
+++ b/src/wallet.js
@@ -53,7 +53,23 @@ async function onConnectWallet() {
export function updateWalletState(address) {
const btn = document.getElementById('connect-wallet-btn');
if (btn) {
- btn.textContent = address ? `${address.slice(0, 4)}...${address.slice(-4)}` : 'Connect Wallet';
+ const short = address ? `${address.slice(0, 4)}...${address.slice(-4)}` : 'Connect Wallet';
+ // Buttons that wrap their text in a [data-wallet-label] span keep their
+ // icon/markup intact across state changes; plain-text buttons (e.g. the
+ // pump dashboard) fall back to replacing textContent.
+ const label = btn.querySelector('[data-wallet-label]');
+ if (label) label.textContent = short;
+ else btn.textContent = short;
+ btn.classList.toggle('is-connected', Boolean(address));
+ if (address) {
+ btn.title = `Connected: ${address}`;
+ btn.setAttribute('aria-label', `Solana wallet connected: ${address}`);
+ btn.dataset.address = address;
+ } else {
+ btn.title = 'Connect your Solana wallet';
+ btn.setAttribute('aria-label', 'Connect your Solana wallet');
+ delete btn.dataset.address;
+ }
}
// Broadcast so consumers (dashboards, balance panels) can react to connect /
// disconnect without reaching into window.solana directly. Fires for both the
diff --git a/tasks/agent-monetization/08-monetization-settings-ui.md b/tasks/agent-monetization/08-monetization-settings-ui.md
deleted file mode 100644
index 712b809b1..000000000
--- a/tasks/agent-monetization/08-monetization-settings-ui.md
+++ /dev/null
@@ -1,84 +0,0 @@
-# Task 08 — Frontend: Monetization Settings Tab in Agent Editor
-
-## Goal
-Add a "Monetization" tab to the existing agent settings/editor UI so owners can configure skill prices and payout wallet without leaving the agent management flow.
-
-## Success Criteria
-- Tab appears in the agent editor only for the agent's owner
-- Loads existing prices on open
-- Owner can add/edit/remove prices per skill
-- Skill list is populated from the agent's registered skills
-- Changes call the pricing API (Task 02) and show success/error feedback
-- Payout wallet section lets owner add or change their Solana/Base payout address
-
-## Approach
-
-### Where to add the tab
-Search for the agent editor/settings component. Likely in:
-- `src/components/agent-editor.jsx` or similar
-- Or a settings panel in the main agent detail page
-
-Add a new tab entry: `Monetization` alongside existing tabs (Identity, Skills, Memory, etc.).
-
-### Tab Content Structure
-
-```
-Monetization
-├── Skill Prices
-│ ├── [skill name] [amount input] [currency dropdown] [active toggle] [Save]
-│ ├── [skill name] ...
-│ └── [+ Add skill price] button
-└── Payout Wallet
- ├── Solana: [address input or connected wallet selector] [Set as payout]
- └── Base/EVM: [address input] [Set as payout]
-```
-
-### Skill List Source
-Fetch from `GET /api/agents/:id` — the agent's `skills[]` array lists registered skills. Use these as the options in the skill name dropdown/selector.
-
-### Component: `SkillPriceRow`
-```jsx
-// Props: skill, price (may be null), agentId, onSave, onDelete
-// Renders: skill name label, amount input (number), currency select, is_active toggle, Save/Delete buttons
-```
-
-### API Calls
-- On mount: `GET /api/agents/:id/pricing` to load existing prices
-- On save row: `PUT /api/agents/:id/pricing/:skill`
-- On delete row: `DELETE /api/agents/:id/pricing/:skill`
-- Payout wallet: `GET /api/billing/payout-wallets` on mount, `POST` to add
-
-### Currency Options
-Display human-readable labels:
-- Solana USDC: mint `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`
-- Base USDC: address `0x833589fcd6edb6e08f4c7c32d4f71b54bda02913`
-
-Amount inputs should be in human units (USDC with 6 decimal places), converted to `bigint` (×10^6) before sending to API.
-
-## Files to Touch
-- Find and edit the agent editor component (search `agent-editor` or `settings` in `src/components/`)
-- Add new component file `src/components/monetization-settings.jsx`
-
-## Do NOT Change
-- Other tabs in the editor
-- Agent identity or skill registration flows
-
-## Verify
-1. Open agent editor as owner → "Monetization" tab is visible
-2. Open agent editor as non-owner (or logged out) → tab is hidden
-3. Set a price for a skill → price persists after page reload
-4. Remove a price → skill returns to free
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/agent-monetization/08-monetization-settings-ui.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/agent-monetization/15-cron-withdrawal-processor.md b/tasks/agent-monetization/15-cron-withdrawal-processor.md
deleted file mode 100644
index dca629e0b..000000000
--- a/tasks/agent-monetization/15-cron-withdrawal-processor.md
+++ /dev/null
@@ -1,125 +0,0 @@
-# Task 15 — Cron: Withdrawal Processor
-
-## Goal
-A cron job that picks up `pending` withdrawal requests and executes the on-chain transfer, then marks them `completed` or `failed`. This is the backend job that actually moves funds.
-
-## Success Criteria
-- Cron runs at a configurable interval (default: every 15 minutes)
-- Picks up rows with `status = 'pending'` in `agent_withdrawals`
-- For Solana USDC: transfers SPL token from the platform escrow/treasury wallet to `to_address`
-- Marks `processing` before sending, `completed` with tx hash after confirmation, `failed` on error
-- A single failed transfer doesn't block other pending withdrawals
-- Re-entrancy is safe: each row is locked with `SELECT ... FOR UPDATE SKIP LOCKED`
-
-## Implementation
-
-### File: `/api/cron/process-withdrawals.js`
-
-```js
-export default async function handler(req, res) {
- // Verify Vercel cron secret
- if (req.headers['authorization'] !== `Bearer ${process.env.CRON_SECRET}`) {
- return res.status(401).end();
- }
-
- // Lock and fetch pending withdrawals (process up to 10 at a time)
- const rows = await db.query(`
- SELECT * FROM agent_withdrawals
- WHERE status = 'pending'
- ORDER BY created_at ASC
- LIMIT 10
- FOR UPDATE SKIP LOCKED
- `);
-
- for (const row of rows) {
- try {
- // Mark processing
- await db.query(
- `UPDATE agent_withdrawals SET status='processing', updated_at=now() WHERE id=$1`,
- [row.id]
- );
-
- // Execute transfer (Solana USDC example)
- const txSig = await transferSolanaUSDC({
- fromWallet: process.env.PLATFORM_TREASURY_KEYPAIR, // base58 keypair
- toAddress: row.to_address,
- amount: row.amount, // lamports
- mint: row.currency_mint,
- });
-
- // Mark completed
- await db.query(
- `UPDATE agent_withdrawals SET status='completed', tx_signature=$1, updated_at=now() WHERE id=$2`,
- [txSig, row.id]
- );
- } catch (err) {
- console.error(`Withdrawal ${row.id} failed:`, err.message);
- await db.query(
- `UPDATE agent_withdrawals SET status='failed', updated_at=now() WHERE id=$1`,
- [row.id]
- );
- }
- }
-
- res.json({ processed: rows.length });
-}
-```
-
-### Solana Transfer Helper
-Create `/api/_lib/solana-transfer.js`:
-```js
-export async function transferSolanaUSDC({ fromWallet, toAddress, amount, mint }) {
- // Use @solana/web3.js + @solana/spl-token
- // createTransferInstruction → send transaction → return signature
-}
-```
-
-Reference existing Solana code in `/api/agents/` or `/src/wallet/` for patterns.
-
-## Vercel Cron Config
-Add to `vercel.json`:
-```json
-{
- "crons": [
- { "path": "/api/cron/process-withdrawals", "schedule": "*/15 * * * *" }
- ]
-}
-```
-
-## Required Env Vars
-- `PLATFORM_TREASURY_KEYPAIR` — base58 private key of the platform's treasury wallet (holds float for payouts)
-- `CRON_SECRET` — shared secret for cron authorization (already used by other crons)
-
-## Files to Create/Touch
-- `/api/cron/process-withdrawals.js` — new cron handler
-- `/api/_lib/solana-transfer.js` — new Solana transfer helper
-- `vercel.json` — add cron entry
-
-## Security Notes
-- `PLATFORM_TREASURY_KEYPAIR` must never be logged or returned in responses
-- All DB mutations should be inside a transaction where possible
-- `SKIP LOCKED` prevents two cron instances from double-processing the same row
-
-## Verify
-```bash
-# Simulate cron call
-curl -X GET /api/cron/process-withdrawals \
- -H "Authorization: Bearer $CRON_SECRET"
-
-# Check withdrawal status changed
-psql $DATABASE_URL -c "SELECT id, status, tx_signature FROM agent_withdrawals ORDER BY created_at DESC LIMIT 5;"
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/agent-monetization/15-cron-withdrawal-processor.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/agent-monetization/16-rate-limiting-and-abuse.md b/tasks/agent-monetization/16-rate-limiting-and-abuse.md
deleted file mode 100644
index 90c354522..000000000
--- a/tasks/agent-monetization/16-rate-limiting-and-abuse.md
+++ /dev/null
@@ -1,101 +0,0 @@
-# Task 16 — Rate Limiting & Abuse Prevention for Paid Skills
-
-## Goal
-Prevent abuse of the payment and pricing APIs: rate-limit payment intent creation, prevent fake intent replays, and ensure callers can't enumerate skill prices to scrape agent configurations at scale.
-
-## Success Criteria
-- Payment intent creation is rate-limited per caller address
-- Replayed payment proofs are rejected (idempotency enforcement)
-- Pricing endpoint has a reasonable public rate limit
-- Withdrawal endpoint is rate-limited per user
-
-## Changes
-
-### 1. Payment Intent Rate Limit
-In the x402 intent creation handler, add a per-payer rate limit using the existing Upstash Redis rate limiter.
-
-Add a new rate limit bucket to `/api/_lib/rate-limit.js`:
-```js
-export const paymentIntentPerPayer = rateLimit({
- prefix: 'payment_intent_payer',
- limit: 20,
- window: 60, // 20 intents per minute per payer address
-});
-```
-
-Apply in the intent creation endpoint:
-```js
-const limited = await paymentIntentPerPayer.check(payerAddress);
-if (limited) return error(res, 429, 'rate_limited', 'Too many payment attempts');
-```
-
-### 2. Intent Replay Prevention
-Payment intents already have a unique `id` and status machine. Ensure the skill access handler checks:
-```sql
-SELECT status FROM agent_payment_intents
-WHERE id = $1 AND status = 'paid'
-FOR UPDATE
-```
-If `status != 'paid'` → reject with 409. The existing `status = 'consumed'` update inside a transaction handles this, but verify it's in a transaction (`BEGIN/COMMIT`).
-
-### 3. Pricing Endpoint Public Rate Limit
-Add to the GET `/api/agents/:id/pricing` handler:
-```js
-export const pricingPerIp = rateLimit({
- prefix: 'pricing_ip',
- limit: 100,
- window: 60, // 100 reads/minute per IP
-});
-```
-
-### 4. Withdrawal Rate Limit
-In `POST /api/billing/withdrawals`, add:
-```js
-export const withdrawalPerUser = rateLimit({
- prefix: 'withdrawal_user',
- limit: 3,
- window: 3600, // 3 withdrawal requests per hour per user
-});
-```
-
-### 5. Minimum Withdrawal Amount
-In the withdrawal API (Task 07), enforce a minimum amount (e.g., 1 USDC = 1,000,000 lamports):
-```js
-const MIN_WITHDRAWAL = 1_000_000;
-if (amount < MIN_WITHDRAWAL) {
- return error(res, 422, 'below_minimum', 'Minimum withdrawal is 1 USDC');
-}
-```
-
-## Files to Touch
-- `/api/_lib/rate-limit.js` — add 3 new rate limit configs
-- The x402 intent creation handler — add payer rate limit
-- `/api/agents/:id/pricing` GET handler — add IP rate limit
-- `/api/billing/withdrawals/index.js` — add user rate limit and minimum
-
-## Verify
-```bash
-# Hammer intent creation from same address — should 429 after 20 req/min
-for i in {1..25}; do curl -X POST /api/agents/:id/x402/:skill/prep ...; done
-
-# Replay intent ID — should 409
-curl POST .../x402/:skill/consume with same intent_id twice
-
-# Withdrawal below minimum
-curl POST /api/billing/withdrawals -d '{"amount":100,...}'
-# → 422 below_minimum
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/agent-monetization/16-rate-limiting-and-abuse.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/agent-monetization/17-notifications.md b/tasks/agent-monetization/17-notifications.md
deleted file mode 100644
index 01863d153..000000000
--- a/tasks/agent-monetization/17-notifications.md
+++ /dev/null
@@ -1,108 +0,0 @@
-# Task 17 — Notifications: Earnings Alerts for Agent Owners
-
-## Goal
-Notify agent owners when they receive a payment (and when a withdrawal completes). This closes the feedback loop so owners know their monetized agents are generating revenue without having to check the dashboard.
-
-## Success Criteria
-- Owner receives a notification when an `agent_revenue_events` row is inserted
-- Owner receives a notification when a withdrawal transitions to `completed` or `failed`
-- Notifications are non-blocking (fire-and-forget, failure silently logged not thrown)
-- Owners can opt out per notification type
-
-## Notification Types to Implement
-
-### In-app notifications (simplest, do this first)
-Add a `notifications` table:
-```sql
-CREATE TABLE user_notifications (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- type TEXT NOT NULL, -- "payment_received" | "withdrawal_completed" | "withdrawal_failed"
- payload JSONB NOT NULL,
- read_at TIMESTAMPTZ,
- created_at TIMESTAMPTZ NOT NULL DEFAULT now()
-);
-CREATE INDEX ON user_notifications (user_id, read_at, created_at DESC);
-```
-
-### Endpoints
-
-`GET /api/notifications` — list unread notifications for the current user
-```json
-{
- "notifications": [
- {
- "id": "uuid",
- "type": "payment_received",
- "payload": { "agent_name": "Atlas", "skill": "answer-question", "net_amount": 950000 },
- "created_at": "2026-04-30T12:00:00Z"
- }
- ],
- "unread_count": 3
-}
-```
-
-`POST /api/notifications/:id/read` — mark a notification read
-
-`POST /api/notifications/read-all` — mark all read
-
-### When to Write Notifications
-
-**Payment received** — in the revenue attribution code (Task 04), after inserting the `agent_revenue_events` row:
-```js
-await db.query(
- `INSERT INTO user_notifications (user_id, type, payload)
- SELECT ai.user_id, 'payment_received',
- jsonb_build_object(
- 'agent_id', $2,
- 'skill', $3,
- 'net_amount', $4,
- 'currency_mint', $5
- )
- FROM agent_identities ai WHERE ai.id = $2`,
- [/* ... */]
-);
-```
-
-**Withdrawal completed/failed** — in the cron processor (Task 15), after updating withdrawal status.
-
-### UI: Notification Bell
-In the main nav/header, add a bell icon with an unread count badge.
-- Fetches `GET /api/notifications` on load (and on focus)
-- Clicking opens a dropdown list of recent notifications
-- "Mark all read" button
-
-Keep the component small — a simple dropdown, not a full page.
-
-## Email Notifications (optional, lower priority)
-If `SENDGRID_API_KEY` or an SMTP env var is configured, also send an email. Make this opt-in via user preferences. Implement only if the in-app version is working.
-
-## Files to Create/Touch
-- `/api/_lib/migrations/014_notifications.sql` — new table
-- `/api/notifications/index.js` — GET
-- `/api/notifications/[id]/read.js` — POST
-- `/api/notifications/read-all.js` — POST
-- Revenue attribution handler (Task 04) — add notification insert
-- Cron withdrawal processor (Task 15) — add notification insert
-- `src/components/notification-bell.jsx` — new component
-- Main layout/nav component — wire in notification bell
-
-## Verify
-1. Complete a payment for a priced skill → notification appears in bell within one page reload
-2. Click bell → dropdown shows "Atlas received payment: 0.95 USDC for answer-question"
-3. Click "Mark all read" → badge clears
-4. Withdrawal completes → "Withdrawal of 1.00 USDC sent" notification appears
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/agent-monetization/17-notifications.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/agent-monetization/19-security-review.md b/tasks/agent-monetization/19-security-review.md
deleted file mode 100644
index a60968105..000000000
--- a/tasks/agent-monetization/19-security-review.md
+++ /dev/null
@@ -1,81 +0,0 @@
-# Task 19 — Security Review: Agent Monetization Feature
-
-## Goal
-Before shipping, conduct a targeted security review of all new code added in Tasks 01–18. Focus on the highest-risk areas: payment flows, authorization boundaries, and financial data integrity.
-
-## Method
-Run `/security-review` on the branch containing all monetization changes, then manually verify each item in the checklist below.
-
-## Checklist
-
-### Authorization
-- [ ] Every pricing write endpoint (`PUT`, `DELETE`) verifies `agent.user_id === session.user_id`
-- [ ] Revenue data endpoints (`/billing/revenue`, `/billing/withdrawals`) are scoped to the authenticated user only — no other user's data leaks
-- [ ] Admin endpoints (`/admin/revenue`, `PATCH /admin/withdrawals/:id`) require `is_admin = true` on the user row
-- [ ] Public endpoints (`GET /api/agents/:id/pricing`, `GET /api/billing/fee-info`) return no sensitive data (wallet private keys, user emails, session tokens)
-
-### Payment Integrity
-- [ ] Intent status transitions are atomic (inside a DB transaction)
-- [ ] `status = 'consumed'` is only set once per intent (idempotency)
-- [ ] `agent_revenue_events.intent_id` has a unique constraint or the insert is inside the same transaction as the status update
-- [ ] `gross_amount = fee_amount + net_amount` is enforced in the insert, not just the application layer
-- [ ] Payment proof signature is verified on the backend before marking intent as `paid` (check existing x402 verification is still called)
-
-### Financial Data
-- [ ] `agent_revenue_events` is append-only (no UPDATE or DELETE allowed from application code)
-- [ ] Withdrawal amount cannot exceed available balance (checked with `SELECT FOR UPDATE` to prevent race conditions)
-- [ ] `PLATFORM_TREASURY_KEYPAIR` is never logged, returned in responses, or stored in the DB
-
-### Input Validation
-- [ ] Skill name in pricing API is validated against `^[a-z0-9-]{1,64}$` (prevent injection via skill name)
-- [ ] Amount fields are integers — no floating-point arithmetic in financial calculations
-- [ ] Payout wallet addresses are validated for correct format per chain before storage
-
-### Rate Limiting
-- [ ] Payment intent creation: rate-limited per payer address
-- [ ] Withdrawal creation: rate-limited per user (max 3/hour)
-- [ ] Pricing read: rate-limited per IP
-
-### CSRF
-- [ ] All state-mutating endpoints (POST, PUT, DELETE, PATCH) that accept session cookie auth require CSRF token verification (check existing `verifyCsrfToken()` is applied)
-
-### Data Leakage
-- [ ] Error messages in payment endpoints do not reveal internal state (intent IDs, stack traces) to callers
-- [ ] Withdrawal `to_address` is not returned to non-owners (the admin endpoint is OK, but the user-facing GET should only return their own)
-
-## Files to Review
-All files created/modified in Tasks 01–18:
-- `/api/_lib/migrations/013_agent_monetization.sql`
-- `/api/_lib/fee.js`
-- `/api/_lib/payout.js`
-- `/api/_lib/solana-transfer.js`
-- `/api/agents/[id]/pricing/*.js`
-- `/api/billing/revenue.js`
-- `/api/billing/withdrawals/*.js`
-- `/api/billing/payout-wallets/*.js`
-- `/api/billing/fee-info.js`
-- `/api/cron/process-withdrawals.js`
-- `/api/notifications/*.js`
-- The modified x402 manifest endpoint
-
-## Output
-Create a brief report listing:
-1. Any HIGH severity findings with the file + line number
-2. Any MEDIUM findings
-3. Confirmation that all checklist items passed
-
-Fix all HIGH and MEDIUM findings before merging.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/agent-monetization/19-security-review.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tests/src/wallet-connect-button.test.js b/tests/src/wallet-connect-button.test.js
new file mode 100644
index 000000000..17e727e63
--- /dev/null
+++ b/tests/src/wallet-connect-button.test.js
@@ -0,0 +1,91 @@
+// @vitest-environment jsdom
+//
+// Header "Connect Wallet" button — the DOM-facing contract of src/wallet.js
+// that the app shell (pages/app.html) and pump dashboard both bind. Covers the
+// label/address swap, the connected-state class + a11y attributes, the
+// icon-preserving [data-wallet-label] path, the plain-text fallback other
+// surfaces rely on, the wallet:changed broadcast, and that initWalletButton
+// wires a click without a wallet present.
+
+import { describe, it, expect, afterEach, vi } from 'vitest';
+
+// The Seeker/MWA boot (and its @solana/web3.js import) is a no-op off-device;
+// stub it so this unit stays light and fast.
+vi.mock('../../solana-mobile/src/index.js', () => ({}));
+
+import {
+ updateWalletState,
+ initWalletButton,
+ getConnectedWalletAddress,
+} from '../../src/wallet.js';
+
+const ADDR = 'So11111111111111111111111111111111111111112';
+const SHORT = `${ADDR.slice(0, 4)}...${ADDR.slice(-4)}`;
+
+afterEach(() => {
+ document.body.innerHTML = '';
+ vi.restoreAllMocks();
+});
+
+function mountIconButton() {
+ document.body.innerHTML = `
+ <button id="connect-wallet-btn" title="Connect your Solana wallet" aria-label="Connect your Solana wallet">
+ <svg></svg><span data-wallet-label>Connect Wallet</span>
+ </button>`;
+ return document.getElementById('connect-wallet-btn');
+}
+
+describe('connect-wallet button state', () => {
+ it('shows the truncated address and connected affordances on connect', () => {
+ const btn = mountIconButton();
+ updateWalletState(ADDR);
+ expect(btn.querySelector('[data-wallet-label]').textContent).toBe(SHORT);
+ expect(btn.querySelector('svg')).toBeTruthy(); // icon survives the swap
+ expect(btn.classList.contains('is-connected')).toBe(true);
+ expect(btn.dataset.address).toBe(ADDR);
+ expect(btn.getAttribute('aria-label')).toContain(ADDR);
+ expect(btn.title).toContain(ADDR);
+ });
+
+ it('resets to the default prompt on disconnect', () => {
+ const btn = mountIconButton();
+ updateWalletState(ADDR);
+ updateWalletState(null);
+ expect(btn.querySelector('[data-wallet-label]').textContent).toBe('Connect Wallet');
+ expect(btn.classList.contains('is-connected')).toBe(false);
+ expect('address' in btn.dataset).toBe(false);
+ expect(btn.getAttribute('aria-label')).toBe('Connect your Solana wallet');
+ });
+
+ it('falls back to textContent for plain-text buttons (no label span)', () => {
+ document.body.innerHTML = '<button id="connect-wallet-btn">Connect Wallet</button>';
+ const btn = document.getElementById('connect-wallet-btn');
+ updateWalletState(ADDR);
+ expect(btn.textContent).toBe(SHORT);
+ expect(btn.classList.contains('is-connected')).toBe(true);
+ });
+
+ it('broadcasts wallet:changed with the address on connect and disconnect', () => {
+ mountIconButton();
+ const seen = [];
+ const handler = (e) => seen.push(e.detail.address);
+ window.addEventListener('wallet:changed', handler);
+ updateWalletState(ADDR);
+ updateWalletState(null);
+ window.removeEventListener('wallet:changed', handler);
+ expect(seen).toEqual([ADDR, null]);
+ });
+
+ it('is a no-op (no throw) when the button is absent', () => {
+ expect(() => updateWalletState(ADDR)).not.toThrow();
+ });
+
+ it('initWalletButton binds a click that points users at Phantom when no wallet is injected', () => {
+ const btn = mountIconButton();
+ const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
+ initWalletButton(); // window.solana undefined → no provider, auto-connect skipped
+ btn.click();
+ expect(openSpy).toHaveBeenCalledWith('https://phantom.app/', '_blank', 'noopener');
+ expect(getConnectedWalletAddress()).toBe(null);
+ });
+});