Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: x402 payment modal, wallet hub give tab, and store updates

nirholase3903c849e87
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a8ee6f562..d93d1b1fe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -52,6 +52,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **One API, many services: the three.ws API gateway** — We bundled a stack of popular third-party APIs behind a single three.ws API so you can reach them all with one integration, one key, and one bill. The first providers are live at /api/v1/x — CoinGecko (live prices and ranked market data), DefiLlama (protocol TVL across all of DeFi), and any OpenAI-compatible LLM — with more landing over the coming releases. Discover everything with one call to GET /api/v1, which returns the full catalog: every provider, endpoint, parameter, and price. You can pay three ways, your choice per call: bring your own upstream key (we just route it, no markup), use a three.ws API key on your plan, or pay-per-call in USDC with no account at all. Every response uses one consistent shape with standard rate-limit headers, and the platform's own capabilities — text sentiment, market and narrative intelligence, and verified agent-card lookups — live under the same /api/v1 surface. `[feature, sdk]`
- **Paid doors stay open when one payment network is down** — Every pay-per-call endpoint — the Pole Club cover charge, agent-to-agent calls, asset downloads — now offers each payment network independently. If Base is fully wired but Solana is missing a setting (or vice versa), you still get a working payment prompt on the network that's ready, instead of the whole door hard-failing. A network is advertised only when every piece it needs is in place, so a checkout can no longer be offered and then rejected mid-payment. The endpoint only declines outright when no network at all can take the payment. `[fix]`
- **Paid market-intel never charges you for unavailable data** — The pay-per-call market-intel endpoints (the $THREE Town Oracle and the crypto-intel kiosk) used to hand back an estimated "neutral" reading — and still take the payment — when their live price feed was rate-limited. They now return a clean "temporarily unavailable, retry shortly" instead, and crucially the payment is never settled when live data is missing. You only pay when you get a real, live signal. `[fix]`
+- **Pay any x402 endpoint in $THREE, not just USDC** — The three.ws payment modal now treats $THREE as a first-class settlement token on Solana, right alongside USDC. When an endpoint accepts both, a token chooser appears in checkout so you decide which to pay with — the headline price, the Phantom transaction, and the receipt all switch to your pick. $THREE (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump) is recognized by its mint, so it shows its own ticker and badge even when the merchant doesn't label it. The payment is still a single gasless signature with the network fee sponsored by the facilitator. Endpoint operators turn the $THREE option on with one setting; the drop-in modal and its solanaAccept() helper support it out of the box. `[feature, sdk]`
- **Pay-per-call vanity wallets now do seed phrases and encrypted delivery** — The on-demand vanity address service — the one any app or agent can call and pay for per use, no account needed — can now hand back a 12- or 24-word seed phrase instead of just a raw key, so the wallet it grinds restores straight into Phantom, Solflare, or any wallet as a recovery phrase. And if you'd rather the secret never travel in the clear, you can now have it encrypted to a key only you hold: the service seals the result so the private key or seed phrase is unreadable to anyone in between — it isn't written to any log or cache, and only you can open it. The plain address still comes back in the clear so you can look it up right away. (`/vanity-wallet`) `[feature, security]`
- **Payment dialog no longer pushes its Pay button off-screen** — On agent profiles, the Unlock skill / purchase dialog had no height limit. When the form ran tall — wallet area, price, fee note, Confirm button, and QR code together — it grew past the screen, so the title was shoved above the top edge and the Pay button dropped below the bottom, and neither could be scrolled to. The dialog is now capped to the visible screen with the form scrolling inside it and the header pinned, so the Pay button is always reachable on any screen size. `[fix]`
- **Pick who walks your pages — diverse avatar roster + Walk SDK** — The walking companion that strolls the corner of every page (and detaches into the full-page playground) now lets you choose your character. A new picker offers a diverse roster — a robot mascot, humanoids, photoreal people, a fox, dancers and showpieces — and swaps the avatar live. Each one is animated correctly whether its model ships its own moves or borrows the shared motion library, so nobody ever freezes mid-stride. Under the hood the whole companion + playground is now a standalone SDK (@three-ws/walk) you can drop into any Three.js site. `[feature, sdk]`
@@ -62,6 +63,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Premium avatar cosmetics are now buyable right in the character creator** — Locked premium headwear, eyewear, dyes and auras in the character creator no longer dead-end on a placeholder — clicking one now opens the real wallet checkout and unlocks it the moment the USDC payment settles, then equips it on your live preview. Anything you already own loads pre-unlocked, and the price you see is the true checkout amount pulled from the catalog. (`/create`) `[feature, fix]`
- **Put a talking 3D guide on any website — new @three-ws/page-agent SDK** — Drop one tag onto any site and a rigged 3D agent appears in the corner, greets visitors, and talks them through the page out loud — mouth moving in time with the words, all in the browser with no backend or API key. Visitors pick who guides them from a diverse roster of rigged agents (realistic, stylized, and a robot), and the choice is remembered as they move between pages. Only skeleton-rigged avatars ship in the catalog, so every guide actually breathes, blinks, and lip-syncs instead of standing frozen. Install @three-ws/page-agent from npm, or paste the one-line embed. `[sdk, feature]`
- **Rigged-or-not filter across your Agents and Avatars** — The rigged-or-not category now reaches everything you own, not just the public gallery. Your Avatars page (both My avatars and the Community tab) and your Agents page each get a Rigged / Static filter and a badge on every card, so you can tell at a glance which models carry a skeleton and can play the animation library — and narrow the list to just the animation-ready ones. An agent's badge reflects the rig state of its 3D body. (`/dashboard/avatars`) `[feature]`
+- **Roaming links no longer open just by standing on them** — In full-page roaming mode — stroll or platformer — walking your avatar onto a link used to dive into it on its own after a short pause, which made it easy to leave a page by accident. Now standing on a link only arms it (it glows with a prompt) and you commit deliberately: press Space / Enter / E or tap the dive button in stroll mode, or press ↓ / the dive button in platformer mode. Gamepads work too — the left stick or d-pad walks, ✕/○ dive in stroll, and pushing down or ○ dives in platformer — so a controller drives the avatar exactly like the keyboard. `[improvement, sdk]`
- **Saved avatar now shows the real model on the "what's next" screen** — After saving an avatar you'd made — including ones built from a template — the post-save "your agent is ready" screen showed a blank white mannequin instead of the avatar you just created, even though the name was correct. The page was looking for the model under a field name the agent record doesn't use, and never fell back to the avatar itself. It now loads your actual avatar — and works even for private avatars you've just made. `[fix]`
- **See your net take when you price a skill** — The Skill Pricing panel on the Monetize dashboard now shows exactly what you keep on every payment. As you type a per-call price, a line below the field updates live — "You receive $X.XX after 2.5% fee" — so the platform's cut is never a surprise at payout time. The same net figure appears in the Add Pricing dialog, and the panel header states the current platform fee rate, which is read from the live billing config rather than hardcoded. (`/dashboard/monetize`) `[feature, improvement]`
- **Shared agent links now unfurl with the agent's own avatar** — When you paste a link to an agent on X, Discord, Slack, Telegram or iMessage, the preview card now shows that agent's actual avatar, name and description instead of a generic three.ws image — so every shared link is visual proof of the collectible. Bots that don't run JavaScript get the right image and text rendered on the server, and agents without an avatar yet fall back to a clean branded card with their initial. We also fixed the canonical and share URLs on agent pages to point at the real /agents/<id> address. `[feature, improvement]`
@@ -73,7 +75,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The $THREE token page is now the single home for the coin** — We retired the separate economy explainer and consolidated everything about $THREE onto one page: live price, the bonding-curve chart, streaming trades, and one-click buy. Every place that pointed you to "learn about $THREE" or "get $THREE" — the holder badges, the Forge high-quality unlock prompts, and the holder gates across the app — now takes you straight to the token page where you can act. Old /three links redirect there automatically. (`/three-token`) `[improvement]`
- **The Club runs cooler — capped frame rate and adaptive quality** — Walking into the Club no longer spins your laptop's fans up. The walk-through now draws at a steady 60 fps instead of chasing high-refresh displays (which did up to 2.4× the GPU work for no visible gain), caps how many pixels it renders on retina screens, and pauses rendering entirely when the tab is in the background. If frames still run slow on a struggling machine, it automatically steps quality down a notch so the scene keeps moving smoothly instead of grinding. Big drop in heat and battery use, same neon-lit walk. (`/club`) `[fix, improvement]`
- **The Pole Club alley is easier to see** — The walk up to the Pole Club was lit so tightly that only a thin strip of pavement under your feet was visible while the walls fell away to black. The alley now carries a soft warm fill light that travels with you and a wider key, plus a gentle lift to the ambient glow — so the stretch you're actually walking through stays legible the whole way to the door, without losing the moody neon look. (`/club`) `[improvement]`
-- **The x402 Console — run a paid-API business end to end** — A new merchant console brings everything you need to charge for endpoints into one place — the Stripe of x402. Configure agent wallets (the named on-chain wallets your agents auto-pay and receive from, each with its own per-call and daily USDC caps), default payout addresses on Base and Solana, and per-product pricing. Build a hosted storefront with a drag-and-drop block editor — hero, product grid, featured product, text, image, button, divider, footer — with a live preview, then publish it to a public /store/<handle> page that takes real on-chain payments. Plus API keys, a settlement webhook, a CORS/domain allow-list, spending caps, accepted-network toggles, and SIWX re-entry. Open it from the x402 dashboard. (`/dashboard/x402-admin`) `[feature, improvement]`
+- **The x402 Console — run a paid-API business end to end** — A new merchant console brings everything you need to charge for endpoints into one place — the Stripe of x402. Configure agent wallets (the named on-chain wallets your agents auto-pay and receive from, each with its own per-call and daily USDC caps), default payout addresses on Base and Solana, and per-product pricing. Build a hosted storefront with a drag-and-drop block editor — hero, product grid, featured product, text, image, button, divider, footer — with a live preview, then publish it to a public /store/<handle> page that takes real on-chain payments. Plus API keys, a settlement webhook, a CORS/domain allow-list, spending caps, accepted-network toggles, SIWX re-entry, and optional Giving — donate a share of every payment to a cause and let buyers round up, shown right on your storefront. Open it from the x402 dashboard. (`/dashboard/x402-admin`) `[feature, improvement]`
- **The x402 payment modal is now a drop-in SDK any site can use** — The polished checkout that lets you pay any x402 endpoint — connect a wallet, approve, get a receipt, all in one popup — is now packaged as a standalone, dependency-free SDK (@three-ws/x402-payment-modal). One script tag turns any button into a pay button, on Solana (Phantom) or Base/EVM (MetaMask) in USDC. It ships with the server piece for Solana, full docs, a step-by-step tutorial, and ready-to-run HTML, React and Express examples, so other builders can add x402 payments to their own products the same way three.ws does. `[sdk, feature]`
- **Token Oracle follow / unfollow is working again** — Subscribing an agent to a token's oracle alerts — and unsubscribing — was silently failing for everyone; only the status check worked. Both now go through correctly, so you can opt an agent into (and out of) score-based alerts as intended. `[fix]`
- **Unity & Unreal avatar loading documented with code that actually works** — The developer hub's Unity and Unreal cards used to show sample code for an SDK that doesn't exist yet. They now show the real, working way to load a three.ws avatar today — your avatar's GLB endpoint loaded at runtime with glTFast (Unity) or glTFRuntime (Unreal), both standard glTF importers — alongside an honest note that a native package is still on the roadmap. (`/dashboard/developers`) `[docs, improvement]`
diff --git a/data/changelog.json b/data/changelog.json
index 1df3afac6..83cd27740 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,10 +1,28 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-19",
+ "title": "Roaming links no longer open just by standing on them",
+ "summary": "In full-page roaming mode — stroll or platformer — walking your avatar onto a link used to dive into it on its own after a short pause, which made it easy to leave a page by accident. Now standing on a link only arms it (it glows with a prompt) and you commit deliberately: press Space / Enter / E or tap the dive button in stroll mode, or press ↓ / the dive button in platformer mode. Gamepads work too — the left stick or d-pad walks, ✕/○ dive in stroll, and pushing down or ○ dives in platformer — so a controller drives the avatar exactly like the keyboard.",
+ "tags": [
+ "improvement",
+ "sdk"
+ ]
+ },
+ {
+ "date": "2026-06-19",
+ "title": "Pay any x402 endpoint in $THREE, not just USDC",
+ "summary": "The three.ws payment modal now treats $THREE as a first-class settlement token on Solana, right alongside USDC. When an endpoint accepts both, a token chooser appears in checkout so you decide which to pay with — the headline price, the Phantom transaction, and the receipt all switch to your pick. $THREE (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump) is recognized by its mint, so it shows its own ticker and badge even when the merchant doesn't label it. The payment is still a single gasless signature with the network fee sponsored by the facilitator. Endpoint operators turn the $THREE option on with one setting; the drop-in modal and its solanaAccept() helper support it out of the box.",
+ "tags": [
+ "feature",
+ "sdk"
+ ]
+ },
{
"date": "2026-06-19",
"title": "The x402 Console — run a paid-API business end to end",
- "summary": "A new merchant console brings everything you need to charge for endpoints into one place — the Stripe of x402. Configure agent wallets (the named on-chain wallets your agents auto-pay and receive from, each with its own per-call and daily USDC caps), default payout addresses on Base and Solana, and per-product pricing. Build a hosted storefront with a drag-and-drop block editor — hero, product grid, featured product, text, image, button, divider, footer — with a live preview, then publish it to a public /store/<handle> page that takes real on-chain payments. Plus API keys, a settlement webhook, a CORS/domain allow-list, spending caps, accepted-network toggles, and SIWX re-entry. Open it from the x402 dashboard.",
+ "summary": "A new merchant console brings everything you need to charge for endpoints into one place — the Stripe of x402. Configure agent wallets (the named on-chain wallets your agents auto-pay and receive from, each with its own per-call and daily USDC caps), default payout addresses on Base and Solana, and per-product pricing. Build a hosted storefront with a drag-and-drop block editor — hero, product grid, featured product, text, image, button, divider, footer — with a live preview, then publish it to a public /store/<handle> page that takes real on-chain payments. Plus API keys, a settlement webhook, a CORS/domain allow-list, spending caps, accepted-network toggles, SIWX re-entry, and optional Giving — donate a share of every payment to a cause and let buyers round up, shown right on your storefront. Open it from the x402 dashboard.",
"tags": [
"feature",
"improvement"
diff --git a/public/changelog.json b/public/changelog.json
index f33f55bab..4975a8198 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T22:49:13.706Z",
+ "generated_at": "2026-06-19T23:11:11.226Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -476,6 +476,17 @@
"fix"
]
},
+ {
+ "date": "2026-06-19",
+ "type": "update",
+ "title": "Pay any x402 endpoint in $THREE, not just USDC",
+ "summary": "The three.ws payment modal now treats $THREE as a first-class settlement token on Solana, right alongside USDC. When an endpoint accepts both, a token chooser appears in checkout so you decide which to pay with — the headline price, the Phantom transaction, and the receipt all switch to your pick. $THREE (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump) is recognized by its mint, so it shows its own ticker and badge even when the merchant doesn't label it. The payment is still a single gasless signature with the network fee sponsored by the facilitator. Endpoint operators turn the $THREE option on with one setting; the drop-in modal and its solanaAccept() helper support it out of the box.",
+ "link": null,
+ "tags": [
+ "feature",
+ "sdk"
+ ]
+ },
{
"date": "2026-06-19",
"type": "update",
@@ -580,6 +591,17 @@
"feature"
]
},
+ {
+ "date": "2026-06-19",
+ "type": "update",
+ "title": "Roaming links no longer open just by standing on them",
+ "summary": "In full-page roaming mode — stroll or platformer — walking your avatar onto a link used to dive into it on its own after a short pause, which made it easy to leave a page by accident. Now standing on a link only arms it (it glows with a prompt) and you commit deliberately: press Space / Enter / E or tap the dive button in stroll mode, or press ↓ / the dive button in platformer mode. Gamepads work too — the left stick or d-pad walks, ✕/○ dive in stroll, and pushing down or ○ dives in platformer — so a controller drives the avatar exactly like the keyboard.",
+ "link": null,
+ "tags": [
+ "improvement",
+ "sdk"
+ ]
+ },
{
"date": "2026-06-19",
"type": "update",
@@ -698,7 +720,7 @@
"date": "2026-06-19",
"type": "update",
"title": "The x402 Console — run a paid-API business end to end",
- "summary": "A new merchant console brings everything you need to charge for endpoints into one place — the Stripe of x402. Configure agent wallets (the named on-chain wallets your agents auto-pay and receive from, each with its own per-call and daily USDC caps), default payout addresses on Base and Solana, and per-product pricing. Build a hosted storefront with a drag-and-drop block editor — hero, product grid, featured product, text, image, button, divider, footer — with a live preview, then publish it to a public /store/<handle> page that takes real on-chain payments. Plus API keys, a settlement webhook, a CORS/domain allow-list, spending caps, accepted-network toggles, and SIWX re-entry. Open it from the x402 dashboard.",
+ "summary": "A new merchant console brings everything you need to charge for endpoints into one place — the Stripe of x402. Configure agent wallets (the named on-chain wallets your agents auto-pay and receive from, each with its own per-call and daily USDC caps), default payout addresses on Base and Solana, and per-product pricing. Build a hosted storefront with a drag-and-drop block editor — hero, product grid, featured product, text, image, button, divider, footer — with a live preview, then publish it to a public /store/<handle> page that takes real on-chain payments. Plus API keys, a settlement webhook, a CORS/domain allow-list, spending caps, accepted-network toggles, SIWX re-entry, and optional Giving — donate a share of every payment to a cause and let buyers round up, shown right on your storefront. Open it from the x402 dashboard.",
"link": "/dashboard/x402-admin",
"tags": [
"feature",
diff --git a/public/changelog.xml b/public/changelog.xml
index e305c6fa4..d40fbb051 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -374,6 +374,14 @@
<category>fix</category>
<description>The pay-per-call market-intel endpoints (the $THREE Town Oracle and the crypto-intel kiosk) used to hand back an estimated &quot;neutral&quot; reading — and still take the payment — when their live price feed was rate-limited. They now return a clean &quot;temporarily unavailable, retry shortly&quot; instead, and crucially the payment is never settled when live data is missing. You only pay when you get a real, live signal.</description>
</item>
+ <item>
+ <title>Pay any x402 endpoint in $THREE, not just USDC</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-19:Pay any x402 endpoint in $THREE, not just USDC</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The three.ws payment modal now treats $THREE as a first-class settlement token on Solana, right alongside USDC. When an endpoint accepts both, a token chooser appears in checkout so you decide which to pay with — the headline price, the Phantom transaction, and the receipt all switch to your pick. $THREE (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump) is recognized by its mint, so it shows its own ticker and badge even when the merchant doesn't label it. The payment is still a single gasless signature with the network fee sponsored by the facilitator. Endpoint operators turn the $THREE option on with one setting; the drop-in modal and its solanaAccept() helper support it out of the box.</description>
+ </item>
<item>
<title>Pay-per-call vanity wallets now do seed phrases and encrypted delivery</title>
<link>https://three.ws/vanity-wallet</link>
@@ -454,6 +462,14 @@
<category>feature</category>
<description>The rigged-or-not category now reaches everything you own, not just the public gallery. Your Avatars page (both My avatars and the Community tab) and your Agents page each get a Rigged / Static filter and a badge on every card, so you can tell at a glance which models carry a skeleton and can play the animation library — and narrow the list to just the animation-ready ones. An agent's badge reflects the rig state of its 3D body.</description>
</item>
+ <item>
+ <title>Roaming links no longer open just by standing on them</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-19:Roaming links no longer open just by standing on them</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>In full-page roaming mode — stroll or platformer — walking your avatar onto a link used to dive into it on its own after a short pause, which made it easy to leave a page by accident. Now standing on a link only arms it (it glows with a prompt) and you commit deliberately: press Space / Enter / E or tap the dive button in stroll mode, or press ↓ / the dive button in platformer mode. Gamepads work too — the left stick or d-pad walks, ✕/○ dive in stroll, and pushing down or ○ dives in platformer — so a controller drives the avatar exactly like the keyboard.</description>
+ </item>
<item>
<title>Saved avatar now shows the real model on the &quot;what's next&quot; screen</title>
<link>https://three.ws/changelog</link>
@@ -548,7 +564,7 @@
<guid isPermaLink="false">2026-06-19:The x402 Console — run a paid-API business end to end</guid>
<pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
<category>feature</category>
- <description>A new merchant console brings everything you need to charge for endpoints into one place — the Stripe of x402. Configure agent wallets (the named on-chain wallets your agents auto-pay and receive from, each with its own per-call and daily USDC caps), default payout addresses on Base and Solana, and per-product pricing. Build a hosted storefront with a drag-and-drop block editor — hero, product grid, featured product, text, image, button, divider, footer — with a live preview, then publish it to a public /store/&lt;handle&gt; page that takes real on-chain payments. Plus API keys, a settlement webhook, a CORS/domain allow-list, spending caps, accepted-network toggles, and SIWX re-entry. Open it from the x402 dashboard.</description>
+ <description>A new merchant console brings everything you need to charge for endpoints into one place — the Stripe of x402. Configure agent wallets (the named on-chain wallets your agents auto-pay and receive from, each with its own per-call and daily USDC caps), default payout addresses on Base and Solana, and per-product pricing. Build a hosted storefront with a drag-and-drop block editor — hero, product grid, featured product, text, image, button, divider, footer — with a live preview, then publish it to a public /store/&lt;handle&gt; page that takes real on-chain payments. Plus API keys, a settlement webhook, a CORS/domain allow-list, spending caps, accepted-network toggles, SIWX re-entry, and optional Giving — donate a share of every payment to a cause and let buyers round up, shown right on your storefront. Open it from the x402 dashboard.</description>
</item>
<item>
<title>The x402 payment modal is now a drop-in SDK any site can use</title>
diff --git a/public/dashboard/x402-admin.html b/public/dashboard/x402-admin.html
index b90ea05c0..acc67d2c3 100644
--- a/public/dashboard/x402-admin.html
+++ b/public/dashboard/x402-admin.html
@@ -331,6 +331,23 @@
</label>
</div>
+ <div class="card">
+ <h3>Giving</h3>
+ <p class="card-sub">Donate a share of every payment to a cause, and let buyers round up. Shown to buyers on your checkout and storefront.</p>
+ <div class="toggle-row"><div class="tr-text"><b>Donate a share of revenue</b><span>A percentage of each settled payment goes to your chosen cause.</span></div><label class="switch"><input type="checkbox" id="charity_enabled" /><span class="slider"></span></label></div>
+ <div id="charityFields" style="margin-top:14px;display:none">
+ <div class="row-2">
+ <label class="field">Cause name<input id="charity_name" maxlength="80" placeholder="GiveDirectly" /></label>
+ <label class="field">Share of each payment<input id="charity_pct" type="number" min="0" max="100" step="0.01" placeholder="1" /><span class="hint">Percent. e.g. 1 = 1% of every payment.</span></label>
+ </div>
+ <div class="row-2">
+ <label class="field">Cause chain<select id="charity_chain"><option value="base">Base</option><option value="solana">Solana</option></select></label>
+ <label class="field">Cause wallet<input id="charity_address" class="mono" spellcheck="false" autocomplete="off" placeholder="0x… or base58" /><span class="hint" id="charityAddrHint">Validated against the selected chain.</span></label>
+ </div>
+ <div class="toggle-row"><div class="tr-text"><b>Round-up at checkout</b><span>Round the buyer's total up to the nearest unit and donate the difference to the cause.</span></div><label class="switch"><input type="checkbox" id="roundup_enabled" /><span class="slider"></span></label></div>
+ </div>
+ </div>
+
<div class="card">
<h3>Business identity</h3>
<p class="card-sub">Shown on hosted checkout pages and your storefront.</p>
@@ -621,6 +638,13 @@ function hydrate(){
$('net_base').checked = nets.includes('base');
$('net_solana').checked = nets.includes('solana');
$('require_siwx').checked = !!s.require_siwx;
+ $('charity_enabled').checked = !!s.charity_enabled;
+ $('charity_name').value = s.charity_name || '';
+ $('charity_pct').value = s.charity_bps ? (s.charity_bps / 100) : '';
+ $('charity_chain').value = s.charity_chain || 'base';
+ $('charity_address').value = s.charity_address || '';
+ $('roundup_enabled').checked = !!s.roundup_enabled;
+ toggleCharity();
if (s.api_key_prefix){ $('keyVal').textContent = s.api_key_prefix + '…'; }
renderCors();
layout = Array.isArray(s.store_layout) ? structuredClone(s.store_layout) : [];
@@ -653,6 +677,14 @@ function collect(){
spend_cap_daily_atomics: toAtomics($('cap_day').value),
allowed_networks: nets.length ? nets : ['base','solana'],
require_siwx: $('require_siwx').checked,
+ charity_enabled: $('charity_enabled').checked,
+ charity_name: $('charity_name').value.trim() || null,
+ charity_chain: $('charity_chain').value,
+ charity_address: $('charity_address').value.trim() || null,
+ charity_bps: Math.round((Number($('charity_pct').value) || 0) * 100),
+ roundup_enabled: $('roundup_enabled').checked,
+ // Round buyer totals up to the nearest $1 (1e6 atomics) when enabled.
+ roundup_to_atomics: $('roundup_enabled').checked ? '1000000' : null,
};
}
@@ -662,6 +694,16 @@ async function save(){
// Client-side address guards — block obviously bad payout wallets.
if (patch.payout_evm && !/^0x[0-9a-fA-F]{40}$/.test(patch.payout_evm)){ goTab('payout'); toast('Base payout address is invalid', true); return; }
if (patch.payout_solana && !/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(patch.payout_solana)){ goTab('payout'); toast('Solana payout address is invalid', true); return; }
+ // Giving guards — mirror the server so a bad config can't silently drop.
+ if (patch.charity_address){
+ const re = patch.charity_chain === 'base' ? /^0x[0-9a-fA-F]{40}$/ : /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+ if (!re.test(patch.charity_address)){ goTab('payout'); toast('Cause wallet is invalid for the selected chain', true); return; }
+ }
+ if (patch.charity_enabled){
+ if (!patch.charity_address){ goTab('payout'); toast('Add a cause wallet to enable giving', true); return; }
+ if (!patch.charity_bps){ goTab('payout'); toast('Set a non-zero share to enable giving', true); return; }
+ }
+ if (patch.roundup_enabled && !patch.charity_address){ goTab('payout'); toast('Round-up needs a cause wallet to receive the difference', true); return; }
setSaveState('saving');
try {
const d = await api.json('/api/x402-merchant', 'PUT', patch);
@@ -685,11 +727,21 @@ function setSaveState(st){
}
// Watch all setting inputs.
-['payout_evm','payout_solana','business_name','support_email','logo_url','accent_color','webhook_url','facilitator','store_handle','cap_call','cap_day']
+['payout_evm','payout_solana','business_name','support_email','logo_url','accent_color','webhook_url','facilitator','store_handle','cap_call','cap_day','charity_name','charity_pct','charity_address']
.forEach((id)=> $(id).addEventListener('input', markDirty));
-['store_published','net_base','net_solana','require_siwx'].forEach((id)=> $(id).addEventListener('change', markDirty));
+['store_published','net_base','net_solana','require_siwx','charity_enabled','charity_chain','roundup_enabled'].forEach((id)=> $(id).addEventListener('change', markDirty));
$('topSave').addEventListener('click', save);
+// ── Giving controls ──
+function toggleCharity(){ $('charityFields').style.display = $('charity_enabled').checked ? '' : 'none'; }
+$('charity_enabled').addEventListener('change', toggleCharity);
+function validateCharityAddr(){
+ const re = $('charity_chain').value === 'base' ? /^0x[0-9a-fA-F]{40}$/ : /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+ validateAddr('charity_address', re, 'charityAddrHint', `${$('charity_chain').value === 'base' ? '0x address, 42 chars.' : 'Base58, 32–44 chars.'}`);
+}
+$('charity_address').addEventListener('input', validateCharityAddr);
+$('charity_chain').addEventListener('change', validateCharityAddr);
+
// Live address validation feedback
function validateAddr(id, re, hintId, okMsg){
const el = $(id); const v = el.value.trim();
@@ -1068,7 +1120,7 @@ function schedulePreview(){ clearTimeout(previewTimer); previewTimer = setTimeou
function refreshPreview(){
const frame = $('previewFrame');
if (!frame) return;
- const data = { store: { business_name: $('business_name').value || 'Your store', logo_url: $('logo_url').value || null, accent_color: $('accent_color').value, store_handle: $('store_handle').value || 'preview', store_layout: layout, store_theme: {} }, products };
+ const data = { store: { business_name: $('business_name').value || 'Your store', logo_url: $('logo_url').value || null, accent_color: $('accent_color').value, store_handle: $('store_handle').value || 'preview', store_layout: layout, store_theme: {}, charity_enabled: $('charity_enabled').checked, charity_name: $('charity_name').value, charity_bps: Math.round((Number($('charity_pct').value)||0)*100), roundup_enabled: $('roundup_enabled').checked }, products };
frame.srcdoc = renderStoreHtml(data, true);
}
$('refreshPreview').addEventListener('click', refreshPreview);
@@ -1100,13 +1152,16 @@ function renderStoreHtml(data, isPreview){
if (b.type==='footer') return `<footer class="b-footer">${esc(b.body||'')}</footer>`;
return '';
};
- const body = (s.store_layout||[]).map(block).join('') || '<section class="b-text"><p class="b-empty">This store has no content yet.</p></section>';
+ const layoutHtml = (s.store_layout||[]).map(block).join('') || '<section class="b-text"><p class="b-empty">This store has no content yet.</p></section>';
+ const giving = (s.charity_enabled && s.charity_bps>0) ? `<div class="b-giving">♥ <span><b>${(s.charity_bps/100)}%</b> of every payment supports <b>${esc(s.charity_name||'a good cause')}</b>${s.roundup_enabled?' · round-up at checkout':''}</span></div>` : '';
+ const body = giving + layoutHtml;
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>${esc(s.business_name||'Store')}</title>
<style>
:root{--accent:${accent}}*{box-sizing:border-box}html,body{margin:0;background:#fff;color:#111;font-family:-apple-system,BlinkMacSystemFont,Inter,"Segoe UI",Roboto,sans-serif;-webkit-font-smoothing:antialiased;line-height:1.55}
.b-hero{padding:80px 24px 56px;max-width:760px;margin:0 auto}.b-hero h1{font-size:clamp(32px,6vw,52px);font-weight:800;letter-spacing:-.03em;margin:0 0 14px}.b-hero p{font-size:18px;color:#555;margin:0 0 26px;max-width:60ch;margin-left:auto;margin-right:auto}
.b-cta{display:inline-block;background:var(--accent);color:#fff;padding:13px 26px;border-radius:11px;font-weight:600;text-decoration:none}
+.b-giving{display:flex;align-items:center;justify-content:center;gap:8px;padding:9px 16px;font-size:13px;background:#ecfdf3;color:#0a7d3a;border-bottom:1px solid #d3f3df}.b-giving b{font-weight:700}
.b-products,.b-text,.b-feature{max-width:1040px;margin:0 auto;padding:30px 24px}.b-products h2,.b-text h2{font-size:26px;font-weight:700;letter-spacing:-.02em;margin:0 0 22px}
.p-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:16px}
.p-card{border:1px solid #e6e8ee;border-radius:16px;padding:20px;display:flex;flex-direction:column;gap:10px;background:#fff;transition:box-shadow .15s,transform .08s}
diff --git a/public/features.json b/public/features.json
index 4b44831f7..b2eaf3f1d 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T22:49:13.684Z",
+ "generated_at": "2026-06-19T23:11:11.204Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/pay/c/index.html b/public/pay/c/index.html
index 64c1a96a0..faa814edc 100644
--- a/public/pay/c/index.html
+++ b/public/pay/c/index.html
@@ -72,6 +72,19 @@
white-space: pre-wrap;
}
+ .giving {
+ display: flex; align-items: flex-start; gap: 7px;
+ margin-top: 12px; padding: 11px 13px;
+ border: 1px solid #bbf7d0; border-radius: 11px;
+ background: linear-gradient(180deg, #f0fdf4 0%, transparent 100%);
+ color: #166534; font-size: 12.5px; line-height: 1.45;
+ }
+ .giving strong { font-weight: 700; }
+ .giving .give-heart { color: #16a34a; flex: 0 0 auto; }
+ @media (prefers-color-scheme: dark) {
+ .giving { background: rgba(22,163,74,0.08); border-color: rgba(34,197,94,0.35); color: #86efac; }
+ }
+
.pay-btn {
width: 100%; padding: 16px;
background: #0f0f0f; color: #fff;
@@ -161,6 +174,7 @@
</div>
<div class="description" id="description" style="display:none"></div>
<div id="meta"></div>
+ <div class="giving" id="giving" style="display:none"></div>
<button class="pay-btn" id="payBtn" disabled>Loading…</button>
<div id="result"></div>
</div>
@@ -190,8 +204,10 @@
const e = await res.json().catch(() => ({}));
throw new Error(e.error_description || `Checkout "${SLUG}" not found (${res.status}).`);
}
- const { sku } = await res.json();
+ const { sku, giving } = await res.json();
+ sku.giving = giving || null;
renderSku(sku);
+ renderGiving(sku.giving);
await loadPrice(sku);
} catch (err) {
renderError(err.message);
@@ -255,6 +271,23 @@
$('meta').innerHTML = html;
}
+ // Surface the merchant's giving config before the buyer pays. Purely
+ // informational here — the actual opt-in + on-chain donation happens in the
+ // payment modal, where the buyer can toggle it off before signing.
+ function renderGiving(giving) {
+ const el = $('giving');
+ if (!el || !giving) return;
+ const bits = [];
+ if (giving.charity_enabled && giving.charity_bps > 0) {
+ bits.push(`${(giving.charity_bps / 100).toLocaleString(undefined, { maximumFractionDigits: 2 })}% of your payment`);
+ }
+ if (giving.roundup_enabled) bits.push('a round-up of the change');
+ if (!bits.length) return;
+ const cause = giving.charity_name ? escapeHtml(giving.charity_name) : 'a good cause';
+ el.innerHTML = `<span class="give-heart" aria-hidden="true">♥</span> ${bits.join(' + ')} supports <strong>${cause}</strong> — opt in at checkout.`;
+ el.style.display = '';
+ }
+
function renderError(msg) {
$('merchantName').textContent = 'Checkout unavailable';
$('actionName').textContent = ' ';
@@ -275,6 +308,7 @@
body: sku.target_body,
merchant: sku.merchant_name,
action: sku.action_name,
+ giving: sku.giving || undefined,
});
recordCall(sku, out, 200);
if (sku.success_url) {
diff --git a/public/store/index.html b/public/store/index.html
index 7347d4245..337bd1163 100644
--- a/public/store/index.html
+++ b/public/store/index.html
@@ -48,6 +48,9 @@
.b-empty { color: #99a; text-align: center; }
.powered { text-align: center; padding: 14px; font-size: 11px; color: #aab; }
.powered a { color: #889; text-decoration: none; font-weight: 600; }
+ .giving { display: flex; align-items: center; justify-content: center; gap: 8px; padding: 9px 16px; font-size: 13px; background: #ecfdf3; color: #0a7d3a; border-bottom: 1px solid #d3f3df; }
+ .giving b { font-weight: 700; }
+ @media (prefers-color-scheme: dark) { .giving { background: #0b1f17; color: #4ade80; border-color: #14532d; } }
.state { max-width: 560px; margin: 90px auto; text-align: center; padding: 0 24px; color: #667; }
.state h2 { color: #111; font-size: 22px; margin: 0 0 8px; }
@@ -130,8 +133,17 @@ function render(data){
const body = layout.map(block).join('') || '<section class="b-text"><p class="b-empty">This store has no content yet.</p></section>';
const logo = s.logo_url ? `<img src="${esc(s.logo_url)}" alt="">` : esc((s.business_name||'·')[0]);
+ let giving = '';
+ if (s.charity_enabled && s.charity_bps > 0){
+ const pct = s.charity_bps / 100;
+ const pctLabel = (pct % 1 === 0 ? pct.toFixed(0) : pct.toString());
+ const cause = s.charity_name ? esc(s.charity_name) : 'a good cause';
+ giving = `<div class="giving">♥ <span><b>${pctLabel}%</b> of every payment supports <b>${cause}</b>${s.roundup_enabled ? ' · round-up at checkout' : ''}</span></div>`;
+ }
+
document.getElementById('root').innerHTML =
`<div class="topbar"><div class="blogo">${logo}</div><span class="bname">${esc(s.business_name||'Store')}</span><span class="secured">Secured by x402 · on-chain settlement</span></div>`
+ + giving
+ body
+ `<div class="powered">Powered by <a href="/x402" target="_blank">three.ws x402</a></div>`;
diff --git a/public/x402.js b/public/x402.js
index 316567254..45331fa82 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -83,6 +83,48 @@ function isSolanaNetwork(net) {
function isEvmNetwork(net) {
return typeof net === 'string' && net.startsWith('eip155:');
}
+
+// Compute the buyer-facing donation for a Solana `accept` under a merchant's
+// giving config (charity split + round-up). Returns null when nothing applies:
+// giving off, cause wallet on a different chain than this checkout, or a zero
+// total. The donation settles in the SAME mint + transaction as the payment, so
+// the cause wallet must be a Solana address. Pure integer math on atomics.
+function computeGiving(giving, accept) {
+ if (!giving || !isSolanaNetwork(accept?.network)) return null;
+ if (giving.charity_chain && giving.charity_chain !== 'solana') return null;
+ const to = giving.charity_address;
+ if (!to || !/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(to)) return null;
+ let base;
+ try { base = BigInt(accept.amount); } catch { return null; }
+ if (base <= 0n) return null;
+ let charityCut = 0n;
+ if (giving.charity_enabled && Number(giving.charity_bps) > 0) {
+ charityCut = (base * BigInt(Math.round(Number(giving.charity_bps)))) / 10000n;
+ }
+ let roundupCut = 0n;
+ if (giving.roundup_enabled && giving.roundup_to_atomics) {
+ let nearest = 0n;
+ try { nearest = BigInt(giving.roundup_to_atomics); } catch { nearest = 0n; }
+ if (nearest > 0n) {
+ const rem = base % nearest;
+ if (rem > 0n) roundupCut = nearest - rem;
+ }
+ }
+ const total = charityCut + roundupCut;
+ if (total <= 0n) return null;
+ const decimals = Number(accept.extra?.decimals ?? 6);
+ const sym = (accept.extra?.name || 'USDC').replace(/^USD Coin$/, 'USDC');
+ return {
+ to,
+ amount: total.toString(),
+ charity: charityCut.toString(),
+ roundup: roundupCut.toString(),
+ total: (base + total).toString(),
+ name: giving.charity_name || 'a good cause',
+ decimals,
+ sym,
+ };
+}
// The modal only signs EIP-3009 transferWithAuthorization for EVM. When the
// server publishes both an EIP-3009 entry and a Permit2 sibling (the
// gas-sponsoring path used by @x402/evm SDK clients), we must pick the
@@ -561,6 +603,30 @@ const STYLES = `
margin-bottom: 6px;
}
+.x402-giving {
+ display: flex; align-items: flex-start; gap: 10px;
+ padding: 11px 12px; margin-bottom: 10px;
+ border-radius: 11px; border: 1px solid #bbf7d0;
+ background: linear-gradient(180deg, #f0fdf4 0%, #ffffff 100%);
+ cursor: pointer; user-select: none;
+ transition: border-color 0.12s, background 0.12s;
+}
+.x402-giving:hover { border-color: #86efac; }
+.x402-giving input { position: absolute; opacity: 0; width: 0; height: 0; }
+.x402-giving-box {
+ flex: 0 0 auto; width: 18px; height: 18px; margin-top: 1px;
+ border-radius: 5px; border: 1.5px solid #86efac; background: #fff;
+ display: flex; align-items: center; justify-content: center;
+ color: #fff; font-size: 12px; line-height: 1; transition: background 0.12s, border-color 0.12s;
+}
+.x402-giving input:checked + .x402-giving-box { background: #16a34a; border-color: #16a34a; }
+.x402-giving input:checked + .x402-giving-box::after { content: '✓'; }
+.x402-giving input:focus-visible + .x402-giving-box { box-shadow: 0 0 0 3px rgba(22,163,74,0.25); }
+.x402-giving-text { flex: 1 1 auto; min-width: 0; }
+.x402-giving-title { font-size: 13px; font-weight: 700; color: #15803d; line-height: 1.3; }
+.x402-giving-sub { font-size: 11.5px; color: #5a6378; margin-top: 2px; line-height: 1.4; font-feature-settings: 'tnum' 1; }
+.x402-giving-amt { font-weight: 700; color: #0f0f0f; }
+
.x402-error-box {
padding: 12px 14px; border-radius: 10px;
background: #fef2f2; border: 1px solid #fecaca; color: #b91c1c;
@@ -755,6 +821,28 @@ class CheckoutModal {
return html;
}
+ // Buyer-facing charity / round-up opt-in. Default-checked; toggling updates
+ // `this.includeDonation`, which runSolana reads when assembling the tx. The
+ // donation rides the same signed transaction, so the buyer pays once.
+ renderGivingBox(g) {
+ const donation = formatAmount(g.amount, g.decimals);
+ const total = formatAmount(g.total, g.decimals);
+ const parts = [];
+ if (g.charity !== '0') parts.push(`${formatAmount(g.charity, g.decimals)} ${g.sym} donation`);
+ if (g.roundup !== '0') parts.push(`${formatAmount(g.roundup, g.decimals)} ${g.sym} round-up`);
+ const detail = parts.join(' + ');
+ return `
+ <label class="x402-giving">
+ <input type="checkbox" data-giving ${this.includeDonation ? 'checked' : ''} />
+ <span class="x402-giving-box"></span>
+ <span class="x402-giving-text">
+ <span class="x402-giving-title">Add <span class="x402-giving-amt">${donation} ${g.sym}</span> for ${escapeHtml(g.name)}</span>
+ <span class="x402-giving-sub">${detail ? escapeHtml(detail) + ' · ' : ''}you'd pay ${total} ${g.sym} total, settled in one transaction</span>
+ </span>
+ </label>
+ `;
+ }
+
setPrice(accept) {
const decimals = accept.extra?.decimals ?? 6;
const amount = formatAmount(accept.amount, decimals);
@@ -769,6 +857,13 @@ class CheckoutModal {
const solanaAccept = this.challenge?.accepts.find((a) => isSolanaNetwork(a.network));
const evmAccept = this.challenge?.accepts.find(isEip3009Accept);
+ // Charity / round-up giving — only when the merchant configured it and the
+ // cause wallet is reachable on this Solana checkout. Default-included, but
+ // always rendered with an opt-out so the buyer consents before signing.
+ this.solanaGiving = solanaAccept ? computeGiving(this.opts.giving, solanaAccept) : null;
+ if (this.includeDonation === undefined) this.includeDonation = true;
+ this.givingShown = false;
+
// SIWX-first path: when the 402 advertises sign-in-with-x AND we have a
// compatible wallet, lead with "Sign in with wallet" (primary) and
// demote pay to a secondary action. payFlowOverride is set true when
@@ -820,11 +915,16 @@ class CheckoutModal {
const fallbackBox = this.siwxFallbackNotice
? `<div class="x402-siwx-fallback">${escapeHtml(this.siwxFallbackNotice)}</div>`
: '';
+ const givingBox = this.solanaGiving ? this.renderGivingBox(this.solanaGiving) : '';
+ this.givingShown = !!this.solanaGiving;
this.bodyEl.innerHTML = `
${this.renderSteps('connect', { discover: 'done' })}
${fallbackBox}
+ ${givingBox}
<div class="x402-wallet-buttons">${buttons.join('')}</div>
`;
+ const giveEl = this.bodyEl.querySelector('[data-giving]');
+ if (giveEl) giveEl.addEventListener('change', (e) => { this.includeDonation = !!e.target.checked; });
const onClick = (e) => {
const btn = e.target.closest('[data-wallet]');
if (!btn || btn.disabled) return;
@@ -993,9 +1093,16 @@ class CheckoutModal {
this.spendReservation = capCheck.reservation || null;
this.renderProgress('authorize', { text: `Building Solana payment for ${payerAddress.slice(0, 6)}…${payerAddress.slice(-4)}` });
+ // Only attach the donation when the buyer actually saw and kept the
+ // opt-in (givingShown) — never silently in autoConnect mode.
+ const tips =
+ this.givingShown && this.includeDonation && this.solanaGiving
+ ? [{ to: this.solanaGiving.to, amount: this.solanaGiving.amount }]
+ : undefined;
const prep = await postJson(`${ORIGIN}/api/x402-checkout?action=prepare`, {
accept,
buyer: payerAddress,
+ ...(tips ? { tips } : {}),
});
this.renderProgress('authorize', { text: 'Confirm in Phantom…' });
const txBytes = base64ToUint8Array(prep.tx_base64);
diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.js
index c5bbd5e03..6148ddd83 100644
--- a/src/agent-wallet-hub/index.js
+++ b/src/agent-wallet-hub/index.js
@@ -1,6 +1,6 @@
/**
* Agent Wallet hub — the single product home for an agent's self-custodied
- * Solana wallet. Tabbed: Balance · Deposit · Trade · Snipe · Pay · Withdraw.
+ * Solana wallet. Tabbed: Balance · Deposit · Trade · Snipe · Pay · Withdraw · Give.
*
* This file owns the shell: layout, the agent header (name + wallet-readiness),
* the network selector, the accessible tab strip, and the shared context handed
@@ -28,6 +28,7 @@ import './tabs/snipe.js';
import './tabs/pay.js';
import './tabs/vanity.js';
import './tabs/withdraw.js';
+import './tabs/give.js';
import { escapeHtml, shortAddress, copyToClipboard, toast } from './util.js';
diff --git a/src/agent-wallet-hub/tabs/give.js b/src/agent-wallet-hub/tabs/give.js
new file mode 100644
index 000000000..74c092b7b
--- /dev/null
+++ b/src/agent-wallet-hub/tabs/give.js
@@ -0,0 +1,574 @@
+/**
+ * Agent Wallet hub — Give tab (charity + round-up).
+ *
+ * Owner-only. Turns the agent's self-custodied Solana wallet into a giving
+ * wallet. Two primitives, both 100% real on-chain — there is no client key, so
+ * every donation is a server-signed, idempotent transfer through the same
+ * POST /api/agents/:id/solana/withdraw the Withdraw tab uses; the destination is
+ * the chosen cause wallet instead of the owner's. No mocks, no fake balances.
+ *
+ * Cause Pick where giving goes — a Solana address or a .sol name,
+ * resolved live via /api/sns. Saved per-agent so it's one tap
+ * next time. A donation is just a withdrawal to this address.
+ * Give now Donate a chosen amount of SOL or USDC, or a quick % of the
+ * live balance. Reviewed + confirmed (crypto is final).
+ * Round-up "Spare change" — donate the fractional remainder of a balance
+ * (e.g. 12.37 USDC → give $0.37, keep $12.00). One tap per asset.
+ * Impact Total given to this cause, summed from the real custody trail
+ * (withdrawals whose destination is the cause wallet).
+ *
+ * Giving prefs (cause address + label) live in localStorage — a client
+ * convenience; the money movement is always real and audited server-side.
+ */
+
+import { registerWalletTab } from '../registry.js';
+import { formatUsd, explorerTxUrl, shortAddress as shortAddr } from '../util.js';
+import { consumeCsrfToken } from '../../api.js';
+
+const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const PREF_KEY = (agentId) => `awh:give:${agentId}`;
+
+const GIVE_STYLE_ID = 'awh-give-style';
+const GIVE_STYLE = `
+.awg-fld { margin-bottom: var(--space-4,16px); }
+.awg-fld label { display:block; font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); margin-bottom:6px; }
+.awg-in, .awg-sel { width:100%; box-sizing:border-box; font:inherit; font-size: var(--text-md,.8125rem); color: var(--ink,#e8e8e8); background: var(--surface-1, rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-md,10px); padding:9px 12px; transition: border-color var(--duration-fast,140ms); }
+.awg-in:focus, .awg-sel:focus { outline:none; border-color: var(--stroke-strong, rgba(255,255,255,.2)); }
+.awg-row { display:flex; gap:8px; }
+.awg-row .awg-in { flex:1; }
+.awg-resolved { font-size: var(--text-sm,.764rem); margin-top:6px; font-family: var(--font-mono,ui-monospace,monospace); word-break:break-all; }
+.awg-resolved.ok { color: var(--success,#4ade80); }
+.awg-resolved.warn { color: var(--warn,#fbbf24); }
+.awg-note { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); margin-top:6px; line-height:1.45; }
+.awg-err { background: color-mix(in srgb, var(--danger,#f87171) 12%, transparent); border:1px solid color-mix(in srgb, var(--danger,#f87171) 32%, transparent); color: var(--danger,#f87171); border-radius: var(--radius-md,10px); padding:10px 12px; font-size: var(--text-sm,.764rem); margin-bottom: var(--space-3,12px); }
+.awg-err .why { color: var(--ink-dim,#aaa); font-size: var(--text-2xs,.6875rem); margin-top:4px; text-transform:capitalize; }
+.awg-cause { display:flex; align-items:center; gap:10px; justify-content:space-between; flex-wrap:wrap; }
+.awg-cause-id { display:flex; flex-direction:column; gap:2px; min-width:0; }
+.awg-cause-id strong { font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); }
+.awg-cause-id .addr { font-family: var(--font-mono,ui-monospace,monospace); font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); word-break:break-all; }
+.awg-heart { font-size:22px; line-height:1; flex:none; }
+.awg-chips { display:flex; gap:6px; flex-wrap:wrap; margin:10px 0 6px; }
+.awg-chip { appearance:none; font:inherit; font-size: var(--text-2xs,.6875rem); color: var(--ink,#e8e8e8); background: var(--surface-2,rgba(255,255,255,.06)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-pill,999px); padding:4px 11px; cursor:pointer; transition: background var(--duration-fast,140ms), border-color var(--duration-fast,140ms); }
+.awg-chip:hover { background: var(--surface-3,rgba(255,255,255,.1)); border-color: var(--stroke-strong,rgba(255,255,255,.14)); }
+.awg-chip:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset:2px; }
+.awg-sum { background: var(--surface-2, rgba(255,255,255,.05)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-md,10px); padding:12px 14px; margin-bottom: var(--space-3,12px); }
+.awg-sum .r { display:flex; justify-content:space-between; gap:12px; padding:4px 0; font-size: var(--text-sm,.764rem); }
+.awg-sum .r > span:first-child { color: var(--ink-dim,#888); flex:none; }
+.awg-sum .r .v { font-family: var(--font-mono,ui-monospace,monospace); text-align:right; word-break:break-all; color: var(--ink,#e8e8e8); }
+.awg-warn { margin-top: var(--space-3,12px); padding: 9px 12px; border-radius: var(--radius-md,10px); font-size: var(--text-sm,.764rem); line-height:1.45; color: var(--warn,#fbbf24); background: color-mix(in srgb, var(--warn,#fbbf24) 9%, transparent); border:1px solid color-mix(in srgb, var(--warn,#fbbf24) 28%, transparent); }
+.awg-actions { display:flex; gap:8px; margin-top: var(--space-3,12px); }
+.awg-spare { list-style:none; margin:0; padding:0; }
+.awg-spare li { display:flex; align-items:center; justify-content:space-between; gap:10px; padding:9px 0; border-bottom:1px solid var(--stroke,rgba(255,255,255,.06)); }
+.awg-spare li:last-child { border-bottom:none; }
+.awg-spare .lab { font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); }
+.awg-spare .lab b { color: var(--ink-bright,#fff); font-family: var(--font-mono,ui-monospace,monospace); }
+.awg-spare .lab small { display:block; color: var(--ink-dim,#888); font-size: var(--text-2xs,.6875rem); margin-top:1px; }
+.awg-impact { display:flex; align-items:baseline; gap:8px; }
+.awg-impact .big { font-family: var(--font-display,system-ui); font-size: var(--text-2xl,1.9rem); font-weight:700; color: var(--ink-bright,#fff); line-height:1; }
+.awg-impact .unit { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); }
+.awg-give-list { list-style:none; margin:8px 0 0; padding:0; }
+.awg-give-list li { display:flex; gap:10px; align-items:center; justify-content:space-between; padding:7px 0; border-bottom:1px solid var(--stroke,rgba(255,255,255,.06)); font-size: var(--text-sm,.764rem); }
+.awg-give-list li:last-child { border-bottom:none; }
+.awg-give-list .t { color: var(--ink-dim,#888); font-family: var(--font-mono,ui-monospace,monospace); font-size: var(--text-2xs,.6875rem); }
+.awg-give-list .a { font-family: var(--font-mono,ui-monospace,monospace); color: var(--ink,#e8e8e8); }
+.awg-give-list a { color: inherit; border-bottom:1px dotted currentColor; text-decoration:none; }
+.awg-ok { text-align:center; padding: var(--space-4,16px) var(--space-2,8px); }
+.awg-ok .ic { font-size:34px; line-height:1; margin-bottom:8px; }
+.awg-skel { height:14px; border-radius:6px; background: var(--surface-2, rgba(255,255,255,.05)); animation: awg-pulse 1.4s ease-in-out infinite; margin:9px 0; }
+.awg-spin { display:inline-block; width:13px; height:13px; border:2px solid rgba(255,255,255,.3); border-top-color: currentColor; border-radius:50%; animation: awg-rot .7s linear infinite; vertical-align:-2px; margin-right:6px; }
+@keyframes awg-rot { to { transform: rotate(360deg); } }
+@keyframes awg-pulse { 0%,100% { opacity:1; } 50% { opacity:.4; } }
+@media (prefers-reduced-motion: reduce) { .awg-skel, .awg-spin { animation:none; } }
+`;
+
+function injectStyle() {
+ if (typeof document === 'undefined' || document.getElementById(GIVE_STYLE_ID)) return;
+ const tag = document.createElement('style');
+ tag.id = GIVE_STYLE_ID;
+ tag.textContent = GIVE_STYLE;
+ document.head.appendChild(tag);
+}
+
+// fetch helper — never throws, always a designed result (mirrors withdraw.js).
+async function call(url, { method = 'GET', body = null } = {}) {
+ try {
+ const opts = { method, credentials: 'include', headers: {} };
+ if (body != null) {
+ opts.headers['content-type'] = 'application/json';
+ opts.body = JSON.stringify(body);
+ }
+ if (method !== 'GET') {
+ const token = await consumeCsrfToken();
+ if (token) opts.headers['x-csrf-token'] = token;
+ }
+ const r = await fetch(url, opts);
+ let j = null;
+ try { j = await r.json(); } catch { /* empty body */ }
+ if (!r.ok) {
+ return { ok: false, status: r.status, code: j?.error || 'error', message: j?.error_description || `request failed (${r.status})`, extra: j || null };
+ }
+ return { ok: true, status: r.status, data: j?.data ?? j };
+ } catch (err) {
+ return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };
+ }
+}
+
+function fmtAmount(n, max = 6) {
+ if (n == null) return '0';
+ const num = Number(n);
+ if (!Number.isFinite(num)) return String(n);
+ return num.toLocaleString(undefined, { maximumFractionDigits: max });
+}
+
+async function resolveRecipient(raw) {
+ const v = (raw || '').trim();
+ if (!v) return { error: 'Enter a cause address.' };
+ if (SOL_ADDR_RE.test(v)) return { address: v };
+ if (/\.sol$/i.test(v)) {
+ const res = await call(`/api/sns?name=${encodeURIComponent(v)}`);
+ if (res.ok && res.data?.address) return { address: res.data.address, name: v };
+ return { error: `Could not resolve “${v}”.` };
+ }
+ return { error: 'Not a valid Solana address or .sol name.' };
+}
+
+function loadPref(agentId) {
+ try {
+ const raw = localStorage.getItem(PREF_KEY(agentId));
+ if (!raw) return null;
+ const p = JSON.parse(raw);
+ return p && SOL_ADDR_RE.test(p.address || '') ? p : null;
+ } catch { return null; }
+}
+function savePref(agentId, pref) {
+ try { localStorage.setItem(PREF_KEY(agentId), JSON.stringify(pref)); } catch { /* storage may be blocked */ }
+}
+function clearPref(agentId) {
+ try { localStorage.removeItem(PREF_KEY(agentId)); } catch { /* ignore */ }
+}
+
+registerWalletTab({
+ id: 'give',
+ label: 'Give',
+ order: 70,
+ ownerOnly: true,
+ mount({ panel, ctx }) {
+ injectStyle();
+ const { escapeHtml, toast } = ctx;
+ const esc = escapeHtml;
+ const base = (sub) => `/api/agents/${encodeURIComponent(ctx.agentId)}/solana/${sub}`;
+
+ let destroyed = false;
+ let detachNet = null;
+ const state = {
+ pref: loadPref(ctx.agentId), // { address, label, name } | null
+ editing: false, // editing/setting the cause
+ holdings: null, // { sol, tokens } | null
+ holdingsErr: null,
+ impact: null, // { totalUsd, count, recent:[] } | null
+ // give-now form
+ selectedAsset: 0,
+ amount: '',
+ phase: 'form', // 'form' | 'confirm' | 'sending' | 'success'
+ intent: null,
+ result: null,
+ };
+
+ // ── assets from live holdings ────────────────────────────────────────────
+ function assetList() {
+ const out = [];
+ const { sol = 0, tokens = [] } = state.holdings || {};
+ if (Number(sol) > 0) out.push({ kind: 'SOL', name: 'SOL', max: Number(sol), decimals: 9 });
+ for (const t of tokens) {
+ if (!(Number(t.ui_amount) > 0)) continue;
+ out.push({
+ kind: t.mint,
+ name: t.is_usdc ? 'USDC' : shortAddr(t.mint, 4, 4),
+ max: Number(t.ui_amount),
+ decimals: t.decimals,
+ isUsdc: !!t.is_usdc,
+ });
+ }
+ return out;
+ }
+
+ // Fractional "spare change" of each held asset.
+ function spareChange() {
+ return assetList()
+ .map((a) => ({ ...a, spare: +(a.max - Math.floor(a.max)).toFixed(Math.min(a.decimals, 9)) }))
+ .filter((a) => a.spare > 0);
+ }
+
+ // ── top-level render ─────────────────────────────────────────────────────
+ function render() {
+ if (destroyed) return;
+ if (!state.pref || state.editing) { panel.innerHTML = renderCauseSetup(); wireCauseSetup(); return; }
+ if (state.phase === 'success') { panel.innerHTML = renderSuccess(); wireSuccess(); return; }
+ if (state.phase === 'confirm' && state.intent) { panel.innerHTML = renderConfirm(); wireConfirm(); return; }
+ panel.innerHTML = renderHome();
+ wireHome();
+ }
+
+ // ── cause setup ──────────────────────────────────────────────────────────
+ function renderCauseSetup() {
+ const p = state.pref || {};
+ return `
+ <div class="awh-card">
+ <p class="awh-card-h">💚 Your cause</p>
+ <p class="awg-note" style="margin-top:0;">Pick where this wallet's giving goes — any Solana wallet or <span class="awh-mono">.sol</span> name. A donation is a real on-chain transfer to this address.</p>
+ <div class="awg-fld" style="margin-top:14px;">
+ <label for="awg-cause-label">Cause name <span style="opacity:.6">(optional)</span></label>
+ <input class="awg-in" id="awg-cause-label" autocomplete="off" maxlength="60" placeholder="e.g. Ocean Cleanup" value="${esc(p.label || '')}">
+ </div>
+ <div class="awg-fld">
+ <label for="awg-cause-addr">Cause wallet — address or .sol name</label>
+ <input class="awg-in" id="awg-cause-addr" autocomplete="off" spellcheck="false" placeholder="Wallet address or name.sol" value="${esc(p.name || p.address || '')}">
+ <div class="awg-resolved" id="awg-cause-resolved" hidden></div>
+ </div>
+ <div class="awg-err" id="awg-cause-err" hidden></div>
+ <div class="awg-actions">
+ ${state.pref ? '<button class="awh-btn" id="awg-cause-cancel" type="button" style="flex:1;">Cancel</button>' : ''}
+ <button class="awh-btn awh-btn--primary" id="awg-cause-save" type="button" style="flex:2;">Save cause</button>
+ </div>
+ </div>`;
+ }
+
+ function wireCauseSetup() {
+ const addrInput = panel.querySelector('#awg-cause-addr');
+ const resolvedEl = panel.querySelector('#awg-cause-resolved');
+ const errEl = panel.querySelector('#awg-cause-err');
+ let resolved = state.pref ? { address: state.pref.address, name: state.pref.name } : null;
+ let seq = 0;
+
+ async function doResolve() {
+ const myId = ++seq;
+ const raw = addrInput.value.trim();
+ resolved = null;
+ if (!raw) { resolvedEl.hidden = true; return; }
+ if (SOL_ADDR_RE.test(raw)) {
+ resolved = { address: raw };
+ resolvedEl.hidden = false; resolvedEl.className = 'awg-resolved ok'; resolvedEl.textContent = `✓ ${shortAddr(raw, 6, 6)}`;
+ return;
+ }
+ const res = await resolveRecipient(raw);
+ if (myId !== seq) return;
+ if (res.address) {
+ resolved = { address: res.address, name: res.name };
+ resolvedEl.hidden = false; resolvedEl.className = 'awg-resolved ok'; resolvedEl.textContent = `→ ${res.address}`;
+ } else {
+ resolvedEl.hidden = false; resolvedEl.className = 'awg-resolved warn'; resolvedEl.textContent = res.error || 'unresolved';
+ }
+ }
+ addrInput.addEventListener('input', () => { clearTimeout(addrInput._t); addrInput._t = setTimeout(doResolve, 250); });
+ if (addrInput.value.trim()) doResolve();
+
+ panel.querySelector('#awg-cause-cancel')?.addEventListener('click', () => { state.editing = false; render(); });
+
+ panel.querySelector('#awg-cause-save')?.addEventListener('click', async () => {
+ errEl.hidden = true;
+ if (!resolved) { await doResolve(); }
+ if (!resolved?.address) { errEl.hidden = false; errEl.textContent = 'Enter a valid Solana address or .sol name for the cause.'; return; }
+ const label = (panel.querySelector('#awg-cause-label').value || '').trim();
+ state.pref = { address: resolved.address, name: resolved.name || null, label: label || null };
+ savePref(ctx.agentId, state.pref);
+ state.editing = false;
+ state.impact = null;
+ toast('Cause saved');
+ render();
+ loadHoldings();
+ loadImpact();
+ });
+ }
+
+ // ── home (cause set) ─────────────────────────────────────────────────────
+ function causeName() {
+ const p = state.pref || {};
+ return p.label || p.name || shortAddr(p.address, 4, 4);
+ }
+
+ function renderHome() {
+ const p = state.pref;
+ const spare = state.holdings ? spareChange() : null;
+ return `
+ <div class="awh-card">
+ <div class="awg-cause">
+ <span class="awg-heart" aria-hidden="true">💚</span>
+ <div class="awg-cause-id">
+ <strong>${esc(causeName())}</strong>
+ <span class="addr">${esc(p.name ? `${p.name} · ` : '')}${esc(shortAddr(p.address, 6, 6))}</span>
+ </div>
+ <button class="awh-btn" id="awg-change" type="button">Change</button>
+ </div>
+ </div>
+
+ <div class="awh-card">
+ <p class="awh-card-h">Your impact</p>
+ ${renderImpact()}
+ </div>
+
+ <div class="awh-card">
+ <p class="awh-card-h">Give now</p>
+ ${renderGiveForm()}
+ </div>
+
+ <div class="awh-card">
+ <p class="awh-card-h">Round up · spare change</p>
+ ${spare === null && !state.holdingsErr
+ ? '<div class="awg-skel" style="width:60%"></div><div class="awg-skel"></div>'
+ : state.holdingsErr
+ ? `<div class="awg-err">Couldn’t load balances.<div class="why">${esc(state.holdingsErr)}</div></div><button class="awh-btn" id="awg-reload" type="button">Retry</button>`
+ : renderSpare(spare)}
+ </div>`;
+ }
+
+ function renderImpact() {
+ if (state.impact === null) return '<div class="awg-skel" style="width:40%"></div><div class="awg-skel" style="width:70%"></div>';
+ const { totalUsd = 0, count = 0, recent = [] } = state.impact;
+ if (!count) {
+ return `<div class="awg-impact"><span class="big">$0.00</span><span class="unit">given so far</span></div>
+ <p class="awg-note">Your donations to ${esc(causeName())} will tally here, settled on-chain and pulled from this wallet's custody trail.</p>`;
+ }
+ return `
+ <div class="awg-impact"><span class="big">${esc(formatUsd(totalUsd) || '$0.00')}</span><span class="unit">given · ${count} donation${count === 1 ? '' : 's'}</span></div>
+ <ul class="awg-give-list">
+ ${recent.slice(0, 5).map((e) => {
+ const when = e.created_at ? new Date(e.created_at).toLocaleDateString() : '';
+ const amt = e.usd != null ? (formatUsd(e.usd) || '') : (e.asset === 'SOL' && e.amount_lamports != null ? `${fmtAmount(Number(e.amount_lamports) / 1e9, 6)} SOL` : '');
+ const link = e.explorer ? `<a href="${esc(e.explorer)}" target="_blank" rel="noopener">tx ↗</a>` : '';
+ return `<li><span class="t">${esc(when)} ${link}</span><span class="a">${esc(amt)}</span></li>`;
+ }).join('')}
+ </ul>`;
+ }
+
+ function renderGiveForm() {
+ if (state.holdings === null && !state.holdingsErr) return '<div class="awg-skel" style="width:50%"></div><div class="awg-skel"></div><div class="awg-skel" style="width:30%"></div>';
+ if (state.holdingsErr) return `<div class="awg-err">Couldn’t load balances.<div class="why">${esc(state.holdingsErr)}</div></div><button class="awh-btn" id="awg-reload2" type="button">Retry</button>`;
+ const assets = assetList();
+ if (!assets.length) return `<div class="awh-empty" style="padding:8px 0;">This wallet holds no funds on ${esc(ctx.getNetwork())} yet. Fund it from the Deposit tab, then give from here.</div>`;
+ const a = assets[Math.min(state.selectedAsset, assets.length - 1)];
+ return `
+ <div class="awg-fld">
+ <label for="awg-asset">Donate</label>
+ <select class="awg-sel" id="awg-asset">
+ ${assets.map((x, i) => `<option value="${i}" ${i === state.selectedAsset ? 'selected' : ''}>${esc(x.name)} — ${esc(fmtAmount(x.max, x.decimals))} available</option>`).join('')}
+ </select>
+ </div>
+ <div class="awg-chips" id="awg-pcts" role="group" aria-label="Quick amounts">
+ ${[1, 5, 10, 25].map((p) => `<button class="awg-chip" type="button" data-pct="${p}">${p}%</button>`).join('')}
+ <button class="awg-chip" type="button" data-pct="100">Max</button>
+ </div>
+ <div class="awg-fld">
+ <label for="awg-amount">Amount (${esc(a.name)})</label>
+ <input class="awg-in" id="awg-amount" type="text" inputmode="decimal" placeholder="0.0" value="${esc(state.amount)}">
+ <div class="awg-note" id="awg-avail">Available: ${esc(fmtAmount(a.max, a.decimals))} ${esc(a.name)}</div>
+ </div>
+ <div class="awg-err" id="awg-give-err" hidden></div>
+ <button class="awh-btn awh-btn--primary" id="awg-review" type="button" style="width:100%;">Review donation</button>`;
+ }
+
+ function renderSpare(spare) {
+ if (!spare || !spare.length) {
+ return `<div class="awh-empty" style="padding:8px 0;">No spare change right now — balances are whole. As fractions build up, round them off here into a donation.</div>`;
+ }
+ return `<ul class="awg-spare">
+ ${spare.map((a, i) => `
+ <li>
+ <span class="lab"><b>${esc(fmtAmount(a.spare, a.decimals))} ${esc(a.name)}</b><small>round ${esc(fmtAmount(a.max, a.decimals))} → ${esc(fmtAmount(Math.floor(a.max), 0))} ${esc(a.name)}</small></span>
+ <button class="awh-btn" type="button" data-spare="${i}">Donate spare</button>
+ </li>`).join('')}
+ </ul>
+ <p class="awg-note">Gives the fractional remainder to ${esc(causeName())} and keeps the whole units. Real on-chain transfer.</p>`;
+ }
+
+ // ── confirm / success ────────────────────────────────────────────────────
+ function renderConfirm() {
+ const it = state.intent;
+ return `
+ <div class="awh-card">
+ <p class="awh-card-h">Confirm donation</p>
+ <div class="awg-sum">
+ <div class="r"><span>To</span><span class="v">${esc(causeName())}</span></div>
+ <div class="r"><span>Address</span><span class="v awh-mono">${esc(it.destination)}</span></div>
+ <div class="r"><span>Amount</span><span class="v">${esc(fmtAmount(it.amount, it.decimals))} ${esc(it.assetName)}</span></div>
+ <div class="r"><span>Network</span><span class="v">${esc(ctx.getNetwork())}</span></div>
+ </div>
+ <div class="awg-warn" role="note">⚠ Crypto transfers are final. Once submitted, this donation cannot be undone or reversed.</div>
+ <div class="awg-err" id="awg-cf-err" hidden></div>
+ <div class="awg-actions">
+ <button class="awh-btn" id="awg-back" type="button" style="flex:1;" ${state.phase === 'sending' ? 'disabled' : ''}>Back</button>
+ <button class="awh-btn awh-btn--primary" id="awg-confirm" type="button" style="flex:2;" ${state.phase === 'sending' ? 'disabled' : ''}>
+ ${state.phase === 'sending' ? '<span class="awg-spin"></span>Sending…' : 'Confirm donation'}
+ </button>
+ </div>
+ </div>`;
+ }
+
+ function renderSuccess() {
+ const r = state.result || {};
+ const it = state.intent || {};
+ const sig = r.signature || null;
+ const explorer = r.explorer || (sig ? explorerTxUrl(sig, ctx.getNetwork()) : null);
+ return `
+ <div class="awh-card awg-ok">
+ <div class="ic">${state.unconfirmed ? '⏳' : '💚'}</div>
+ <div style="font-size:var(--text-md,.8125rem);font-weight:600;color:var(--ink-bright,#fff);margin-bottom:4px;">
+ ${state.unconfirmed ? 'Donation submitted' : 'Thank you — donation sent'}
+ </div>
+ <div class="awh-empty" style="padding:0 0 12px;">
+ ${state.unconfirmed
+ ? 'Submitted to the network — confirm it on the explorer before retrying.'
+ : `${esc(fmtAmount(it.amount, it.decimals))} ${esc(it.assetName)} given to ${esc(causeName())}.`}
+ </div>
+ ${explorer ? `<a class="awh-btn awh-btn--primary" href="${esc(explorer)}" target="_blank" rel="noopener" style="text-decoration:none;display:inline-block;">View on explorer ↗</a>` : ''}
+ <div style="margin-top:14px;"><button class="awh-btn" id="awg-again" type="button">Give again</button></div>
+ </div>`;
+ }
+
+ // ── wiring ───────────────────────────────────────────────────────────────
+ function wireHome() {
+ panel.querySelector('#awg-change')?.addEventListener('click', () => { state.editing = true; render(); });
+ panel.querySelector('#awg-reload')?.addEventListener('click', () => { state.holdings = null; state.holdingsErr = null; render(); loadHoldings(); });
+ panel.querySelector('#awg-reload2')?.addEventListener('click', () => { state.holdings = null; state.holdingsErr = null; render(); loadHoldings(); });
+
+ const assets = assetList();
+ const assetSel = panel.querySelector('#awg-asset');
+ const amountInput = panel.querySelector('#awg-amount');
+ const availEl = panel.querySelector('#awg-avail');
+ const errEl = panel.querySelector('#awg-give-err');
+ const currentAsset = () => assets[Math.min(Number(assetSel?.value || 0), assets.length - 1)];
+
+ assetSel?.addEventListener('change', () => {
+ state.selectedAsset = Number(assetSel.value);
+ const a = currentAsset();
+ if (availEl) availEl.textContent = `Available: ${fmtAmount(a.max, a.decimals)} ${a.name}`;
+ });
+ amountInput?.addEventListener('input', () => { state.amount = amountInput.value; });
+
+ panel.querySelectorAll('#awg-pcts [data-pct]').forEach((b) => b.addEventListener('click', () => {
+ const a = currentAsset();
+ if (!a) return;
+ const pct = Number(b.dataset.pct);
+ const v = +(a.max * (pct / 100)).toFixed(Math.min(a.decimals, 9));
+ if (amountInput) { amountInput.value = String(v); state.amount = String(v); }
+ }));
+
+ panel.querySelector('#awg-review')?.addEventListener('click', () => {
+ if (!errEl) return;
+ errEl.hidden = true;
+ const a = currentAsset();
+ if (!a) { errEl.hidden = false; errEl.textContent = 'No asset available to donate.'; return; }
+ const amt = Number((amountInput.value || '').trim());
+ if (!Number.isFinite(amt) || amt <= 0) { errEl.hidden = false; errEl.textContent = 'Enter an amount, or tap a quick %.'; return; }
+ if (amt > a.max + 1e-12) { errEl.hidden = false; errEl.textContent = 'Amount exceeds the available balance.'; return; }
+ beginConfirm(a, amt);
+ });
+
+ // Round-up donations — one per asset row.
+ const spare = spareChange();
+ panel.querySelectorAll('[data-spare]').forEach((b) => b.addEventListener('click', () => {
+ const a = spare[Number(b.dataset.spare)];
+ if (a) beginConfirm(a, a.spare);
+ }));
+ }
+
+ function beginConfirm(asset, amount) {
+ state.intent = {
+ kind: asset.kind,
+ assetName: asset.name,
+ decimals: asset.decimals,
+ amount,
+ destination: state.pref.address,
+ idem: (crypto?.randomUUID?.() || `give-${Date.now()}-${Math.round(Math.random() * 1e9)}`),
+ };
+ state.phase = 'confirm';
+ render();
+ }
+
+ function wireConfirm() {
+ panel.querySelector('#awg-back')?.addEventListener('click', () => { state.phase = 'form'; render(); });
+ panel.querySelector('#awg-confirm')?.addEventListener('click', submitDonation);
+ }
+
+ function wireSuccess() {
+ panel.querySelector('#awg-again')?.addEventListener('click', () => {
+ state.phase = 'form'; state.intent = null; state.result = null; state.amount = ''; state.unconfirmed = false;
+ state.holdings = null; state.impact = null;
+ render();
+ loadHoldings();
+ loadImpact();
+ });
+ }
+
+ async function submitDonation() {
+ const it = state.intent;
+ if (!it || state.phase === 'sending') return;
+ state.phase = 'sending';
+ render();
+ const res = await call(base('withdraw'), {
+ method: 'POST',
+ body: { asset: it.kind, amount: it.amount, destination: it.destination, network: ctx.getNetwork(), idempotency_key: it.idem },
+ });
+ if (destroyed) return;
+ if (res.ok || res.status === 202) {
+ state.result = res.ok ? res.data : (res.extra?.data ?? res.extra ?? {});
+ state.unconfirmed = res.status === 202;
+ state.phase = 'success';
+ toast(state.unconfirmed ? 'Donation submitted' : 'Donation sent 💚');
+ render();
+ return;
+ }
+ state.phase = 'confirm';
+ render();
+ const errEl = panel.querySelector('#awg-cf-err');
+ if (errEl) {
+ errEl.hidden = false;
+ errEl.innerHTML = `${esc(res.message)}${res.code ? `<div class="why">${esc(String(res.code).replace(/_/g, ' '))}</div>` : ''}`;
+ }
+ }
+
+ // ── data loads ───────────────────────────────────────────────────────────
+ async function loadHoldings() {
+ const res = await call(`${base('holdings')}?network=${ctx.getNetwork()}`);
+ if (destroyed) return;
+ if (!res.ok) { state.holdingsErr = res.message; state.holdings = null; }
+ else { state.holdingsErr = null; state.holdings = res.data; }
+ if (state.pref && !state.editing && state.phase === 'form') render();
+ }
+
+ // Impact = withdrawals from the custody trail whose destination is the cause.
+ async function loadImpact() {
+ if (!state.pref) return;
+ const res = await call(`${base('custody')}?network=${ctx.getNetwork()}&limit=100`);
+ if (destroyed) return;
+ if (!res.ok) { state.impact = { totalUsd: 0, count: 0, recent: [] }; if (!state.editing && state.phase === 'form') render(); return; }
+ const dest = state.pref.address;
+ const gifts = (res.data?.items || []).filter(
+ (e) => e.event_type === 'spend' && e.category === 'withdraw' && e.destination === dest,
+ );
+ const totalUsd = gifts.reduce((s, e) => s + (Number(e.usd) || 0), 0);
+ state.impact = { totalUsd, count: gifts.length, recent: gifts };
+ if (state.pref && !state.editing && state.phase === 'form') render();
+ }
+
+ detachNet = ctx.onNetworkChange(() => {
+ state.holdings = null; state.holdingsErr = null; state.impact = null;
+ state.phase = 'form'; state.intent = null; state.amount = '';
+ render();
+ if (state.pref && !state.editing) { loadHoldings(); loadImpact(); }
+ });
+
+ render();
+
+ return {
+ onShow() {
+ if (!state.pref || state.editing) return;
+ if (state.holdings === null && state.phase === 'form') loadHoldings();
+ if (state.impact === null) loadImpact();
+ },
+ destroy() { destroyed = true; detachNet?.(); },
+ };
+ },
+});
+
+// Exported for unit tests — pure helpers with no DOM dependency.
+export const __test = { SOL_ADDR_RE, fmtAmount, loadPref, savePref, clearPref, PREF_KEY };
diff --git a/vercel.json b/vercel.json
index 73d16bd65..30d9a9c90 100644
--- a/vercel.json
+++ b/vercel.json
@@ -2780,6 +2780,14 @@
"src": "/pay/(.*)",
"dest": "/pay/$1"
},
+ {
+ "src": "/x402/studio",
+ "dest": "/x402/studio.html"
+ },
+ {
+ "src": "/x402/studio/",
+ "dest": "/x402/studio.html"
+ },
{
"src": "/x402",
"dest": "/x402-stripe.html"
diff --git a/walk-sdk/src/playground.js b/walk-sdk/src/playground.js
index 9bdabbbde..12ed6e339 100644
--- a/walk-sdk/src/playground.js
+++ b/walk-sdk/src/playground.js
@@ -241,6 +241,48 @@ async function loadCharacter(avatarId, charPx) {
return { model, controller, halfW: (size.x * scale) / 2 };
}
+// Deflection past which a stick axis counts as a held direction. High enough
+// that a resting/drifting stick never walks the avatar on its own.
+const PAD_DEADZONE = 0.45;
+
+// Standard Gamepad → walk intents. Reads the first connected pad (null when
+// none) so a controller drives the avatar exactly like the keyboard: left stick
+// or d-pad to move, ✕/A (0) and ○/B (1) as face buttons. Each mode decides what
+// counts as "dive" — so "joystick down" and "press O" map to entry, never a
+// resting stick.
+function readGamepad() {
+ const pads = typeof navigator !== 'undefined' && navigator.getGamepads
+ ? navigator.getGamepads()
+ : null;
+ if (!pads) return null;
+ let gp = null;
+ for (const p of pads) {
+ if (p && p.connected) { gp = p; break; }
+ }
+ if (!gp) return null;
+ const ax = gp.axes[0] || 0;
+ const ay = gp.axes[1] || 0;
+ const btn = (i) => !!gp.buttons[i]?.pressed;
+ return {
+ left: ax < -PAD_DEADZONE || btn(14),
+ right: ax > PAD_DEADZONE || btn(15),
+ up: ay < -PAD_DEADZONE || btn(12),
+ down: ay > PAD_DEADZONE || btn(13),
+ faceA: btn(0), // ✕ / A
+ faceB: btn(1), // ○ / B
+ };
+}
+
+// Fold a gamepad's intents into a keyboard-driven `input` map without stomping
+// keys the player is physically holding: `held` remembers which flags this pad
+// asserted last frame, so releasing the stick only clears what the pad set.
+function mergePad(input, held, next) {
+ for (const k in next) {
+ if (next[k]) { input[k] = true; held[k] = true; }
+ else if (held[k]) { input[k] = false; held[k] = false; }
+ }
+}
+
// ═════════════════════════════════════════════════════════════════════════════
// Stroll mode — gentle top-down aerial view, no gravity, roam anywhere.
// ═════════════════════════════════════════════════════════════════════════════
@@ -257,8 +299,8 @@ class StrollPlayground {
this.char = { x: 0, y: 0, vx: 0, vy: 0, facing: 0 };
this._yaw = 0;
this.input = { up: false, down: false, left: false, right: false, dive: false };
+ this._padHeld = {};
this._armEl = null;
- this._armAt = 0;
this._armHref = null;
this._lastProbe = 0;
this._diving = false;
@@ -542,7 +584,6 @@ class StrollPlayground {
this._clearArm();
this._armEl = el;
this._armHref = href;
- this._armAt = performance.now();
el.classList.add('walk-pg-portal');
this._say('Press Space (or ⬇ / gamepad) to dive in', 2400);
}
@@ -582,7 +623,20 @@ class StrollPlayground {
this._raf = requestAnimationFrame(this._tick);
}
+ _pollGamepad() {
+ const gp = readGamepad();
+ mergePad(this.input, this._padHeld, {
+ up: !!gp?.up,
+ down: !!gp?.down,
+ left: !!gp?.left,
+ right: !!gp?.right,
+ // Either face button is the deliberate "dive into this link" confirm.
+ dive: !!(gp?.faceA || gp?.faceB),
+ });
+ }
+
_step(dt) {
+ this._pollGamepad();
const c = this.char;
let ix = (this.input.right ? 1 : 0) - (this.input.left ? 1 : 0);
let iy = (this.input.down ? 1 : 0) - (this.input.up ? 1 : 0);
@@ -706,9 +760,9 @@ class PlatformerPlayground {
this._lastScan = 0;
this._scrollY = 0;
this.input = { left: false, right: false, jump: false, down: false };
+ this._padHeld = {};
this._jumpEdge = false;
this._armEl = null;
- this._armAt = 0;
this._armHref = null;
this._diving = false;
this._picker = null;
@@ -1027,10 +1081,9 @@ class PlatformerPlayground {
if (this._armEl === p.el) return;
this._clearArm();
this._armEl = p.el;
- this._armAt = performance.now();
this._armHref = p.href;
p.el.classList.add('walk-pg-portal');
- this._say('↓ to dive in', 2200);
+ this._say('Press ↓ (or ⤓ / gamepad) to dive in', 2200);
}
_clearArm() {
@@ -1069,7 +1122,19 @@ class PlatformerPlayground {
this._raf = requestAnimationFrame(this._tick);
}
+ _pollGamepad() {
+ const gp = readGamepad();
+ mergePad(this.input, this._padHeld, {
+ left: !!gp?.left,
+ right: !!gp?.right,
+ jump: !!gp?.faceA, // ✕ / A leaps
+ // Down on the stick/d-pad, or ○ / B, dives into the link platform.
+ down: !!(gp?.down || gp?.faceB),
+ });
+ }
+
_step(dt) {
+ this._pollGamepad();
const c = this.char;
const dir = (this.input.right ? 1 : 0) - (this.input.left ? 1 : 0);
const accel = c.grounded ? GROUND_ACCEL : AIR_ACCEL;
@@ -1082,6 +1147,9 @@ class PlatformerPlayground {
if (Math.abs(c.vx) <= f) c.vx = 0;
else c.vx -= Math.sign(c.vx) * f;
}
+ // Edge-trigger the jump from whichever source released it (keyup clears this
+ // for the keyboard; the pad poll can't, so re-arm here when jump is idle).
+ if (!this.input.jump) this._jumpEdge = false;
if (this.input.jump && c.grounded && !this._jumpEdge) {
c.vy = -JUMP_V;
c.grounded = false;
@@ -1091,14 +1159,19 @@ class PlatformerPlayground {
}
if (this.input.down && c.grounded) {
if (this.platform?.href) {
- this._dive(this.platform.href);
- return;
+ // Down on a link platform dives — never drops through it. Held over
+ // from a previous page? The spawn guard swallows it for a beat.
+ if (performance.now() > this._spawnGuardUntil) {
+ this._dive(this.platform.href);
+ return;
+ }
+ } else {
+ c.y += 4;
+ c.grounded = false;
+ const dropped = this.platform;
+ this.platform = null;
+ this._dropIgnore = dropped;
}
- c.y += 4;
- c.grounded = false;
- const dropped = this.platform;
- this.platform = null;
- this._dropIgnore = dropped;
}
c.vy = Math.min(c.vy + GRAVITY * dt, TERMINAL);
const prevY = c.y;
diff --git a/x402-payment-modal/CHANGELOG.md b/x402-payment-modal/CHANGELOG.md
index 88d2309a9..c32c67ea1 100644
--- a/x402-payment-modal/CHANGELOG.md
+++ b/x402-payment-modal/CHANGELOG.md
@@ -3,6 +3,30 @@
All notable changes to `@three-ws/x402-payment-modal` are documented here. This
project adheres to [Semantic Versioning](https://semver.org).
+## 1.1.0
+
+### Added
+
+- **Pay in USDC _or_ THREE on Solana.** When a 402 challenge offers more than one
+ Solana token, the modal renders a token picker so the buyer chooses which to
+ pay in; the headline price and the built transaction follow the choice. USDC
+ and [$THREE](https://three.ws/three-token) (`FeMb…pump`) are recognized by mint
+ — correct symbol, decimals, and branding even when the `accept` omits
+ `extra.name`/`extra.decimals`.
+- **`solanaAccept()` server helper** — build a spec-shaped Solana `accept` from
+ `token: 'usdc' | 'three'` (or an explicit `mint`) with the price as `uiAmount`
+ (human) or `amount` (atomic). Exports `THREE_MINT`, `USDC_MINT_SOLANA`, and
+ `WELL_KNOWN_SOLANA_TOKENS`.
+- **`window.X402.tokens`** + client exports `THREE_MINT`, `USDC_MINT_SOLANA`,
+ `KNOWN_SOLANA_TOKENS` for inline merchants composing challenges in the browser.
+
+### Notes
+
+- THREE is a utility token, not a stablecoin: the browser can't dollar-denominate
+ it, so client-side spending caps apply to USDC only — enforce THREE caps
+ server-side. Settlement is unchanged — the checkout endpoint already transfers
+ any SPL mint named by the chosen `accept`.
+
## 1.0.0
Initial public release. Extracted from the three.ws platform as a standalone,
diff --git a/x402-payment-modal/README.md b/x402-payment-modal/README.md
index d3cce980b..6c46b5be0 100644
--- a/x402-payment-modal/README.md
+++ b/x402-payment-modal/README.md
@@ -38,9 +38,13 @@ throttle retries, and the receipt, so you ship a paid endpoint in minutes.
- **Zero dependencies, zero build.** Plain ES module. Drop in a `<script>` tag or
`import` it. The Solana/EVM crypto helpers are loaded lazily from a CDN *only*
when a payment is actually attempted.
-- **Solana + EVM.** Phantom (Solana USDC) and any injected EVM wallet (Base USDC
+- **Solana + EVM.** Phantom (Solana) and any injected EVM wallet (Base USDC
via EIP-3009 `transferWithAuthorization`). The modal picks the right path from
the 402 challenge.
+- **Pay in USDC _or_ THREE on Solana.** Offer both and the buyer gets a token
+ picker — pay in USDC, or in [$THREE](https://three.ws/three-token), the three.ws
+ utility token, recognized on sight (symbol, decimals, branding). See
+ [Accepting multiple Solana tokens](#accepting-multiple-solana-tokens-usdc--three).
- **SIWX re-entry.** If a wallet already paid for a resource, it can sign back in
instead of paying again. See [docs/siwx.md](docs/siwx.md).
- **Spending caps.** Optional per-call / hourly / daily caps enforced in the
@@ -271,6 +275,41 @@ Lower-level helpers (`prepareSolanaCheckout`, `encodeX402Payment`,
---
+## Accepting multiple Solana tokens (USDC + THREE)
+
+An x402 challenge can list more than one accepted payment. List a USDC accept
+**and** a [$THREE](https://three.ws/three-token) accept on Solana, and the modal
+renders a token picker: the buyer chooses which to pay in, the headline price and
+the transaction follow the choice. No client wiring — the checkout endpoint
+already builds an SPL transfer for whatever mint the chosen accept names.
+
+Build the accepts with the `solanaAccept` helper (no hardcoded mints):
+
+```js
+import { solanaAccept } from '@three-ws/x402-payment-modal/server';
+
+// feePayer is your facilitator's sponsor account (pays the SOL network fee).
+const accepts = [
+ solanaAccept({ token: 'usdc', uiAmount: 0.25, payTo, feePayer }), // $0.25 in USDC
+ solanaAccept({ token: 'three', uiAmount: 1000, payTo, feePayer }), // or 1,000 THREE
+];
+
+// Return them in your 402 body / PAYMENT-REQUIRED envelope:
+// { x402Version: 2, accepts }
+```
+
+`solanaAccept` takes `token: 'usdc' | 'three'` (or an explicit `mint` for any
+SPL token), the price as `uiAmount` (human units) or `amount` (atomic string),
+and emits a spec-shaped `accept`. The constants `THREE_MINT`, `USDC_MINT_SOLANA`,
+and `WELL_KNOWN_SOLANA_TOKENS` are exported too. On the client, the same mints
+are exposed at `window.X402.tokens` for inline merchants.
+
+> **THREE is a utility token, not a stablecoin.** Its price floats, so the modal
+> can't dollar-denominate it for browser-side spending caps — enforce caps for
+> THREE server-side. USDC caps work in the browser as usual.
+
+---
+
## Documentation
- [Architecture](docs/architecture.md) — the full payment lifecycle.
diff --git a/x402-payment-modal/examples/server-express/server.js b/x402-payment-modal/examples/server-express/server.js
index 35c6245c9..6c57f8b2c 100644
--- a/x402-payment-modal/examples/server-express/server.js
+++ b/x402-payment-modal/examples/server-express/server.js
@@ -18,6 +18,7 @@ import express from 'express';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { x402CheckoutRouter } from '@three-ws/x402-payment-modal/server/express';
+import { solanaAccept } from '@three-ws/x402-payment-modal/server';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PORT = process.env.PORT || 3000;
@@ -54,36 +55,27 @@ app.get('/api/paid/hello', (req, res) => {
const hasPayment = Boolean(req.get('X-PAYMENT'));
if (!hasPayment) {
- // No payment yet → answer with the x402 v2 challenge.
+ // No payment yet → answer with the x402 v2 challenge. We offer TWO Solana
+ // tokens — USDC and THREE — so the modal shows a token picker and the buyer
+ // chooses which to pay in. `solanaAccept` builds each spec-shaped entry.
+ const common = { payTo: DEMO_PAY_TO, feePayer: DEMO_FEE_PAYER, maxTimeoutSeconds: 60 };
return res.status(402).json({
x402Version: 2,
error: 'Payment required',
resource: {
url: `${req.protocol}://${req.get('host')}/api/paid/hello`,
- description: 'A friendly hello, paid for in USDC.',
+ description: 'A friendly hello — pay in USDC or THREE.',
mimeType: 'application/json',
},
accepts: [
- {
- scheme: 'exact',
- // Solana mainnet, in CAIP-2 form.
- network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
- amount: '10000', // 0.01 USDC (USDC has 6 decimals → 10000 = 0.01)
- asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC mint
- payTo: DEMO_PAY_TO,
- maxTimeoutSeconds: 60,
- extra: {
- name: 'USDC',
- decimals: 6,
- feePayer: DEMO_FEE_PAYER,
- },
- },
+ solanaAccept({ token: 'usdc', uiAmount: 0.01, ...common }), // $0.01 in USDC
+ solanaAccept({ token: 'three', uiAmount: 1000, ...common }), // or 1,000 THREE
],
});
}
// A real implementation verifies the X-PAYMENT proof here before responding.
- return res.json({ message: 'Hello — thanks for paying with USDC!' });
+ return res.json({ message: 'Hello — thanks for paying on Solana!' });
});
// Static demo page (examples/server-express/public/index.html).
diff --git a/x402-payment-modal/package.json b/x402-payment-modal/package.json
index 2c93d36df..82fe3e120 100644
--- a/x402-payment-modal/package.json
+++ b/x402-payment-modal/package.json
@@ -1,6 +1,6 @@
{
"name": "@three-ws/x402-payment-modal",
- "version": "1.0.0",
+ "version": "1.1.0",
"description": "Drop-in x402 payment modal for any paid HTTP endpoint. One ES module, zero runtime dependencies — handles wallet connect (Phantom/Solana + EVM via EIP-3009), the 402 → sign → settle flow, SIWX re-entry, client-side spending caps, and a receipt. Vanilla JS, no bundler required.",
"type": "module",
"main": "./src/index.js",
diff --git a/x402-payment-modal/src/index.js b/x402-payment-modal/src/index.js
index b855e571c..3e730d709 100644
--- a/x402-payment-modal/src/index.js
+++ b/x402-payment-modal/src/index.js
@@ -36,7 +36,7 @@
// is configurable via `configure({...})` or `data-*` attributes on the script
// tag — see CONFIG / configure() below and docs/api-reference.md.
-const VERSION = '1.0.0';
+const VERSION = '1.1.0';
// ─────────────────────────────────────────────────────────── configuration ───
// All host-specific knobs live here so the modal runs unchanged on any site.
@@ -992,7 +992,8 @@ class CheckoutModal {
}
renderSiwxChoice({ siwxSolana, siwxEvm }) {
- const priceText = formatAmount(this.accept.amount, this.accept.extra?.decimals ?? 6);
+ const priceInfo = tokenInfo(this.accept);
+ const priceText = formatAmount(this.accept.amount, priceInfo.decimals);
// One primary button — internally we pick the wallet kind that matches
// the supported SIWX chains AND the detected wallets. Phantom wins ties
// to match the existing modal's default preference.
@@ -1003,7 +1004,7 @@ class CheckoutModal {
this.bodyEl.innerHTML = `
${this.renderSteps('connect', { discover: 'done' })}
<button class="x402-pay-btn" data-action="siwx">${siwxLabel}</button>
- <button class="x402-pay-secondary" data-action="pay">Pay ${priceText} USDC instead</button>
+ <button class="x402-pay-secondary" data-action="pay">Pay ${priceText} ${escapeHtml(priceInfo.symbol)} instead</button>
<div class="x402-siwx-hint">Already paid for this once? Sign in to re-enter without paying again.</div>
`;
const siwxBtn = this.bodyEl.querySelector('[data-action="siwx"]');