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: studio fees panel + tests; on-chain brand, gallery, erc8004 deploy, solana register refinements

nirholas7739e4abdd51
diff --git a/api/_lib/three-brand.js b/api/_lib/three-brand.js
index a2d41c8b4..25198defd 100644
--- a/api/_lib/three-brand.js
+++ b/api/_lib/three-brand.js
@@ -34,7 +34,7 @@ export const THREE_WS = {
xHandle: '@trythreews',
github: 'https://github.com/nirholas/three.ws',
docs: 'https://three.ws/docs',
- ogImage: 'https://three.ws/og.png',
+ ogImage: 'https://three.ws/og-image.png',
};
// ── $THREE — the platform coin every artifact links back to ──────────────────
@@ -65,9 +65,25 @@ export function agentHomeUrl(agentId) {
// ── helpers ──────────────────────────────────────────────────────────────────
-function clamp(str, max) {
+const _enc = new TextEncoder();
+
+/**
+ * Clamp to a UTF-8 *byte* budget without splitting a codepoint. On-chain
+ * attributes are borsh strings measured in bytes, so a CJK/emoji name must be
+ * bounded by bytes — not characters — or it can overflow the 1232-byte tx.
+ */
+function clamp(str, maxBytes) {
const s = String(str ?? '').trim();
- return s.length > max ? `${s.slice(0, max - 1).trimEnd()}…` : s;
+ if (_enc.encode(s).length <= maxBytes) return s;
+ let out = '';
+ let bytes = 0;
+ for (const ch of s) {
+ const b = _enc.encode(ch).length;
+ if (bytes + b > maxBytes - 3) break; // reserve 3 bytes for the ellipsis
+ out += ch;
+ bytes += b;
+ }
+ return `${out.trimEnd()}…`;
}
/** A Metaplex `creators` array crediting the owner + the platform. */
@@ -77,6 +93,23 @@ function creators(ownerAddress) {
return list;
}
+/** Default enforced secondary-sale royalty for agent assets: 5%, to the owner. */
+export const AGENT_ROYALTY_BPS = 500;
+
+/**
+ * Plain-data config for the Metaplex Core Royalties plugin. Kept SDK-free so
+ * this module stays dependency-light — the caller turns this into the plugin
+ * with `ruleSet('None')`. Returns `null` when there's no owner to credit
+ * (the plugin requires creator percentages to sum to 100).
+ *
+ * @param {string} ownerAddress base58 owner/creator wallet
+ * @param {number} [basisPoints]
+ */
+export function agentRoyaltyConfig(ownerAddress, basisPoints = AGENT_ROYALTY_BPS) {
+ if (!ownerAddress) return null;
+ return { basisPoints, creators: [{ address: ownerAddress, percentage: 100 }] };
+}
+
// ── Agent identity (Metaplex Core asset) ─────────────────────────────────────
/**
@@ -158,21 +191,22 @@ export function buildAgentManifest(a) {
*/
export function buildAgentOnchainAttributes(a) {
const tok = threeTokenLinks();
- // Caps keep the plugin well under Solana's 1232-byte tx limit even with a
- // long agent name, a long IPFS URI, and a full skill list.
+ // Caps (in UTF-8 bytes) keep the plugin comfortably under Solana's 1232-byte
+ // tx limit even with a long agent name and a full skill list. The off-chain
+ // JSON URI already lives on-chain in the asset's `uri` field, so it is not
+ // duplicated here.
const pairs = [
['platform', THREE_WS.name],
['url', THREE_WS.website],
['agent', clamp(a.name, 48)],
- ...(a.agentUrl ? [['agent_url', clamp(a.agentUrl, 80)]] : []),
+ ...(a.agentUrl ? [['agent_url', clamp(a.agentUrl, 72)]] : []),
['x', THREE_WS.x],
['github', THREE_WS.github],
['$THREE', tok.mint],
['$THREE_url', tok.pumpfun],
['standard', 'metaplex-core'],
['schema', 'agent-manifest/0.1'],
- ...(a.metadataUri ? [['metadata', clamp(a.metadataUri, 96)]] : []),
- ...(a.skills?.length ? [['skills', clamp(a.skills.join(','), 96)]] : []),
+ ...(a.skills?.length ? [['skills', clamp(a.skills.join(','), 80)]] : []),
...(a.createdAt ? [['created', a.createdAt]] : []),
];
return pairs.map(([key, value]) => ({ key, value: String(value) }));
diff --git a/api/agents/onchain/[action].js b/api/agents/onchain/[action].js
index d6807dc5b..bcb849be3 100644
--- a/api/agents/onchain/[action].js
+++ b/api/agents/onchain/[action].js
@@ -11,7 +11,7 @@
import { z } from 'zod';
import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
-import { mplCore, create } from '@metaplex-foundation/mpl-core';
+import { mplCore, create, ruleSet } from '@metaplex-foundation/mpl-core';
import {
generateSigner,
publicKey as umiPublicKey,
@@ -35,6 +35,7 @@ import { env } from '../../_lib/env.js';
import {
buildAgentManifest,
buildAgentOnchainAttributes,
+ agentRoyaltyConfig,
agentHomeUrl,
} from '../../_lib/three-brand.js';
@@ -134,12 +135,14 @@ async function pinManifest(manifest) {
return { cid, uri: publicUrl(key) };
}
-function buildManifest({ agent_id, name, description, avatar_id, skills, wallet_address }) {
+function buildManifest({ agent_id, name, description, avatar_id, skills, wallet_address, image, animationUrl }) {
return buildAgentManifest({
name,
description,
avatarId: avatar_id || null,
skills,
+ image,
+ animationUrl,
externalUrl: agentHomeUrl(agent_id),
ownerAddress: wallet_address,
createdAt: new Date().toISOString(),
@@ -166,18 +169,23 @@ async function buildSolanaTx({ rpc, walletAddress, name, metadataUri, attributes
const ownerPk = umiPublicKey(walletAddress);
const assetSigner = generateSigner(umi);
umi.use(signerIdentity(createNoopSigner(ownerPk)));
- // `create` (Core v2 under the hood) lets us attach the on-chain Attributes
- // plugin: three.ws brand, provenance links, and the $THREE mint are written
- // into the asset account itself — not just the off-chain JSON at `uri`.
- const builder = create(umi, {
- asset: assetSigner,
- owner: ownerPk,
- name,
- uri: metadataUri,
- plugins: attributes?.length
- ? [{ type: 'Attributes', attributeList: attributes }]
- : [],
- });
+ // `create` (Core v2 under the hood) lets us attach on-chain plugins:
+ // • Attributes — three.ws brand, provenance links, and the $THREE mint are
+ // written into the asset account itself, not just the off-chain JSON.
+ // • Royalties — an enforced 5% secondary-sale royalty to the owner.
+ const royalty = agentRoyaltyConfig(walletAddress);
+ const plugins = [
+ ...(attributes?.length ? [{ type: 'Attributes', attributeList: attributes }] : []),
+ ...(royalty
+ ? [{
+ type: 'Royalties',
+ basisPoints: royalty.basisPoints,
+ creators: royalty.creators.map((c) => ({ address: umiPublicKey(c.address), percentage: c.percentage })),
+ ruleSet: ruleSet('None'),
+ }]
+ : []),
+ ];
+ const builder = create(umi, { asset: assetSigner, owner: ownerPk, name, uri: metadataUri, plugins });
const tx = await builder.buildAndSign(umi);
return { assetSigner, txBytes: umi.transactions.serialize(tx) };
}
@@ -270,13 +278,18 @@ async function handlePrep(req, res) {
return error(res, 400, 'validation_error', `invalid chain: ${e.message}`);
}
+ // Resolve the avatar's real media so the asset carries its actual thumbnail
+ // (PNG) and 3D body (GLB) — not the branded default poster.
+ let avatarImage, avatarAnimationUrl;
if (body.avatar_id) {
const [av] = await sql`
- select id from avatars
+ select id, storage_key, thumbnail_key from avatars
where id=${body.avatar_id} and owner_id=${user.id} and deleted_at is null
limit 1
`;
if (!av) return error(res, 404, 'not_found', 'avatar not found');
+ if (av.thumbnail_key) avatarImage = publicUrl(av.thumbnail_key);
+ if (av.storage_key) avatarAnimationUrl = publicUrl(av.storage_key);
}
// Refuse if the wallet is linked to a *different* user. If unlinked, allow
@@ -292,7 +305,7 @@ async function handlePrep(req, res) {
return error(res, 403, 'forbidden', 'wallet is linked to another account');
}
- const manifest = buildManifest(body);
+ const manifest = buildManifest({ ...body, image: avatarImage, animationUrl: avatarAnimationUrl });
const { cid, uri: metadataUri } = await pinManifest(manifest);
let familyPrep;
@@ -304,7 +317,6 @@ async function handlePrep(req, res) {
name: body.name,
agentUrl: agentHomeUrl(body.agent_id),
skills: body.skills,
- metadataUri,
createdAt: new Date().toISOString(),
});
familyPrep = await prepSolana({
diff --git a/api/agents/solana/_handlers.js b/api/agents/solana/_handlers.js
index 17604834d..2dc5e6f62 100644
--- a/api/agents/solana/_handlers.js
+++ b/api/agents/solana/_handlers.js
@@ -13,6 +13,8 @@ import { getSessionUser } from '../../_lib/auth.js';
import { parse } from '../../_lib/validate.js';
import { randomToken } from '../../_lib/crypto.js';
import { env } from '../../_lib/env.js';
+import { publicUrl } from '../../_lib/r2.js';
+import { buildAgentManifest, buildAgentOnchainAttributes, agentRoyaltyConfig } from '../../_lib/three-brand.js';
import { KIND_MAP, crawlAgentAttestations } from '../../_lib/solana-attestations.js';
import {
mintAttestation,
@@ -161,16 +163,49 @@ export const handleMetadata = wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
- const url = new URL(req.url, `http://${req.headers.host}`);
- const name = url.searchParams.get('name') || 'Agent';
- const desc = url.searchParams.get('desc') || '';
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ let asset = url.searchParams.get('asset');
+ if (asset) { try { new PublicKey(asset); } catch { asset = null; } }
+
+ // Defaults come from the query (mint-time, agent not yet in the DB). Once the
+ // agent is registered + confirmed, we serve its live name/skills/avatar.
+ let name = url.searchParams.get('name') || 'Agent';
+ let description = url.searchParams.get('desc') || '';
+ let skills = [];
+ let ownerAddress = null;
+ let avatarId = null;
+ let image; // real avatar thumbnail (PNG) when available
+ let animationUrl; // real avatar GLB when available
+
+ if (asset) {
+ const [a] = await sql`select name, description, skills, wallet_address as owner, avatar_id from agent_identities where meta->>'sol_mint_address' = ${asset} and deleted_at is null limit 1`;
+ if (a) {
+ name = a.name || name;
+ description = a.description || description;
+ skills = a.skills || [];
+ ownerAddress = a.owner || null;
+ avatarId = a.avatar_id || null;
+ if (a.avatar_id) {
+ const [av] = await sql`select storage_key, thumbnail_key from avatars where id = ${a.avatar_id} and deleted_at is null limit 1`;
+ if (av?.thumbnail_key) image = publicUrl(av.thumbnail_key);
+ if (av?.storage_key) animationUrl = publicUrl(av.storage_key);
+ }
+ }
+ }
- return json(res, 200, {
+ const manifest = buildAgentManifest({
name,
- description: desc,
- image: '',
- attributes: [],
- }, { 'cache-control': 'public, max-age=3600', 'access-control-allow-origin': '*' });
+ description,
+ image,
+ animationUrl,
+ externalUrl: asset ? `${env.APP_ORIGIN}/agent-passport.html?asset=${asset}&network=${network}` : undefined,
+ avatarId,
+ skills,
+ ownerAddress,
+ });
+
+ return json(res, 200, manifest, { 'cache-control': 'public, max-age=300', 'access-control-allow-origin': '*' });
});
// ── solana-card ───────────────────────────────────────────────────────────────
@@ -275,7 +310,7 @@ export const handlePriceHistory = wrap(async (req, res) => {
// ── solana-register-prep ──────────────────────────────────────────────────────
import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
-import { mplCore, createV1 } from '@metaplex-foundation/mpl-core';
+import { mplCore, create, ruleSet } from '@metaplex-foundation/mpl-core';
import { generateSigner, publicKey as umiPublicKey, signerIdentity, createNoopSigner } from '@metaplex-foundation/umi';
import { limits as _limits } from '../../_lib/rate-limit.js';
@@ -336,21 +371,53 @@ export const handleRegisterPrep = wrap(async (req, res) => {
const publicRpc = PUBLIC_RPC[network] || PUBLIC_RPC.mainnet;
const appOrigin = env.APP_ORIGIN;
- const metadataUri = body.metadata_uri || `${appOrigin}/api/agents/solana-metadata?name=${encodeURIComponent(name)}&desc=${encodeURIComponent(description)}`;
+
+ // Resolve the asset signer up front so its pubkey can be baked into the
+ // metadata URI and the on-chain attributes before the tx is built.
+ // generateSigner is local crypto (no RPC), so this is safe even if the
+ // configured RPC is unreachable.
+ const assetSigner = asset_pubkey
+ ? createNoopSigner(umiPublicKey(asset_pubkey))
+ : generateSigner(createUmi(publicRpc).use(mplCore()));
+ const assetPubkey = assetSigner.publicKey;
+
+ const passportUrl = `${appOrigin}/agent-passport.html?asset=${assetPubkey}&network=${network}`;
+ const metadataUri = body.metadata_uri
+ || `${appOrigin}/api/agents/solana-metadata?asset=${assetPubkey}&network=${network}&name=${encodeURIComponent(name)}&desc=${encodeURIComponent(description)}`;
+
+ // On-chain brand written into the asset account itself: three.ws identity,
+ // our links, and the $THREE mint (Attributes plugin) + an enforced 5%
+ // secondary-sale royalty to the owner (Royalties plugin).
+ const attributeList = buildAgentOnchainAttributes({
+ name,
+ agentUrl: passportUrl,
+ createdAt: new Date().toISOString(),
+ });
+ const royalty = agentRoyaltyConfig(wallet_address);
+ const plugins = [
+ { type: 'Attributes', attributeList },
+ ...(royalty
+ ? [{
+ type: 'Royalties',
+ basisPoints: royalty.basisPoints,
+ creators: royalty.creators.map((c) => ({ address: umiPublicKey(c.address), percentage: c.percentage })),
+ ruleSet: ruleSet('None'),
+ }]
+ : []),
+ ];
const buildTx = async (rpc) => {
const umi = createUmi(rpc).use(mplCore());
const ownerPubkey = umiPublicKey(wallet_address);
- const assetSigner = asset_pubkey ? createNoopSigner(umiPublicKey(asset_pubkey)) : generateSigner(umi);
umi.use(signerIdentity(createNoopSigner(ownerPubkey)));
- const builder = createV1(umi, { asset: assetSigner, owner: ownerPubkey, name, uri: metadataUri });
+ const builder = create(umi, { asset: assetSigner, owner: ownerPubkey, name, uri: metadataUri, plugins });
const tx = await builder.buildAndSign(umi);
- return { assetSigner, txBytes: umi.transactions.serialize(tx) };
+ return umi.transactions.serialize(tx);
};
- let assetSigner, txBytes;
+ let txBytes;
try {
- ({ assetSigner, txBytes } = await buildTx(configuredRpc));
+ txBytes = await buildTx(configuredRpc);
} catch (rpcErr) {
if (configuredRpc === publicRpc) {
console.error('[solana/register-prep] public RPC failed:', rpcErr.message);
@@ -358,7 +425,7 @@ export const handleRegisterPrep = wrap(async (req, res) => {
}
console.warn('[solana/register-prep] configured RPC failed, retrying with public RPC:', rpcErr.message);
try {
- ({ assetSigner, txBytes } = await buildTx(publicRpc));
+ txBytes = await buildTx(publicRpc);
} catch (fallbackErr) {
console.error('[solana/register-prep] public RPC fallback also failed:', fallbackErr.message);
return error(res, 503, 'rpc_unavailable', 'Solana RPC temporarily unavailable — try again in a moment.');
diff --git a/api/pump/[action].js b/api/pump/[action].js
index 83e1dc929..3afed3a29 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -35,6 +35,13 @@
// quotes is handled internally by the SDK)
// create-fee-sharing-prep -> handleCreateFeeSharingPrep (step 1)
// update-fee-shares-prep -> handleUpdateFeeSharesPrep (step 2)
+// fee-info -> handleFeeInfo (read-only: claimable creator
+// fees, graduation, sharing-config shareholders)
+// collect-creator-fee-agent -> handleCollectCreatorFeeAgent (server-signs
+// with the agent custodial wallet)
+// distribute-creator-fees-agent -> handleDistributeCreatorFeesAgent (server-signs)
+// fee-sharing-agent -> handleFeeSharingAgent (server-signs create +
+// update sharing config; delegated fee rewards)
import { z } from 'zod';
import { Keypair, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';
@@ -3017,4 +3024,398 @@ async function handleCreateFeeSharingPrep(req, res) {
return error(res, e.status || 502, e.code || 'pump_sdk_error', e.message || 'failed to build create-fee-sharing tx');
}
}
+// ── fee-info ───────────────────────────────────────────────────────────────
+// Read-only resolver: given a mint, report where creator fees go (cashback,
+// sharing-config shareholders, or direct creator), the claimable vault balance
+// (pump native vault + AMM WSOL vault), graduation status, and the on-chain
+// sharing-config shareholders if one exists. Mirrors the coin-fees skill's
+// fetch-fee-info.mjs so the studio shows real, on-chain numbers — no estimates.
+// Public read (rate-limited) so anyone can inspect a coin's fee posture before
+// claiming a delegated share.
+
+const MIN_RENT_EXEMPTION_LAMPORTS = 890_880n;
+
+async function handleFeeInfo(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const mintStr = url.searchParams.get('mint');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const mintPk = solanaPubkey(mintStr);
+ if (!mintPk) return error(res, 400, 'validation_error', 'valid mint required');
+
+ try {
+ const connection = getConnection({ network });
+ const [
+ { PumpSdk, OnlinePumpSdk, canonicalPumpPoolPda, creatorVaultPda, feeSharingConfigPda },
+ { OnlinePumpAmmSdk, coinCreatorVaultAuthorityPda, coinCreatorVaultAtaPda },
+ { AccountLayout, NATIVE_MINT, TOKEN_PROGRAM_ID },
+ ] = await Promise.all([
+ import('@pump-fun/pump-sdk'),
+ import('@pump-fun/pump-swap-sdk'),
+ import('@solana/spl-token'),
+ ]);
+
+ const onlineSdk = new OnlinePumpSdk(connection);
+ const offlineSdk = new PumpSdk();
+ const bondingCurve = await onlineSdk.fetchBondingCurve(mintPk).catch(() => null);
+ if (!bondingCurve) return error(res, 404, 'not_found', 'no bonding curve for this mint');
+
+ const poolPda = canonicalPumpPoolPda(mintPk);
+ const poolInfo = await connection.getAccountInfo(poolPda);
+ let isGraduated = false;
+ let poolCoinCreator = null;
+ let isCashbackCoin = false;
+
+ if (poolInfo) {
+ isGraduated = true;
+ try {
+ const pool = await new OnlinePumpAmmSdk(connection).fetchPool(poolPda);
+ poolCoinCreator = pool.coinCreator;
+ isCashbackCoin = pool.isCashbackCoin === true
+ || (Array.isArray(pool.is_cashback_coin) && pool.is_cashback_coin[0] === true);
+ } catch { /* pool not fully initialized */ }
+ } else {
+ isCashbackCoin = bondingCurve.isCashbackCoin === true
+ || (Array.isArray(bondingCurve.is_cashback_coin) && bondingCurve.is_cashback_coin[0] === true);
+ }
+
+ const effectiveCreator = poolCoinCreator ?? new PublicKey(bondingCurve.creator);
+
+ let hasSharingConfig = false;
+ let sharingConfig = null;
+ if (!isCashbackCoin) {
+ // When a creator migrates to a fee-sharing config, the on-chain creator
+ // field (pool.coinCreator / bondingCurve.creator) becomes the config PDA.
+ const cfgPda = feeSharingConfigPda(mintPk);
+ hasSharingConfig = effectiveCreator.equals(cfgPda);
+ if (hasSharingConfig) {
+ const cfgInfo = await connection.getAccountInfo(cfgPda);
+ if (cfgInfo) {
+ const cfg = offlineSdk.decodeSharingConfig(cfgInfo);
+ sharingConfig = {
+ address: cfgPda.toBase58(),
+ admin: cfg.admin.toBase58(),
+ admin_revoked: cfg.adminRevoked ?? false,
+ shareholders: cfg.shareholders.map((s) => ({
+ address: s.address.toBase58(),
+ bps: Number(s.shareBps),
+ })),
+ };
+ } else {
+ hasSharingConfig = false;
+ }
+ }
+ }
+
+ // Vault balance = pump native creator vault (minus rent) + AMM WSOL vault.
+ // When a sharing config exists, fees accrue under the config PDA.
+ let claimableLamports = 0n;
+ if (!isCashbackCoin) {
+ const vaultCreator = hasSharingConfig ? feeSharingConfigPda(mintPk) : effectiveCreator;
+ const nativeVault = creatorVaultPda(vaultCreator);
+ const nativeInfo = await connection.getAccountInfo(nativeVault);
+ if (nativeInfo) {
+ const adjusted = BigInt(nativeInfo.lamports) - MIN_RENT_EXEMPTION_LAMPORTS;
+ if (adjusted > 0n) claimableLamports += adjusted;
+ }
+ try {
+ const ammAuthority = coinCreatorVaultAuthorityPda(vaultCreator);
+ const ammAta = coinCreatorVaultAtaPda(ammAuthority, NATIVE_MINT, TOKEN_PROGRAM_ID);
+ const ammInfo = await connection.getAccountInfo(ammAta);
+ if (ammInfo) {
+ const parsed = AccountLayout.decode(
+ new Uint8Array(ammInfo.data.buffer, ammInfo.data.byteOffset, ammInfo.data.byteLength),
+ );
+ claimableLamports += BigInt(parsed.amount.toString());
+ }
+ } catch { /* no AMM vault yet */ }
+ }
+
+ const feeDestination = isCashbackCoin ? 'cashback' : hasSharingConfig ? 'sharing_config' : 'creator';
+
+ return json(res, 200, {
+ mint: mintPk.toBase58(),
+ network,
+ is_graduated: isGraduated,
+ is_cashback_coin: isCashbackCoin,
+ has_sharing_config: hasSharingConfig,
+ creator: effectiveCreator.toBase58(),
+ claimable_lamports: claimableLamports.toString(),
+ claimable_sol: Number(claimableLamports) / LAMPORTS_PER_SOL,
+ fee_destination: feeDestination,
+ sharing_config: sharingConfig,
+ });
+ } catch (e) {
+ return error(res, e.status || 502, e.code || 'pump_sdk_error', e.message || 'failed to read fee info');
+ }
+}
+
+// Build a v0 transaction from `instructions`, sign with the agent keypair (and
+// any extra signers), send, and confirm. Mirrors the launch-agent send path so
+// every server-signed pump action uses the same RPC handling.
+async function signSendWithAgent({ network, agentKeypair, instructions, extraSigners = [] }) {
+ const conn = solanaConnection(network);
+ const { TransactionMessage, VersionedTransaction } = await import('@solana/web3.js');
+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');
+ const msg = new TransactionMessage({
+ payerKey: agentKeypair.publicKey,
+ recentBlockhash: blockhash,
+ instructions,
+ }).compileToV0Message();
+ const vtx = new VersionedTransaction(msg);
+ vtx.sign([agentKeypair, ...extraSigners]);
+ const signature = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false });
+ await conn.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');
+ return signature;
+}
+
+// Resolve the agent + mint the caller controls, and assert the agent's custodial
+// wallet is the on-chain creator (agent_authority) of the coin. Returns
+// { agent, mintRow, loaded, creator } or sends an error and returns null.
+async function resolveAgentFeeContext(req, res, body) {
+ const user = await getSessionUser(req);
+ if (!user) { error(res, 401, 'unauthorized', 'sign in required'); return null; }
+
+ const agent = await resolveLaunchAgentId({
+ userId: user.id, agentId: body.agent_id, avatarId: body.avatar_id,
+ });
+ if (!agent) { error(res, 404, 'not_found', 'agent not found'); return null; }
+
+ const [mintRow] = await sql`
+ select id, mint, network, agent_authority, sharing_config
+ from pump_agent_mints
+ where agent_id=${agent.id} and mint=${body.mint} and network=${body.network}
+ limit 1
+ `;
+ if (!mintRow) { error(res, 404, 'not_found', 'coin not found for this agent'); return null; }
+
+ const loaded = await loadAgentForSigning(agent.id, user.id, {
+ reason: 'studio_fee_action',
+ meta: { mint: body.mint, network: body.network },
+ });
+ if (loaded.error) { error(res, loaded.error.status, loaded.error.code, loaded.error.msg); return null; }
+
+ const creator = loaded.keypair.publicKey.toBase58();
+ if (mintRow.agent_authority && mintRow.agent_authority !== creator) {
+ error(res, 409, 'creator_mismatch',
+ 'this coin was launched from a connected wallet — claim with that wallet instead of the agent wallet');
+ return null;
+ }
+ return { user, agent, mintRow, loaded, creator };
+}
+
+// ── collect-creator-fee-agent ──────────────────────────────────────────────
+// Server-signs the creator-fee collection with the agent custodial wallet. Use
+// for coins launched from the agent wallet (agent_authority == agent wallet).
+
+const collectFeeAgentSchema = z.object({
+ agent_id: z.string().uuid().optional(),
+ avatar_id: z.string().uuid().optional(),
+ mint: z.string().min(32).max(44),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+}).refine((b) => b.agent_id || b.avatar_id, { message: 'agent_id or avatar_id required' });
+
+async function handleCollectCreatorFeeAgent(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(collectFeeAgentSchema, await readJson(req));
+ const ctx = await resolveAgentFeeContext(req, res, body);
+ if (!ctx) return;
+
+ try {
+ const { connection } = await getPumpSdk({ network: body.network });
+ const { OnlinePumpSdk } = await import('@pump-fun/pump-sdk');
+ const onlineSdk = new OnlinePumpSdk(connection);
+ const creatorPk = ctx.loaded.keypair.publicKey;
+ const ixs = await onlineSdk.collectCoinCreatorFeeInstructions(creatorPk, creatorPk);
+ const signature = await signSendWithAgent({
+ network: body.network,
+ agentKeypair: ctx.loaded.keypair,
+ instructions: Array.isArray(ixs) ? ixs : [ixs],
+ });
+ await sql`
+ insert into agent_actions (agent_id, type, payload, source_skill)
+ values (${ctx.agent.id}, ${'pumpfun.collect_creator_fee'},
+ ${JSON.stringify({ mint: body.mint, network: body.network, signature, source: 'studio_agent_wallet' })}::jsonb,
+ ${'pumpfun'})
+ `.catch((e) => console.error('[pump/collect-creator-fee-agent] log failed', e?.message));
+ return json(res, 201, {
+ ok: true, mint: body.mint, network: body.network, signature,
+ explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
+ });
+ } catch (e) {
+ return error(res, e.status || 502, e.code || 'rpc_error', e.message || 'collect failed');
+ }
+}
+
+// ── distribute-creator-fees-agent ──────────────────────────────────────────
+// Server-signs distribution of shared fees to the sharing-config shareholders,
+// paid by the agent custodial wallet. Distribution is permissionless on-chain;
+// this lets the agent wallet crank it without a connected wallet.
+
+async function handleDistributeCreatorFeesAgent(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(collectFeeAgentSchema, await readJson(req));
+ const ctx = await resolveAgentFeeContext(req, res, body);
+ if (!ctx) return;
+
+ try {
+ const { connection } = await getPumpSdk({ network: body.network });
+ const { OnlinePumpSdk } = await import('@pump-fun/pump-sdk');
+ const onlineSdk = new OnlinePumpSdk(connection);
+ const { instructions } = await onlineSdk.buildDistributeCreatorFeesInstructions(new PublicKey(body.mint));
+ const signature = await signSendWithAgent({
+ network: body.network,
+ agentKeypair: ctx.loaded.keypair,
+ instructions,
+ });
+ await sql`
+ insert into agent_actions (agent_id, type, payload, source_skill)
+ values (${ctx.agent.id}, ${'pumpfun.distribute_creator_fees'},
+ ${JSON.stringify({ mint: body.mint, network: body.network, signature, source: 'studio_agent_wallet' })}::jsonb,
+ ${'pumpfun'})
+ `.catch((e) => console.error('[pump/distribute-creator-fees-agent] log failed', e?.message));
+ return json(res, 201, {
+ ok: true, mint: body.mint, network: body.network, signature,
+ explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
+ });
+ } catch (e) {
+ return error(res, e.status || 502, e.code || 'rpc_error', e.message || 'distribute failed');
+ }
+}
+
+// ── fee-sharing-agent ──────────────────────────────────────────────────────
+// Server-signs the full delegation lifecycle with the agent custodial wallet:
+// creates the sharing config if absent, then sets the shareholder split. This
+// is the on-chain mechanism behind "reward" coins — creator fees are split to a
+// list of delegated wallets (e.g. GitHub contributors) who can each claim their
+// share via distribute. Shares are basis points and must sum to 10000.
+
+const feeSharingAgentSchema = z.object({
+ agent_id: z.string().uuid().optional(),
+ avatar_id: z.string().uuid().optional(),
+ mint: z.string().min(32).max(44),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ shareholders: z.array(z.object({
+ address: z.string().min(32).max(44),
+ share_bps: z.number().int().min(1).max(10_000),
+ })).min(1).max(10)
+ .refine((arr) => arr.reduce((s, x) => s + x.share_bps, 0) === 10_000, { message: 'share_bps must sum to 10000' })
+ .refine((arr) => new Set(arr.map((x) => x.address)).size === arr.length, { message: 'duplicate shareholder addresses' }),
+}).refine((b) => b.agent_id || b.avatar_id, { message: 'agent_id or avatar_id required' });
+
+async function handleFeeSharingAgent(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(feeSharingAgentSchema, await readJson(req));
+ const ctx = await resolveAgentFeeContext(req, res, body);
+ if (!ctx) return;
+
+ const newShareholders = body.shareholders.map((s) => {
+ const pk = solanaPubkey(s.address);
+ if (!pk) throw Object.assign(new Error(`invalid shareholder ${s.address}`), { status: 400, code: 'validation_error' });
+ return { address: pk, shareBps: s.share_bps };
+ });
+
+ try {
+ const { sdk, connection } = await getPumpSdk({ network: body.network });
+ const [
+ { feeSharingConfigPda, bondingCurvePda },
+ { canonicalPumpPoolPda },
+ { isLegacyQuoteMint },
+ ] = await Promise.all([
+ import('@pump-fun/pump-sdk'),
+ import('@pump-fun/pump-swap-sdk'),
+ getPumpSdkV2({ network: body.network }),
+ ]);
+
+ const mintPk = new PublicKey(body.mint);
+ const creator = ctx.loaded.keypair.publicKey;
+
+ // The sharing-config account existing on-chain means the split has already
+ // been initialized — skip creation and go straight to updating shares.
+ const cfgPda = feeSharingConfigPda(mintPk);
+ const cfgInfo = await connection.getAccountInfo(cfgPda);
+ const configExists = !!cfgInfo;
+
+ const signatures = [];
+
+ // Step 1 — create the config if it doesn't exist yet. A fresh config seeds
+ // the creator as the sole shareholder at 10000 bps.
+ if (!configExists) {
+ const bcInfo = await connection.getAccountInfo(bondingCurvePda(mintPk));
+ const bc = bcInfo ? sdk.decodeBondingCurve(bcInfo) : null;
+ const poolPk = (bc && bc.quoteMint && !isLegacyQuoteMint(bc.quoteMint))
+ ? canonicalPumpPoolPda(mintPk, bc.quoteMint)
+ : canonicalPumpPoolPda(mintPk);
+ const createIx = await sdk.createFeeSharingConfig({ creator, mint: mintPk, pool: poolPk });
+ signatures.push(await signSendWithAgent({
+ network: body.network, agentKeypair: ctx.loaded.keypair, instructions: [createIx],
+ }));
+ }
+
+ // Step 2 — set the shareholder split. Right after creation the current set
+ // is [creator] at 10000 bps; otherwise it's whatever the cached config holds.
+ const cached = Array.isArray(ctx.mintRow.sharing_config?.shareholders)
+ ? ctx.mintRow.sharing_config.shareholders
+ : null;
+ const currentShareholders = (configExists && cached?.length)
+ ? cached.map((s) => new PublicKey(s.address))
+ : [creator];
+ const updateIx = await sdk.updateFeeShares({
+ authority: creator, mint: mintPk, currentShareholders, newShareholders,
+ });
+ signatures.push(await signSendWithAgent({
+ network: body.network, agentKeypair: ctx.loaded.keypair, instructions: [updateIx],
+ }));
+
+ // Cache the split so the next update knows the current shareholder set and
+ // the UI reflects delegation immediately. On-chain fee-info remains the
+ // source of truth.
+ const sharingConfig = {
+ address: cfgPda.toBase58(),
+ admin: creator,
+ shareholders: body.shareholders.map((s) => ({ address: s.address, bps: s.share_bps })),
+ updated_at: new Date().toISOString(),
+ };
+ await sql`
+ update pump_agent_mints set sharing_config=${JSON.stringify(sharingConfig)}::jsonb
+ where id=${ctx.mintRow.id}
+ `;
+ await sql`
+ insert into agent_actions (agent_id, type, payload, source_skill)
+ values (${ctx.agent.id}, ${'pumpfun.set_fee_sharing'},
+ ${JSON.stringify({ mint: body.mint, network: body.network, shareholders: sharingConfig.shareholders, signatures, source: 'studio_agent_wallet' })}::jsonb,
+ ${'pumpfun'})
+ `.catch((e) => console.error('[pump/fee-sharing-agent] log failed', e?.message));
+
+ return json(res, 201, {
+ ok: true, mint: body.mint, network: body.network,
+ created: !configExists, signatures,
+ sharing_config: sharingConfig,
+ explorer: `https://solscan.io/tx/${signatures[signatures.length - 1]}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
+ });
+ } catch (e) {
+ return error(res, e.status || 502, e.code || 'rpc_error', e.message || 'fee sharing failed');
+ }
+}
+
function _sse(res, event, data) { res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); }
diff --git a/public/gallery/gallery.js b/public/gallery/gallery.js
index df809f2dc..2227877da 100644
--- a/public/gallery/gallery.js
+++ b/public/gallery/gallery.js
@@ -343,6 +343,14 @@ function renderCard(a) {
const viewsLabel = views >= 1 ? `${formatCompact(views)} view${views === 1 ? '' : 's'}` : '';
+ // Same "deployed on-chain" badge used across the platform. gallery.js is a
+ // static public asset (not bundled), so the shared module is reached via the
+ // global set by /src/shared/onchain-badge.js loaded in index.html; degrades
+ // to no badge if unavailable. Only avatars backing an on-chain agent show it.
+ const onchainBadge = window.twsOnchainBadge?.onchainBadgeHTML
+ ? window.twsOnchainBadge.onchainBadgeHTML(a, { link: false, showChain: true, size: 'sm' })
+ : '';
+
card.innerHTML = `
<a class="gallery-card-thumb" href="${escapeAttr(viewerUrl)}" aria-label="View ${escapeAttr(a.name || 'Avatar')} in 3D viewer">
${thumbContent}
@@ -351,6 +359,7 @@ function renderCard(a) {
</a>
<div class="gallery-card-body">
<h3 class="gallery-card-name"><a href="${escapeAttr(detailUrl)}">${escapeHtml(a.name || 'Untitled')}</a></h3>
+ ${onchainBadge ? `<div class="gallery-card-onchain" style="margin:4px 0 2px">${onchainBadge}</div>` : ''}
${a.description ? `<p class="gallery-card-desc">${escapeHtml(a.description)}</p>` : ''}
${tagChips ? `<div class="gallery-card-tags">${tagChips}</div>` : ''}
<div class="gallery-card-foot">
diff --git a/public/gallery/index.html b/public/gallery/index.html
index e59c70c6b..63e302695 100644
--- a/public/gallery/index.html
+++ b/public/gallery/index.html
@@ -143,6 +143,8 @@
<div id="footer-container"></div>
<script src="/footer.js"></script>
+ <!-- Sets window.twsOnchainBadge for the static gallery.js (bundled by Vite). -->
+ <script type="module">import '/src/shared/onchain-badge.js';</script>
<script type="module" src="/gallery/gallery.js"></script>
<script src="/brand.js" defer></script>
</body>
diff --git a/public/marketplace.css b/public/marketplace.css
index dfa19562e..41f39f890 100644
--- a/public/marketplace.css
+++ b/public/marketplace.css
@@ -3551,12 +3551,14 @@ body.market-page {
transition: color 0.15s, transform 0.1s, background 0.15s;
opacity: 0;
}
-.market-card-agent:hover .card-star { opacity: 1; }
+.market-card-agent:hover .card-star,
+.card-star:focus-visible { opacity: 1; }
.card-star.on {
color: #fde047;
opacity: 1;
}
.card-star:hover { color: #fde047; transform: scale(1.1); background: rgba(0,0,0,0.7); }
+.card-star:focus-visible { color: #fde047; outline: 2px solid #fde047; outline-offset: 2px; }
/* ── Featured badge on cards ────────────────────────────────────── */
diff --git a/public/studio/fees-panel.js b/public/studio/fees-panel.js
new file mode 100644
index 000000000..5ae1b8661
--- /dev/null
+++ b/public/studio/fees-panel.js
@@ -0,0 +1,712 @@
+// Fees & rewards panel — post-launch control surface for a coin's creator fees
+// and delegated reward splits. Mounted inside the studio's existing-token view
+// (and reusable on the avatar page).
+//
+// Capabilities, all wired to real on-chain state via /api/pump/*:
+// • Show claimable creator fees (pump native vault + AMM WSOL vault).
+// • Claim creator fees — connected-wallet creator signs, or the agent
+// custodial wallet signs server-side (collect-creator-fee-agent).
+// • Delegate fees to a team / GitHub contributors (fee-sharing config) — the
+// "reward coin" mechanism. Import contributors from a GitHub repo, assign a
+// wallet + share to each, and write the split on-chain.
+// • Distribute / claim-if-delegated — anyone (creator, agent, or a delegated
+// shareholder) can crank distribution to release accrued shares.
+//
+// Entry:
+// mountFeesPanel(el, {
+// mint, network, creator, agentId, avatarId, symbol, name, getUser
+// }) → { teardown }
+
+// ── Pure helpers (tested) ────────────────────────────────────────────────────
+
+// Parse "owner/repo" (or a full GitHub URL) into { owner, repo } or null.
+export function parseGithubRepo(input) {
+ const s = String(input || '').trim();
+ if (!s) return null;
+ const m = s.match(/(?:github\.com\/)?([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i);
+ if (!m) return null;
+ const owner = m[1], repo = m[2];
+ if (!owner || !repo || owner === 'github.com') return null;
+ return { owner, repo };
+}
+
+// Convert contributor weights into integer basis points summing to exactly
+// 10000. Largest-remainder method; the heaviest row absorbs any rounding drift.
+export function weightsToBps(weights) {
+ const total = weights.reduce((a, b) => a + Math.max(0, b), 0);
+ if (total <= 0 || weights.length === 0) return weights.map(() => 0);
+ const raw = weights.map((w) => (Math.max(0, w) / total) * 10_000);
+ const floored = raw.map((x) => Math.floor(x));
+ let remainder = 10_000 - floored.reduce((a, b) => a + b, 0);
+ const order = raw
+ .map((x, i) => ({ i, frac: x - Math.floor(x) }))
+ .sort((a, b) => b.frac - a.frac);
+ for (let k = 0; k < order.length && remainder > 0; k++, remainder--) floored[order[k].i] += 1;
+ return floored;
+}
+
+// Validate a shareholder split. Returns { ok, errors[], totalBps }.
+export function validateShareSplit(rows) {
+ const errors = [];
+ const clean = rows.filter((r) => r.address?.trim() || r.bps > 0);
+ if (clean.length === 0) errors.push('Add at least one recipient.');
+ if (clean.length > 10) errors.push('Maximum 10 recipients.');
+ const seen = new Set();
+ for (const r of clean) {
+ const a = (r.address || '').trim();
+ if (!a) { errors.push('Every recipient needs a wallet address.'); continue; }
+ if (a.length < 32 || a.length > 44) errors.push(`Invalid wallet: ${a.slice(0, 8)}…`);
+ if (seen.has(a)) errors.push(`Duplicate wallet: ${a.slice(0, 8)}…`);
+ seen.add(a);
+ if (!(r.bps > 0)) errors.push('Every recipient needs a share above 0%.');
+ }
+ const totalBps = clean.reduce((s, r) => s + (r.bps || 0), 0);
+ if (clean.length && totalBps !== 10_000)
+ errors.push(`Shares must total 100% (currently ${(totalBps / 100).toFixed(1)}%).`);
+ return { ok: errors.length === 0, errors: [...new Set(errors)], totalBps };
+}
+
+// ── DOM utilities ─────────────────────────────────────────────────────────────
+
+const esc = (s) =>
+ String(s ?? '').replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+
+const shortAddr = (a) => (!a || a.length < 10 ? a || '' : a.slice(0, 4) + '…' + a.slice(-4));
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+const RPC_URL = (typeof window !== 'undefined' && window.location?.origin
+ ? window.location.origin
+ : 'https://three.ws') + '/api/solana-rpc';
+const SOLSCAN = (sig, net) => `https://solscan.io/tx/${sig}${net === 'devnet' ? '?cluster=devnet' : ''}`;
+
+function detectWallet() {
+ if (typeof window === 'undefined') return null;
+ return window.phantom?.solana || window.solana || window.backpack || window.solflare || null;
+}
+
+let _web3;
+async function loadWeb3() {
+ if (!_web3) _web3 = await import('https://esm.sh/@solana/[email protected]');
+ return _web3;
+}
+
+function friendlyError(msg) {
+ const m = String(msg || '');
+ if (/user rejected|rejected the request/i.test(m)) return 'Signing cancelled.';
+ if (/0x1\b|insufficient.*lamports|insufficient.*sol/i.test(m)) return 'Not enough SOL to cover the network fee.';
+ if (/creator_mismatch|connected wallet/i.test(m)) return m;
+ if (/429|rate.limit/i.test(m)) return 'Too many requests — wait a moment and try again.';
+ if (/no bonding curve|not_found/i.test(m)) return 'This coin is not on pump.fun yet.';
+ return m;
+}
+
+// ── CSS ────────────────────────────────────────────────────────────────────────
+
+const FP_CSS = `
+.fp{display:flex;flex-direction:column;gap:.7rem;margin-top:.85rem;padding-top:.85rem;
+ border-top:1px solid rgba(255,255,255,.07)}
+.fp-head{display:flex;align-items:center;gap:.5rem}
+.fp-head-t{font-size:.78rem;font-weight:600;color:rgba(255,255,255,.82);letter-spacing:-.01em}
+.fp-badge{font-size:.6rem;font-weight:600;letter-spacing:.04em;text-transform:uppercase;
+ padding:.16rem .45rem;border-radius:999px;margin-left:auto}
+.fp-badge.creator{color:#c8f0d8;background:rgba(164,240,188,.1);border:1px solid rgba(164,240,188,.25)}
+.fp-badge.split{color:#c4b5f5;background:rgba(170,140,240,.12);border:1px solid rgba(170,140,240,.3)}
+.fp-badge.cashback{color:#a8c4f0;background:rgba(120,160,240,.1);border:1px solid rgba(120,160,240,.28)}
+
+.fp-loading{display:flex;align-items:center;gap:.5rem;font-size:.74rem;color:rgba(255,255,255,.36);
+ padding:.5rem 0}
+@keyframes fp-spin{to{transform:rotate(360deg)}}
+.fp-spin{width:13px;height:13px;border:2px solid rgba(255,255,255,.12);border-top-color:rgba(255,255,255,.5);
+ border-radius:50%;animation:fp-spin .8s linear infinite;flex-shrink:0}
+
+.fp-claim{display:flex;align-items:center;gap:.7rem;padding:.7rem .8rem;border-radius:11px;
+ background:rgba(164,240,188,.05);border:1px solid rgba(164,240,188,.16)}
+.fp-claim-amt{flex:1;min-width:0}
+.fp-claim-n{font-size:1.15rem;font-weight:700;color:#fff;letter-spacing:-.02em;line-height:1.1}
+.fp-claim-n small{font-size:.7rem;font-weight:500;color:rgba(255,255,255,.4);margin-left:.2rem}
+.fp-claim-l{font-size:.64rem;color:rgba(255,255,255,.4);margin-top:.15rem}
+.fp-btn{padding:.5rem .85rem;border-radius:8px;cursor:pointer;font-size:.78rem;font-weight:600;
+ white-space:nowrap;transition:all .15s;line-height:1.1;border:1px solid transparent}
+.fp-btn.primary{background:linear-gradient(135deg,rgba(120,200,140,.24),rgba(60,140,100,.16));
+ border-color:rgba(120,200,140,.45);color:#d2f3df}
+.fp-btn.primary:hover:not([disabled]){background:linear-gradient(135deg,rgba(120,200,140,.36),rgba(60,140,100,.24));
+ border-color:rgba(120,200,140,.7)}
+.fp-btn.ghost{background:rgba(255,255,255,.05);border-color:rgba(255,255,255,.1);color:rgba(255,255,255,.7)}
+.fp-btn.ghost:hover:not([disabled]){background:rgba(255,255,255,.1);color:#fff}
+.fp-btn.violet{background:rgba(170,140,240,.14);border-color:rgba(170,140,240,.34);color:#cdbcf8}
+.fp-btn.violet:hover:not([disabled]){background:rgba(170,140,240,.22)}
+.fp-btn[disabled]{opacity:.45;cursor:not-allowed}
+.fp-btn.busy{opacity:.7;cursor:wait}
+
+.fp-note{font-size:.69rem;color:rgba(255,255,255,.45);line-height:1.5;padding:.5rem .65rem;
+ background:rgba(255,255,255,.025);border:1px solid rgba(255,255,255,.06);border-radius:8px}
+.fp-note.warn{color:rgba(246,200,114,.9);background:rgba(246,200,114,.06);border-color:rgba(246,200,114,.2)}
+.fp-note.you{color:#c8f0d8;background:rgba(164,240,188,.07);border-color:rgba(164,240,188,.22)}
+.fp-err{font-size:.72rem;color:#f6b3b3;padding:.45rem .6rem;border-radius:8px;line-height:1.45;
+ background:rgba(246,179,179,.07);border:1px solid rgba(246,179,179,.18)}
+.fp-ok{font-size:.72rem;color:#a4f0bc;padding:.45rem .6rem;border-radius:8px;line-height:1.45;
+ background:rgba(164,240,188,.08);border:1px solid rgba(164,240,188,.22);display:flex;gap:.5rem;align-items:center;flex-wrap:wrap}
+.fp-ok a{color:#c8f0d8;text-decoration:none;border-bottom:1px solid rgba(200,240,216,.3)}
+
+.fp-deleg{display:flex;flex-direction:column;gap:.55rem}
+.fp-deleg-title{font-size:.72rem;font-weight:600;color:rgba(255,255,255,.7)}
+.fp-share-row{display:flex;align-items:center;gap:.45rem}
+.fp-share-row .fp-sh-meta{flex:1;min-width:0;display:flex;flex-direction:column;gap:.15rem}
+.fp-share-addr{width:100%;padding:.4rem .55rem;border-radius:7px;outline:none;font-size:.74rem;
+ background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.09);color:#fff;
+ font-family:ui-monospace,monospace;box-sizing:border-box;transition:border-color .15s}
+.fp-share-addr:focus{border-color:rgba(170,140,240,.45)}
+.fp-share-addr::placeholder{color:rgba(255,255,255,.22);font-family:inherit}
+.fp-share-gh{font-size:.62rem;color:rgba(255,255,255,.4);display:flex;align-items:center;gap:.3rem}
+.fp-share-gh img{width:13px;height:13px;border-radius:50%}
+.fp-share-pct{width:62px;flex-shrink:0;padding:.4rem .4rem;border-radius:7px;outline:none;font-size:.74rem;
+ background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.09);color:#fff;text-align:right;
+ font-family:ui-monospace,monospace;box-sizing:border-box}
+.fp-share-pct:focus{border-color:rgba(170,140,240,.45)}
+.fp-share-x{flex-shrink:0;width:26px;height:26px;border-radius:6px;cursor:pointer;line-height:1;
+ background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.1);color:rgba(255,255,255,.5);font-size:.85rem}
+.fp-share-x:hover{background:rgba(246,179,179,.12);border-color:rgba(246,179,179,.3);color:#f6b3b3}
+.fp-deleg-foot{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap}
+.fp-deleg-total{font-size:.7rem;font-family:ui-monospace,monospace;margin-right:auto}
+.fp-deleg-total.ok{color:#a4f0bc}
+.fp-deleg-total.bad{color:rgba(246,200,114,.9)}
+.fp-add{padding:.35rem .6rem;border-radius:7px;cursor:pointer;font-size:.7rem;
+ background:rgba(255,255,255,.04);border:1px dashed rgba(255,255,255,.16);color:rgba(255,255,255,.6)}
+.fp-add:hover{color:#fff;border-color:rgba(255,255,255,.3)}
+
+.fp-gh{display:flex;gap:.4rem;align-items:center}
+.fp-gh input{flex:1;min-width:0;padding:.42rem .6rem;border-radius:7px;outline:none;font-size:.74rem;
+ background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.09);color:#fff;box-sizing:border-box}
+.fp-gh input:focus{border-color:rgba(170,140,240,.45)}
+.fp-gh input::placeholder{color:rgba(255,255,255,.25)}
+
+.fp-holders{display:flex;flex-direction:column;gap:.3rem}
+.fp-holder{display:flex;align-items:center;gap:.5rem;padding:.4rem .6rem;border-radius:8px;
+ background:rgba(255,255,255,.025);border:1px solid rgba(255,255,255,.05);font-size:.73rem}
+.fp-holder code{flex:1;min-width:0;font-family:ui-monospace,monospace;color:rgba(255,255,255,.6);
+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.fp-holder .fp-holder-pct{font-weight:600;color:#cdbcf8}
+.fp-holder.is-you{background:rgba(164,240,188,.06);border-color:rgba(164,240,188,.2)}
+.fp-holder.is-you .fp-holder-pct{color:#a4f0bc}
+.fp-holder .fp-you-tag{font-size:.58rem;font-weight:600;color:#0c1410;background:#a4f0bc;
+ padding:.05rem .3rem;border-radius:4px;letter-spacing:.03em}
+
+.fp-cta{display:flex;align-items:center;gap:.6rem;padding:.6rem .7rem;border-radius:10px;cursor:pointer;
+ background:rgba(170,140,240,.06);border:1px dashed rgba(170,140,240,.28);transition:all .15s}
+.fp-cta:hover{background:rgba(170,140,240,.1);border-color:rgba(170,140,240,.45)}
+.fp-cta-ic{font-size:1.1rem;line-height:1}
+.fp-cta-b{flex:1;min-width:0}
+.fp-cta-t{font-size:.76rem;font-weight:600;color:rgba(255,255,255,.85)}
+.fp-cta-s{font-size:.65rem;color:rgba(255,255,255,.45);margin-top:.1rem;line-height:1.4}
+.fp-cta-arrow{color:rgba(170,140,240,.7);font-size:.9rem}
+
+.fp-wallet{display:flex;align-items:center;gap:.5rem;font-size:.7rem;color:rgba(255,255,255,.5);
+ padding:.45rem .6rem;border-radius:8px;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.06)}
+.fp-wallet .fp-w-dot{width:6px;height:6px;border-radius:50%;background:rgba(255,255,255,.2);flex-shrink:0}
+.fp-wallet.on .fp-w-dot{background:#a4f0bc;box-shadow:0 0 6px rgba(164,240,188,.45)}
+.fp-wallet code{font-family:ui-monospace,monospace;color:rgba(255,255,255,.62)}
+.fp-wallet .fp-w-btn{margin-left:auto;padding:.26rem .55rem;border-radius:6px;cursor:pointer;font-size:.68rem;
+ background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);color:rgba(255,255,255,.75)}
+.fp-wallet .fp-w-btn:hover{background:rgba(255,255,255,.12);color:#fff}
+`;
+
+let _cssInjected = false;
+function injectCss() {
+ if (_cssInjected || typeof document === 'undefined') return;
+ _cssInjected = true;
+ const el = document.createElement('style');
+ el.textContent = FP_CSS;
+ document.head.appendChild(el);
+}
+
+// ── Mount ──────────────────────────────────────────────────────────────────────
+
+export function mountFeesPanel(container, opts = {}) {
+ injectCss();
+ const { mint, network = 'mainnet', creator, agentId, avatarId, symbol = 'TOKEN', getUser } = opts;
+
+ const s = {
+ info: null, loading: true, loadError: '',
+ wallet: null, // { provider, address }
+ agentWalletAddress: undefined, // undefined=unresolved, null=none, string=addr
+ busy: '', // action label while a tx is in flight
+ actionError: '', actionOk: null, // { label, sig }
+ editing: false,
+ rows: [], // [{ address, pct, gh?:{login,avatar} }]
+ githubRepo: '', githubBusy: false, githubError: '',
+ };
+
+ let _alive = true;
+
+ // Is the agent custodial wallet the on-chain creator? → server-signed path.
+ const isAgentCreator = () =>
+ s.agentWalletAddress && creator && s.agentWalletAddress === creator;
+ // Connected wallet matches the creator → it can sign creator-only actions.
+ const connectedIsCreator = () => s.wallet?.address && creator && s.wallet.address === creator;
+ // Connected wallet is one of the delegated shareholders.
+ const youAreShareholder = () => {
+ const holders = s.info?.sharing_config?.shareholders || [];
+ return !!(s.wallet?.address && holders.some((h) => h.address === s.wallet.address));
+ };
+
+ const agentBody = () => (agentId ? { agent_id: agentId } : { avatar_id: avatarId });
+
+ // ── Data ──────────────────────────────────────────────────────────────────
+
+ async function loadInfo() {
+ s.loading = true; s.loadError = '';
+ render();
+ try {
+ const r = await fetch(`/api/pump/fee-info?mint=${encodeURIComponent(mint)}&network=${network}`,
+ { credentials: 'include' });
+ const data = await r.json();
+ if (!r.ok) throw new Error(data.error_description || data.error || `HTTP ${r.status}`);
+ s.info = data;
+ } catch (e) {
+ s.loadError = friendlyError(e.message || String(e));
+ }
+ s.loading = false;
+ render();
+ }
+
+ // Resolve the agent custodial wallet address once, so we know whether to use
+ // the server-signed path. Best-effort — failure just falls back to connected.
+ async function resolveAgentWallet() {
+ if (!agentId && !avatarId) { s.agentWalletAddress = null; return; }
+ try {
+ const r = await fetch('/api/pump/agent-wallet', {
+ method: 'POST', credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ...agentBody(), network }),
+ });
+ const data = await r.json();
+ s.agentWalletAddress = r.ok ? (data.address || null) : null;
+ } catch { s.agentWalletAddress = null; }
+ render();
+ }
+
+ async function tryAutoConnect() {
+ const w = detectWallet();
+ if (!w?.isConnected || !w.publicKey) return;
+ const addr = w.publicKey.toBase58?.() || w.publicKey.toString?.();
+ if (addr) { s.wallet = { provider: w, address: addr }; render(); }
+ }
+
+ async function connectWallet() {
+ const w = detectWallet();
+ if (!w) { window.open('https://phantom.app/', '_blank', 'noopener'); return; }
+ try {
+ if (!w.isConnected) await w.connect?.();
+ const addr = w.publicKey?.toBase58?.() || w.publicKey?.toString?.();
+ if (addr) { s.wallet = { provider: w, address: addr }; s.actionError = ''; render(); }
+ } catch { /* dismissed */ }
+ }
+
+ // ── Transaction helpers ─────────────────────────────────────────────────────
+
+ async function pollConfirm(conn, sig, timeoutMs = 75_000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const { value } = await conn.getSignatureStatuses([sig], { searchTransactionHistory: true });
+ const st = value?.[0];
+ if (st) {
+ if (st.err) throw new Error(`On-chain error: ${JSON.stringify(st.err)}`);
+ if (st.confirmationStatus === 'confirmed' || st.confirmationStatus === 'finalized') return;
+ }
+ await sleep(2000);
+ }
+ throw new Error('Confirmation timed out — the transaction may still land. Check Solscan.');
+ }
+
+ async function signSendPrep(txBase64) {
+ const { VersionedTransaction, Connection } = await loadWeb3();
+ const tx = VersionedTransaction.deserialize(Uint8Array.from(atob(txBase64), (c) => c.charCodeAt(0)));
+ const signed = await s.wallet.provider.signTransaction(tx);
+ const conn = new Connection(RPC_URL, 'confirmed');
+ const sig = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false });
+ await pollConfirm(conn, sig);
+ return sig;
+ }
+
+ function finishAction(label, sig) {
+ s.busy = ''; s.actionError = '';
+ s.actionOk = { label, sig };
+ render();
+ loadInfo(); // refresh on-chain truth
+ }
+
+ function failAction(e) {
+ s.busy = ''; s.actionError = friendlyError(e.message || String(e)); render();
+ }
+
+ // ── Actions ─────────────────────────────────────────────────────────────────
+
+ async function claimCreatorFees() {
+ if (s.busy) return;
+ s.busy = 'Claiming…'; s.actionError = ''; s.actionOk = null; render();
+ try {
+ let sig;
+ if (isAgentCreator()) {
+ const r = await fetch('/api/pump/collect-creator-fee-agent', {
+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ...agentBody(), mint, network }),
+ });
+ const d = await r.json();
+ if (!r.ok) throw new Error(d.error_description || d.error || `HTTP ${r.status}`);
+ sig = d.signature;
+ } else {
+ if (!s.wallet) { await connectWallet(); if (!s.wallet) { s.busy = ''; render(); return; } }
+ const r = await fetch('/api/pump/collect-creator-fee-prep', {
+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ creator_address: creator, wallet_address: s.wallet.address, network }),
+ });
+ const d = await r.json();
+ if (!r.ok) throw new Error(d.error_description || d.error || `HTTP ${r.status}`);
+ sig = await signSendPrep(d.tx_base64);
+ }
+ finishAction('Creator fees claimed', sig);
+ } catch (e) { failAction(e); }
+ }
+
+ async function distribute() {
+ if (s.busy) return;
+ s.busy = 'Distributing…'; s.actionError = ''; s.actionOk = null; render();
+ try {
+ let sig;
+ // Prefer the connected wallet (so a delegated shareholder can crank it);
+ // fall back to the agent wallet when the agent is the creator.
+ if (s.wallet) {
+ const r = await fetch('/api/pump/distribute-creator-fees-prep', {
+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ mint, wallet_address: s.wallet.address, network }),
+ });
+ const d = await r.json();
+ if (!r.ok) throw new Error(d.error_description || d.error || `HTTP ${r.status}`);
+ sig = await signSendPrep(d.tx_base64);
+ } else if (isAgentCreator()) {
+ const r = await fetch('/api/pump/distribute-creator-fees-agent', {
+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ...agentBody(), mint, network }),
+ });
+ const d = await r.json();
+ if (!r.ok) throw new Error(d.error_description || d.error || `HTTP ${r.status}`);
+ sig = d.signature;
+ } else {
+ await connectWallet(); s.busy = ''; render(); return;
+ }
+ finishAction('Rewards distributed to shareholders', sig);
+ } catch (e) { failAction(e); }
+ }
+
+ async function saveDelegation() {
+ const split = validateShareSplit(s.rows);
+ if (!split.ok) { s.actionError = split.errors[0]; render(); return; }
+ const shareholders = s.rows
+ .filter((r) => r.address?.trim() && r.bps > 0)
+ .map((r) => ({ address: r.address.trim(), share_bps: r.bps }));
+
+ s.busy = 'Saving split…'; s.actionError = ''; s.actionOk = null; render();
+ try {
+ if (isAgentCreator()) {
+ const r = await fetch('/api/pump/fee-sharing-agent', {
+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ...agentBody(), mint, network, shareholders }),
+ });
+ const d = await r.json();
+ if (!r.ok) throw new Error(d.error_description || d.error || `HTTP ${r.status}`);
+ s.editing = false;
+ finishAction('Reward split saved on-chain', d.signatures?.[d.signatures.length - 1]);
+ } else {
+ // Connected-wallet creator: create config (if needed) then set shares,
+ // signing each step in the wallet.
+ if (!s.wallet) { await connectWallet(); if (!s.wallet) { s.busy = ''; render(); return; } }
+ if (!s.info?.has_sharing_config) {
+ s.busy = 'Creating config…'; render();
+ const cr = await fetch('/api/pump/create-fee-sharing-prep', {
+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ mint, creator_address: creator, wallet_address: s.wallet.address, network }),
+ });
+ const cd = await cr.json();
+ if (!cr.ok) throw new Error(cd.error_description || cd.error || `HTTP ${cr.status}`);
+ await signSendPrep(cd.tx_base64);
+ }
+ s.busy = 'Setting shares…'; render();
+ const current = (s.info?.sharing_config?.shareholders || []).map((h) => h.address);
+ const ur = await fetch('/api/pump/update-fee-shares-prep', {
+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ mint, wallet_address: s.wallet.address, network,
+ current_shareholders: current.length ? current : [creator],
+ new_shareholders: shareholders,
+ }),
+ });
+ const ud = await ur.json();
+ if (!ur.ok) throw new Error(ud.error_description || ud.error || `HTTP ${ur.status}`);
+ const sig = await signSendPrep(ud.tx_base64);
+ s.editing = false;
+ finishAction('Reward split saved on-chain', sig);
+ }
+ } catch (e) { failAction(e); }
+ }
+
+ // ── GitHub import ─────────────────────────────────────────────────────────────
+
+ async function importGithub() {
+ const parsed = parseGithubRepo(s.githubRepo);
+ if (!parsed) { s.githubError = 'Enter a repo as owner/name (e.g. solana-labs/solana).'; render(); return; }
+ s.githubBusy = true; s.githubError = ''; render();
+ try {
+ const r = await fetch(
+ `https://api.github.com/repos/${parsed.owner}/${parsed.repo}/contributors?per_page=10`,
+ { headers: { accept: 'application/vnd.github+json' } });
+ if (r.status === 404) throw new Error('Repository not found.');
+ if (r.status === 403) throw new Error('GitHub rate limit hit — try again in a minute.');
+ if (!r.ok) throw new Error(`GitHub error ${r.status}`);
+ const contributors = (await r.json())
+ .filter((c) => c.type === 'User')
+ .slice(0, 10);
+ if (!contributors.length) throw new Error('No contributors found on that repo.');
+ const bps = weightsToBps(contributors.map((c) => c.contributions || 1));
+ s.rows = contributors.map((c, i) => ({
+ address: '', bps: bps[i],
+ gh: { login: c.login, avatar: c.avatar_url, url: c.html_url },
+ }));
+ s.editing = true;
+ } catch (e) {
+ s.githubError = friendlyError(e.message || String(e));
+ }
+ s.githubBusy = false;
+ render();
+ }
+
+ // ── Delegation editor row helpers ─────────────────────────────────────────────
+
+ function startEditing(seed) {
+ s.rows = seed && seed.length
+ ? seed.map((h) => ({ address: h.address, bps: h.bps }))
+ : [{ address: '', bps: 10_000 }];
+ s.editing = true; s.actionError = ''; render();
+ }
+ function addRow() { if (s.rows.length < 10) { s.rows.push({ address: '', bps: 0 }); render(); } }
+ function removeRow(i) { s.rows.splice(i, 1); render(); }
+
+ // ── Render ────────────────────────────────────────────────────────────────────
+
+ function render() {
+ if (!_alive) return;
+ if (s.loading && !s.info) { renderLoading(); return; }
+ if (s.loadError && !s.info) { renderLoadError(); return; }
+ renderMain();
+ }
+
+ function renderLoading() {
+ container.innerHTML = `<div class="fp"><div class="fp-loading"><div class="fp-spin"></div>Reading on-chain fees…</div></div>`;
+ }
+
+ function renderLoadError() {
+ container.innerHTML = `<div class="fp">
+ <div class="fp-head"><span class="fp-head-t">Fees &amp; rewards</span></div>
+ <div class="fp-err">${esc(s.loadError)}</div>
+ <button class="fp-btn ghost" id="fp-retry">Retry</button>
+ </div>`;
+ container.querySelector('#fp-retry')?.addEventListener('click', loadInfo);
+ }
+
+ function renderMain() {
+ const info = s.info || {};
+ const dest = info.fee_destination;
+ const badge = dest === 'sharing_config'
+ ? `<span class="fp-badge split">Delegated split</span>`
+ : dest === 'cashback'
+ ? `<span class="fp-badge cashback">Trader cashback</span>`
+ : `<span class="fp-badge creator">Creator fees</span>`;
+
+ const okBlock = s.actionOk
+ ? `<div class="fp-ok">✓ ${esc(s.actionOk.label)}${s.actionOk.sig
+ ? ` · <a href="${esc(SOLSCAN(s.actionOk.sig, network))}" target="_blank" rel="noopener">view ↗</a>` : ''}</div>`
+ : '';
+ const errBlock = s.actionError ? `<div class="fp-err">${esc(s.actionError)}</div>` : '';
+
+ container.innerHTML = `<div class="fp">
+ <div class="fp-head"><span class="fp-head-t">Fees &amp; rewards</span>${badge}</div>
+ ${renderClaim(info)}
+ ${okBlock}${errBlock}
+ ${renderDelegation(info)}
+ ${renderSignerHint(info)}
+ </div>`;
+
+ wire();
+ }
+
+ function renderClaim(info) {
+ if (info.is_cashback_coin) {
+ return `<div class="fp-note">This coin returns trading fees to holders as <b>cashback</b> — there's no creator vault to claim. Traders claim their own cashback from pump.fun.</div>`;
+ }
+ const sol = Number(info.claimable_sol || 0);
+ const has = sol > 0.0000001;
+ const amt = sol < 0.001 && has ? sol.toFixed(6) : sol.toFixed(4);
+ const inFlight = s.busy === 'Claiming…' || s.busy === 'Distributing…';
+ // When fees are delegated, the claim button cranks distribution instead of
+ // pulling to a single creator.
+ const delegated = info.fee_destination === 'sharing_config';
+ const label = delegated ? 'Distribute' : 'Claim';
+ const action = delegated ? 'distribute' : 'claim';
+ const sub = delegated ? 'Accrued · splits to shareholders' : 'Claimable creator fees';
+ return `<div class="fp-claim">
+ <div class="fp-claim-amt">
+ <div class="fp-claim-n">${amt}<small>SOL</small></div>
+ <div class="fp-claim-l">${sub}</div>
+ </div>
+ <button class="fp-btn primary${inFlight ? ' busy' : ''}" id="fp-claim" data-action="${action}" ${(!has || s.busy) ? 'disabled' : ''}>
+ ${inFlight ? s.busy : label}
+ </button>
+ </div>`;
+ }
+
+ function renderDelegation(info) {
+ if (info.is_cashback_coin) return '';
+
+ // Editing mode — shareholder split editor + GitHub import.
+ if (s.editing) return renderEditor(info);
+
+ // Existing on-chain split.
+ if (info.has_sharing_config && info.sharing_config?.shareholders?.length) {
+ const holders = info.sharing_config.shareholders;
+ const rowsHtml = holders.map((h) => {
+ const you = s.wallet?.address === h.address;
+ return `<div class="fp-holder${you ? ' is-you' : ''}">
+ <code title="${esc(h.address)}">${esc(shortAddr(h.address))}</code>
+ ${you ? `<span class="fp-you-tag">YOU</span>` : ''}
+ <span class="fp-holder-pct">${(h.bps / 100).toFixed(1)}%</span>
+ </div>`;
+ }).join('');
+ const youNote = youAreShareholder()
+ ? `<div class="fp-note you">You're delegated ${(holders.find((h) => h.address === s.wallet.address).bps / 100).toFixed(1)}% of creator fees. Hit <b>Distribute</b> above to release accrued rewards to every shareholder, including you.</div>`
+ : '';
+ const canEdit = isAgentCreator() || connectedIsCreator();
+ return `<div class="fp-deleg">
+ <div class="fp-deleg-title">Reward split — ${holders.length} recipient${holders.length === 1 ? '' : 's'}</div>
+ <div class="fp-holders">${rowsHtml}</div>
+ ${youNote}
+ ${canEdit ? `<div class="fp-deleg-foot"><button class="fp-btn ghost" id="fp-edit">Edit split</button></div>` : ''}
+ </div>`;
+ }
+
+ // No split yet — offer to set one up (gated by graduation).
+ if (!info.is_graduated) {
+ return `<div class="fp-note warn">🎁 <b>Delegated rewards</b> unlock once this coin graduates to the AMM (reaches the bonding-curve cap). Until then, all creator fees go to the creator and can be claimed above.</div>`;
+ }
+ return `<div class="fp-cta" id="fp-setup" role="button" tabindex="0">
+ <span class="fp-cta-ic">🎁</span>
+ <div class="fp-cta-b">
+ <div class="fp-cta-t">Delegate fees as rewards</div>
+ <div class="fp-cta-s">Split creator fees across a team or GitHub contributors. Each delegated wallet can claim its share.</div>
+ </div>
+ <span class="fp-cta-arrow">→</span>
+ </div>`;
+ }
+
+ function renderEditor(info) {
+ const split = validateShareSplit(s.rows);
+ const totalPct = (split.totalBps / 100).toFixed(1);
+ const totalCls = split.totalBps === 10_000 ? 'ok' : 'bad';
+ const rowsHtml = s.rows.map((r, i) => `
+ <div class="fp-share-row" data-i="${i}">
+ <div class="fp-sh-meta">
+ <input class="fp-share-addr" data-i="${i}" placeholder="Recipient Solana wallet" value="${esc(r.address)}" spellcheck="false" />
+ ${r.gh ? `<span class="fp-share-gh"><img src="${esc(r.gh.avatar)}" alt="" />@${esc(r.gh.login)}</span>` : ''}
+ </div>
+ <input class="fp-share-pct" data-i="${i}" type="number" min="0" max="100" step="0.1" value="${(r.bps / 100).toFixed(1)}" />
+ <button class="fp-share-x" data-i="${i}" title="Remove">✕</button>
+ </div>`).join('');
+
+ const busy = !!s.busy;
+ return `<div class="fp-deleg">
+ <div class="fp-deleg-title">🎁 Reward split — delegate creator fees</div>
+ <div class="fp-gh">
+ <input id="fp-gh-input" placeholder="Import GitHub repo — owner/name" value="${esc(s.githubRepo)}" spellcheck="false" />
+ <button class="fp-btn violet${s.githubBusy ? ' busy' : ''}" id="fp-gh-go" ${s.githubBusy ? 'disabled' : ''}>${s.githubBusy ? 'Loading…' : 'Import'}</button>
+ </div>
+ ${s.githubError ? `<div class="fp-err">${esc(s.githubError)}</div>` : ''}
+ ${s.rows.length ? rowsHtml : `<div class="fp-note">Add recipients below or import a GitHub repo's contributors.</div>`}
+ <button class="fp-add" id="fp-add" ${s.rows.length >= 10 ? 'disabled' : ''}>+ Add recipient</button>
+ <div class="fp-deleg-foot">
+ <span class="fp-deleg-total ${totalCls}">Total ${totalPct}%</span>
+ <button class="fp-btn ghost" id="fp-cancel" ${busy ? 'disabled' : ''}>Cancel</button>
+ <button class="fp-btn primary${busy ? ' busy' : ''}" id="fp-save" ${busy ? 'disabled' : ''}>${busy ? esc(s.busy) : 'Save split on-chain'}</button>
+ </div>
+ <div class="fp-note">Shares are written to a pump.fun fee-sharing config. ${isAgentCreator() ? 'Your agent wallet signs.' : 'Your connected creator wallet signs (one or two prompts).'} Each recipient can then claim by distributing.</div>
+ </div>`;
+ }
+
+ // Tell the user which wallet is needed when a creator-only action can't be
+ // taken with the current signer.
+ function renderSignerHint(info) {
+ if (info.is_cashback_coin) return '';
+ if (isAgentCreator()) {
+ return `<div class="fp-wallet on"><span class="fp-w-dot"></span>Signed by agent wallet <code>${esc(shortAddr(creator))}</code></div>`;
+ }
+ // Creator is an external wallet — surface connect / mismatch state.
+ if (!s.wallet) {
+ return `<div class="fp-wallet"><span class="fp-w-dot"></span>Connect the creator wallet to manage fees
+ <button class="fp-w-btn" id="fp-connect">Connect</button></div>`;
+ }
+ if (!connectedIsCreator() && !youAreShareholder()) {
+ return `<div class="fp-wallet on"><span class="fp-w-dot"></span>Connected <code>${esc(shortAddr(s.wallet.address))}</code> — creator is <code title="${esc(creator)}">${esc(shortAddr(creator))}</code>. Claiming needs the creator wallet.</div>`;
+ }
+ return `<div class="fp-wallet on"><span class="fp-w-dot"></span>Connected <code>${esc(shortAddr(s.wallet.address))}</code></div>`;
+ }
+
+ // ── Wiring ──────────────────────────────────────────────────────────────────
+
+ function wire() {
+ const q = (sel) => container.querySelector(sel);
+
+ q('#fp-claim')?.addEventListener('click', (e) => {
+ e.currentTarget.dataset.action === 'distribute' ? distribute() : claimCreatorFees();
+ });
+ q('#fp-edit')?.addEventListener('click', () => startEditing(s.info?.sharing_config?.shareholders));
+ const setup = q('#fp-setup');
+ if (setup) {
+ setup.addEventListener('click', () => startEditing());
+ setup.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); startEditing(); } });
+ }
+ q('#fp-connect')?.addEventListener('click', connectWallet);
+
+ // Editor
+ q('#fp-add')?.addEventListener('click', addRow);
+ q('#fp-cancel')?.addEventListener('click', () => { s.editing = false; s.actionError = ''; render(); });
+ q('#fp-save')?.addEventListener('click', saveDelegation);
+ q('#fp-gh-go')?.addEventListener('click', importGithub);
+ q('#fp-gh-input')?.addEventListener('input', (e) => { s.githubRepo = e.target.value; });
+ q('#fp-gh-input')?.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); importGithub(); } });
+
+ container.querySelectorAll('.fp-share-addr').forEach((el) => {
+ el.addEventListener('input', (e) => { s.rows[+e.target.dataset.i].address = e.target.value; });
+ });
+ container.querySelectorAll('.fp-share-pct').forEach((el) => {
+ el.addEventListener('input', (e) => {
+ const pct = Math.max(0, Math.min(100, parseFloat(e.target.value) || 0));
+ s.rows[+e.target.dataset.i].bps = Math.round(pct * 100);
+ const t = container.querySelector('.fp-deleg-total');
+ const split = validateShareSplit(s.rows);
+ if (t) { t.textContent = `Total ${(split.totalBps / 100).toFixed(1)}%`; t.className = `fp-deleg-total ${split.totalBps === 10_000 ? 'ok' : 'bad'}`; }
+ });
+ });
+ container.querySelectorAll('.fp-share-x').forEach((el) => {
+ el.addEventListener('click', (e) => removeRow(+e.currentTarget.dataset.i));
+ });
+ }
+
+ // ── Boot ────────────────────────────────────────────────────────────────────
+
+ render();
+ loadInfo();
+ resolveAgentWallet();
+ tryAutoConnect();
+
+ return {
+ teardown() { _alive = false; container.innerHTML = ''; },
+ };
+}
diff --git a/public/studio/launch-panel.js b/public/studio/launch-panel.js
index 828f8dea5..2747d478d 100644
--- a/public/studio/launch-panel.js
+++ b/public/studio/launch-panel.js
@@ -10,6 +10,8 @@
// DOM entry:
// mountLaunchPanel(el, { getAvatar, getUser }) → { avatarChanged, teardown }
+import { mountFeesPanel } from './fees-panel.js';
+
// ── Pure validation ─────────────────────────────────────────────────────────
export function validateLaunchForm({ name, symbol, description, initialBuy } = {}) {
@@ -101,8 +103,9 @@ const LP_CSS = `
.lp-src button.on .lp-src-sub{color:rgba(164,240,188,.55)}
/* Coin-type selector */
-.lp-coin{display:grid;grid-template-columns:repeat(4,1fr);gap:.3rem;padding:.25rem;
+.lp-coin{display:grid;grid-template-columns:repeat(5,1fr);gap:.3rem;padding:.25rem;
background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:10px}
+@media (max-width:360px){.lp-coin{grid-template-columns:repeat(3,1fr)}}
.lp-coin button{padding:.5rem .35rem;border-radius:7px;cursor:pointer;background:transparent;
border:1px solid transparent;color:rgba(255,255,255,.5);font-size:.74rem;font-weight:600;
transition:all .15s;line-height:1.2;text-align:center}
@@ -110,16 +113,20 @@ const LP_CSS = `
.lp-coin button.on{background:rgba(164,240,188,.12);border-color:rgba(164,240,188,.32);color:#c8f0d8}
.lp-coin button.mayhem.on{background:rgba(246,140,80,.14);border-color:rgba(246,140,80,.38);color:#f6c498}
.lp-coin button.usdc.on{background:rgba(120,160,240,.12);border-color:rgba(120,160,240,.34);color:#a8c4f0}
+.lp-coin button.reward.on{background:rgba(170,140,240,.14);border-color:rgba(170,140,240,.36);color:#cdbcf8}
.lp-coin button[disabled]{opacity:.42;cursor:not-allowed}
.lp-coin-sub{display:block;font-size:.6rem;color:rgba(255,255,255,.32);font-weight:400;margin-top:.18rem;letter-spacing:.01em}
.lp-coin button.on .lp-coin-sub{color:rgba(200,240,216,.62)}
.lp-coin button.mayhem.on .lp-coin-sub{color:rgba(246,196,152,.72)}
.lp-coin button.usdc.on .lp-coin-sub{color:rgba(168,196,240,.72)}
+.lp-coin button.reward.on .lp-coin-sub{color:rgba(205,188,248,.72)}
.lp-coin-emoji{display:block;font-size:.95rem;line-height:1;margin-bottom:.18rem}
.lp-coin-note{font-size:.7rem;color:rgba(255,255,255,.42);line-height:1.5;padding:.45rem .65rem;
background:rgba(255,255,255,.025);border:1px solid rgba(255,255,255,.06);border-radius:8px}
.lp-coin-note.mayhem{color:rgba(246,196,152,.85);background:rgba(246,140,80,.07);border-color:rgba(246,140,80,.2)}
.lp-coin-note.usdc{color:rgba(168,196,240,.85);background:rgba(120,160,240,.07);border-color:rgba(120,160,240,.22)}
+.lp-coin-note.reward{color:rgba(205,188,248,.9);background:rgba(170,140,240,.07);border-color:rgba(170,140,240,.22)}
+.lp-coin-note.reward b{color:#dccff8}
.lp-empty{text-align:center;padding:2.5rem 1rem;color:rgba(255,255,255,.3);font-size:.85rem;line-height:1.7}
.lp-empty a{color:rgba(164,240,188,.7);text-decoration:none}
.lp-empty a:hover{color:#a4f0bc}
@@ -434,8 +441,14 @@ export function mountLaunchPanel(container, { getAvatar, getUser, getPreviewView
let _balanceInterval = null;
const _walletListeners = []; // [{ wallet, event, fn }]
+ let _feesPanel = null; // mounted fee/rewards panel in the existing-token view
+
+ function teardownFees() {
+ if (_feesPanel) { try { _feesPanel.teardown(); } catch { /* ignore */ } _feesPanel = null; }
+ }
function cleanup() {
+ teardownFees();
if (_balanceInterval) { clearInterval(_balanceInterval); _balanceInterval = null; }
if (s._agentBalanceTimer) { clearInterval(s._agentBalanceTimer); s._agentBalanceTimer = null; }
for (const { wallet, event, fn } of _walletListeners) {
@@ -846,7 +859,7 @@ export function mountLaunchPanel(container, { getAvatar, getUser, getPreviewView
}
function switchCoinType(next) {
- if (!['regular', 'mayhem', 'agent', 'usdc'].includes(next)) return;
+ if (!['regular', 'mayhem', 'agent', 'usdc', 'reward'].includes(next)) return;
if (next === s.coinType) return;
s.coinType = next;
s.errorMsg = '';
@@ -1037,7 +1050,9 @@ export function mountLaunchPanel(container, { getAvatar, getUser, getPreviewView
...(av.agent_id ? { agent_id: av.agent_id } : { avatar_id: av.id }),
wallet_address: payer,
name: nameTrim, symbol: symTrim, uri: s._metaUrl,
- coin_type: isUsdc ? 'agent' : s.coinType,
+ // 'reward' launches as a plain pump.fun coin; the delegated fee split
+ // is configured after graduation in the Fees & rewards panel.
+ coin_type: isUsdc ? 'agent' : s.coinType === 'reward' ? 'regular' : s.coinType,
buyback_bps: (isUsdc || s.coinType === 'agent') ? s.buybackBps : 0,
...(isUsdc
? { usdc_buy_in: buyIn, quote_mint: USDC_MAINNET_MINT }
@@ -1151,6 +1166,10 @@ export function mountLaunchPanel(container, { getAvatar, getUser, getPreviewView
// ── Render ─────────────────────────────────────────────────────────────
function render() {
+ // The fee/rewards panel only lives in the existing-token view; tear it down
+ // before any re-render so it never leaks across views (renderExisting
+ // re-mounts it fresh against the current mint).
+ teardownFees();
if (!av || av.id === DEMO_ID) { renderEmpty(); return; }
if (s.checkingMint) { renderChecking(); return; }
if (s.existingMint && !s.forceNew) { renderExisting(); return; }
@@ -1190,6 +1209,7 @@ export function mountLaunchPanel(container, { getAvatar, getUser, getPreviewView
<div class="lp-guide-type" title="Pump.fun high-volatility mode — no agent buyback or payments. Pure speculation."><b>🔥 Mayhem</b>High-volatility mode on pump.fun.</div>
<div class="lp-guide-type" title="Agent revenue (SOL from paid endpoints) buys back and burns the token automatically."><b>🤖 Agent</b>SOL revenue auto-buyback &amp; burn.</div>
<div class="lp-guide-type" title="USDC-denominated agent payments via agent-payments-sdk. Coming soon."><b>💵 USDC</b>Stablecoin-denominated. Coming soon.</div>
+ <div class="lp-guide-type" title="Open-source reward coin — delegate creator fees to a team or GitHub contributors who each claim their share."><b>🎁 Reward</b>Delegate fees to contributors.</div>
</div>
<div class="lp-guide-tip">
@@ -1257,6 +1277,7 @@ export function mountLaunchPanel(container, { getAvatar, getUser, getPreviewView
? `<a class="lp-ex-link" href="/agent/${esc(s.resolvedAgentId || av.agent_id)}">Agent page ↗</a>`
: ''}
</div>
+ <div id="lp-fees"></div>
<button class="lp-ex-new" id="lp-force-new">Launch a new token for this avatar</button>
</div></div>`;
@@ -1268,6 +1289,23 @@ export function mountLaunchPanel(container, { getAvatar, getUser, getPreviewView
container.querySelector('#lp-force-new')?.addEventListener('click', () => {
s.forceNew = true; render();
});
+
+ // Mount the fees & rewards control surface against this coin. The on-chain
+ // creator (agent_authority) decides whether claims are server-signed by the
+ // agent wallet or signed by the user's connected creator wallet.
+ const feesEl = container.querySelector('#lp-fees');
+ if (feesEl && m.mint) {
+ _feesPanel = mountFeesPanel(feesEl, {
+ mint: m.mint,
+ network: m.network || 'mainnet',
+ creator: m.agent_authority || null,
+ agentId: s.resolvedAgentId || av?.agent_id || null,
+ avatarId: av?.id || null,
+ symbol: m.symbol || '',
+ name: m.name || '',
+ getUser,
+ });
+ }
}
function renderTimeout() {
@@ -1458,15 +1496,20 @@ export function mountLaunchPanel(container, { getAvatar, getUser, getPreviewView
<button type="button" role="tab" data-coin="usdc" class="usdc ${ct === 'usdc' ? 'on' : ''}" ${busy ? 'disabled' : ''} title="USDC-paired agent coin — trades and pays out in USDC instead of SOL.">
<span class="lp-coin-emoji">💵</span>USDC<span class="lp-coin-sub">Stablecoin pair</span>
</button>
+ <button type="button" role="tab" data-coin="reward" class="reward ${ct === 'reward' ? 'on' : ''}" ${busy ? 'disabled' : ''} title="Open-source / GitHub reward coin — creator fees are delegated and split to a team or repo contributors who each claim their share.">
+ <span class="lp-coin-emoji">🎁</span>Reward<span class="lp-coin-sub">Delegated fees</span>
+ </button>
</div>`;
const coinNoteHtml = ct === 'mayhem'
? `<div class="lp-coin-note mayhem">Mayhem coins launch on pump.fun's high-volatility mode. No agent buyback or payments — pure speculation.</div>`
: ct === 'usdc'
? `<div class="lp-coin-note usdc">USDC-paired agent coin. Bonding curve quotes in USDC instead of SOL — your initial buy and all subsequent trades settle through the wallet's USDC ATA. Buyback share still applies, denominated in USDC.</div>`
- : ct === 'regular'
- ? `<div class="lp-coin-note">Standard pump.fun launch — no on-chain buyback. Initial buy still funds bonding curve.</div>`
- : '';
+ : ct === 'reward'
+ ? `<div class="lp-coin-note reward">Open-source reward coin. Launches as a standard pump.fun coin, then once it graduates you delegate creator fees as a split — import a GitHub repo's contributors or add wallets in <b>Fees &amp; rewards</b>. Each delegated wallet claims its share.</div>`
+ : ct === 'regular'
+ ? `<div class="lp-coin-note">Standard pump.fun launch — no on-chain buyback. Initial buy still funds bonding curve.</div>`
+ : '';
// USDC coins are agent-buyback-bound (same on-chain agent identity flow
// as 'agent'), so surface the buyback slider for both variants.
diff --git a/public/style.css b/public/style.css
index 1698fa7e6..6ec27bdcd 100644
--- a/public/style.css
+++ b/public/style.css
@@ -3815,8 +3815,8 @@ body.deploy-page {
color: #fff;
}
.showcase-seg--active {
- background: #fff;
- color: #0a0a0a;
+ background: var(--accent);
+ color: #000;
}
/* sort select */
@@ -3833,9 +3833,9 @@ body.deploy-page {
}
.showcase-sort-sel {
padding: 7px 12px;
- background: rgba(255, 255, 255, 0.04);
- border: 1px solid rgba(255, 255, 255, 0.12);
- border-radius: 10px;
+ background: var(--surface-2);
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-control);
color: #fff;
font: inherit;
font-size: var(--text-sm);
@@ -3875,9 +3875,9 @@ body.deploy-page {
border-color: rgba(255, 255, 255, 0.2);
}
.showcase-chip--active {
- color: #0a0a0a;
- background: #fff;
- border-color: #fff;
+ color: #000;
+ background: var(--accent);
+ border-color: var(--accent);
}
.showcase-chip-dot {
width: 6px;
@@ -3886,13 +3886,13 @@ body.deploy-page {
background: rgba(255, 255, 255, 0.45);
}
.showcase-chip--active .showcase-chip-dot {
- background: #0a0a0a;
+ background: #000;
}
.showcase-chip--testnet .showcase-chip-dot {
- background: #fbbf24;
+ background: var(--warn);
}
.showcase-chip--active.showcase-chip--testnet .showcase-chip-dot {
- background: #0a0a0a;
+ background: #000;
}
.showcase-chip-reset {
padding: 5px 11px;
@@ -3925,8 +3925,8 @@ body.deploy-page {
display: flex;
flex-direction: column;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.045), rgba(255, 255, 255, 0.015));
- border: 1px solid rgba(255, 255, 255, 0.08);
- border-radius: 14px;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-card);
overflow: hidden;
transition:
transform 0.16s ease,
@@ -3982,7 +3982,7 @@ body.deploy-page {
border-radius: 999px;
}
.showcase-chain-badge--testnet {
- color: #fbbf24;
+ color: var(--warn);
}
.showcase-card-3dpill {
position: absolute;
@@ -3991,7 +3991,7 @@ body.deploy-page {
padding: 3px 9px;
font-size: 11px;
font-weight: 600;
- color: #0a0a0a;
+ color: #000;
background: rgba(255, 255, 255, 0.92);
border-radius: 999px;
opacity: 0;
@@ -4059,7 +4059,7 @@ body.deploy-page {
font-size: 11px;
font-weight: 500;
color: rgba(255, 255, 255, 0.7);
- background: rgba(255, 255, 255, 0.05);
+ background: var(--surface-2);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 999px;
}
@@ -4068,7 +4068,7 @@ body.deploy-page {
border-color: rgba(255, 255, 255, 0.22);
}
.showcase-tag--x402 {
- color: #4ade80;
+ color: var(--success);
border-color: rgba(74, 222, 128, 0.3);
background: rgba(74, 222, 128, 0.08);
}
@@ -4100,9 +4100,9 @@ body.deploy-page {
font-weight: 500;
color: #fff;
text-decoration: none;
- background: rgba(255, 255, 255, 0.05);
+ background: var(--surface-2);
border: 1px solid rgba(255, 255, 255, 0.1);
- border-radius: 10px;
+ border-radius: var(--radius-control);
cursor: pointer;
transition:
background 0.12s ease,
@@ -4126,19 +4126,33 @@ body.deploy-page {
border-radius: 8px;
}
.showcase-btn--primary {
- background: #fff;
- border-color: #fff;
- color: #0a0a0a;
+ background: var(--accent);
+ border-color: var(--accent);
+ color: #000;
font-weight: 600;
}
.showcase-btn--primary:hover {
- background: #e8e8e8;
- border-color: #e8e8e8;
+ background: var(--ink);
+ border-color: var(--ink);
}
.showcase-btn--ghost {
background: transparent;
}
+/* Keyboard focus — interactive elements get a visible ring (the dashboard's
+ blanket ring is scoped to .dn-shell and doesn't reach the showcase). */
+.showcase-seg:focus-visible,
+.showcase-chip:focus-visible,
+.showcase-chip-reset:focus-visible,
+.showcase-sort-sel:focus-visible,
+.showcase-btn:focus-visible,
+.showcase-card-thumb:focus-visible,
+.showcase-card-title:focus-visible,
+.showcase-card-owner:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+}
+
/* load more */
.showcase-loadmore {
display: flex;
@@ -4220,6 +4234,12 @@ body.deploy-page {
.showcase-empty .showcase-btn {
margin-top: var(--space-sm);
}
+.showcase-empty--error .showcase-empty-art {
+ opacity: 1;
+}
+.showcase-empty--error h3 {
+ color: var(--danger);
+}
@media (max-width: 560px) {
.showcase-grid {
diff --git a/src/agents-directory.js b/src/agents-directory.js
index fff87dc17..8301d0bbe 100644
--- a/src/agents-directory.js
+++ b/src/agents-directory.js
@@ -306,7 +306,7 @@ export class AgentsDirectory {
</div>
</div>
<p class="card-desc">${cleanDesc}${agent.description.length > 140 ? '…' : ''}</p>
- ${onchainBadge ? `<div class="card-onchain">${onchainBadge}</div>` : ''}
+ ${onchainBadge ? `<div class="card-onchain" style="margin:8px 0 2px">${onchainBadge}</div>` : ''}
${protoBadges || overflow ? `<div class="card-protos">${protoBadges}${overflow}</div>` : ''}
${trustPills ? `<div class="card-trust">${trustPills}</div>` : ''}
${
diff --git a/src/erc8004/deploy-button.css b/src/erc8004/deploy-button.css
index 31f9a56a6..8e9dfc628 100644
--- a/src/erc8004/deploy-button.css
+++ b/src/erc8004/deploy-button.css
@@ -244,66 +244,6 @@
font-style: italic;
}
-/* ── Light-mode overrides ────────────────────────────────────────────────── */
-
-@media (prefers-color-scheme: light) {
- .deploy-chain-select {
- border-color: rgba(0, 0, 0, 0.18);
- background-color: rgba(0, 0, 0, 0.03);
- color: #444;
- }
-
- .deploy-chain-select:hover:not(:disabled) {
- background-color: rgba(0, 0, 0, 0.05);
- color: #111;
- border-color: rgba(0, 0, 0, 0.35);
- }
-
- .deploy-chain-select option {
- background: #fff;
- color: #111;
- }
-
- .deploy-btn {
- border-color: rgba(0, 0, 0, 0.18);
- background: rgba(0, 0, 0, 0.03);
- color: #111;
- }
-
- .deploy-btn:hover:not(:disabled) {
- background: rgba(0, 0, 0, 0.06);
- border-color: rgba(0, 0, 0, 0.4);
- color: #000;
- }
-
- .deploy-chip--success {
- background: #ecfdf5;
- border-color: #22c55e;
- color: #15803d;
- }
-
- .deploy-progress {
- color: #555;
- }
-
- .progress-step--active {
- color: #111;
- background: rgba(0, 0, 0, 0.06);
- border-color: rgba(0, 0, 0, 0.25);
- }
-
- .progress-step--done {
- color: #15803d;
- }
-
- .deploy-error {
- background: #fff1f2;
- border-color: #fca5a5;
- color: #b91c1c;
- }
-
- .deploy-action-btn {
- border-color: #b91c1c;
- color: #b91c1c;
- }
-}
+/* No light-mode block: three.ws is a dark-only product (no prefers-color-scheme
+ switch anywhere in theme.css / style.css). This control must stay dark to match
+ the page it lives in, regardless of the visitor's OS theme. */
diff --git a/src/erc8004/deploy-button.js b/src/erc8004/deploy-button.js
index 12cca76b4..92680f439 100644
--- a/src/erc8004/deploy-button.js
+++ b/src/erc8004/deploy-button.js
@@ -160,7 +160,7 @@ export class DeployButton {
</div>
<div class="deploy-vanity-link-row" style="${showVanity ? '' : 'display:none'};margin-top:4px;font-size:12px;">
<button type="button" class="deploy-vanity-link"
- style="background:none;border:none;color:#0066cc;cursor:pointer;padding:0;font-size:12px;text-decoration:underline">
+ style="background:none;border:none;color:rgba(255,255,255,0.6);cursor:pointer;padding:0;font-size:12px;text-decoration:underline">
${this._vanityPrefix
? `&#10024; Vanity: <span style="font-family:monospace;font-weight:600">${_esc(this._vanityPrefix)}</span> &middot; change`
: '&#10024; Customize address (optional)'}
diff --git a/tests/api/solana-register-prep.test.js b/tests/api/solana-register-prep.test.js
index 2aa5b3f2b..28d1ae3f9 100644
--- a/tests/api/solana-register-prep.test.js
+++ b/tests/api/solana-register-prep.test.js
@@ -48,9 +48,13 @@ vi.mock('@metaplex-foundation/umi-bundle-defaults', () => ({
}));
vi.mock('@metaplex-foundation/mpl-core', () => ({
mplCore: vi.fn(() => () => {}),
+ create: vi.fn(() => ({
+ buildAndSign: vi.fn(async () => FAKE_TX),
+ })),
createV1: vi.fn(() => ({
buildAndSign: vi.fn(async () => FAKE_TX),
})),
+ ruleSet: vi.fn((type) => ({ type })),
fetchAsset: vi.fn(),
}));
vi.mock('@metaplex-foundation/umi', () => ({
diff --git a/tests/studio-fees-panel.test.js b/tests/studio-fees-panel.test.js
new file mode 100644
index 000000000..2fab9c723
--- /dev/null
+++ b/tests/studio-fees-panel.test.js
@@ -0,0 +1,70 @@
+import { describe, it, expect } from 'vitest';
+import { parseGithubRepo, weightsToBps, validateShareSplit } from '../public/studio/fees-panel.js';
+
+// A plausible 44-char base58 Solana address for split validation tests.
+const A = (c) => c.repeat(44);
+
+describe('parseGithubRepo', () => {
+ it('parses owner/repo', () => {
+ expect(parseGithubRepo('solana-labs/solana')).toEqual({ owner: 'solana-labs', repo: 'solana' });
+ });
+ it('parses a full github URL', () => {
+ expect(parseGithubRepo('https://github.com/anza-xyz/agave')).toEqual({ owner: 'anza-xyz', repo: 'agave' });
+ });
+ it('strips a trailing .git and slash', () => {
+ expect(parseGithubRepo('github.com/foo/bar.git/')).toEqual({ owner: 'foo', repo: 'bar' });
+ });
+ it('rejects empty / malformed input', () => {
+ expect(parseGithubRepo('')).toBeNull();
+ expect(parseGithubRepo('justaname')).toBeNull();
+ expect(parseGithubRepo(' ')).toBeNull();
+ });
+});
+
+describe('weightsToBps', () => {
+ it('always sums to exactly 10000', () => {
+ for (const ws of [[1], [1, 1, 1], [5, 3, 2], [100, 1, 1, 1], [7, 7, 7, 7, 7, 7, 7]]) {
+ expect(weightsToBps(ws).reduce((a, b) => a + b, 0)).toBe(10_000);
+ }
+ });
+ it('splits evenly with largest-remainder rounding', () => {
+ expect(weightsToBps([1, 1, 1])).toEqual([3334, 3333, 3333]);
+ });
+ it('weights proportionally', () => {
+ expect(weightsToBps([3, 1])).toEqual([7500, 2500]);
+ });
+ it('handles all-zero weights without NaN', () => {
+ expect(weightsToBps([0, 0])).toEqual([0, 0]);
+ });
+});
+
+describe('validateShareSplit', () => {
+ it('accepts a clean 50/50 split', () => {
+ const r = validateShareSplit([{ address: A('1'), bps: 5000 }, { address: A('2'), bps: 5000 }]);
+ expect(r.ok).toBe(true);
+ expect(r.totalBps).toBe(10_000);
+ });
+ it('rejects when shares do not total 100%', () => {
+ const r = validateShareSplit([{ address: A('1'), bps: 5000 }, { address: A('2'), bps: 4000 }]);
+ expect(r.ok).toBe(false);
+ expect(r.errors.some((e) => /100%/.test(e))).toBe(true);
+ });
+ it('rejects a recipient with no wallet', () => {
+ const r = validateShareSplit([{ address: '', bps: 10_000 }]);
+ expect(r.ok).toBe(false);
+ });
+ it('rejects duplicate wallets', () => {
+ const r = validateShareSplit([{ address: A('1'), bps: 5000 }, { address: A('1'), bps: 5000 }]);
+ expect(r.ok).toBe(false);
+ expect(r.errors.some((e) => /Duplicate/.test(e))).toBe(true);
+ });
+ it('rejects more than 10 recipients', () => {
+ const rows = Array.from({ length: 11 }, (_, i) => ({ address: A(String.fromCharCode(65 + i)), bps: 909 }));
+ const r = validateShareSplit(rows);
+ expect(r.ok).toBe(false);
+ expect(r.errors.some((e) => /Maximum 10/.test(e))).toBe(true);
+ });
+ it('rejects an empty list', () => {
+ expect(validateShareSplit([]).ok).toBe(false);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 207d09681..415a97598 100644
--- a/vercel.json
+++ b/vercel.json
@@ -746,6 +746,10 @@
"src": "/deploy",
"dest": "/app-next.html"
},
+ {
+ "src": "/showcase/?",
+ "dest": "/app-next.html"
+ },
{
"src": "/dashboard-classic/?",
"dest": "/dashboard-classic/index.html"
diff --git a/vite.config.js b/vite.config.js
index 71239d617..0eb0983bd 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -199,7 +199,7 @@ const appConfig = {
// large bundles (Three.js, ethers) without affecting the output.
reportCompressedSize: false,
rollupOptions: {
- external: ['/studio/launch-panel.js', /^@pump-fun\/agent-payments-sdk(\/.*)?$/],
+ external: ['/studio/launch-panel.js', '/studio/fees-panel.js', './fees-panel.js', /^@pump-fun\/agent-payments-sdk(\/.*)?$/],
output: {
manualChunks(id) {
if (id.includes('node_modules/three/')) {
@@ -470,6 +470,8 @@ const appConfig = {
'/widget/': resolve(root, 'pages/widget.html'),
'/login': resolve(root, 'public/login.html'),
'/deploy': resolve(root, 'pages/app.html'),
+ '/showcase': resolve(root, 'pages/app.html'),
+ '/showcase/': resolve(root, 'pages/app.html'),
'/agents': resolve(root, 'public/agents/index.html'),
'/agents/': resolve(root, 'public/agents/index.html'),
'/start': resolve(root, 'pages/start.html'),