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: pump fee-sharing GitHub resolve, social-fee PDA, metadata_uri threading + avatar/studio/tokens polish

nirholasd84003547412
diff --git a/api/pump/[action].js b/api/pump/[action].js
index 3afed3a29..0d82273ad 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -37,6 +37,13 @@
// update-fee-shares-prep -> handleUpdateFeeSharesPrep (step 2)
// fee-info -> handleFeeInfo (read-only: claimable creator
// fees, graduation, sharing-config shareholders)
+// resolve-github-shareholder -> handleResolveGithubShareholder (read-only:
+// GitHub @login/id -> the recipient's linked
+// Solana payout wallet, or a pump.fun social-fee
+// escrow PDA when they haven't joined yet)
+// create-social-fee-pda-prep -> handleCreateSocialFeePdaPrep (user-signed:
+// initialise the pump.fun social-fee escrow that
+// a fee-share update then routes a slice into)
// collect-creator-fee-agent -> handleCollectCreatorFeeAgent (server-signs
// with the agent custodial wallet)
// distribute-creator-fees-agent -> handleDistributeCreatorFeesAgent (server-signs)
@@ -132,6 +139,10 @@ const wrapped = wrap(async (req, res) => {
case 'create-fee-sharing-prep': return handleCreateFeeSharingPrep(req, res);
case 'update-fee-shares-prep': return handleUpdateFeeSharesPrep(req, res);
case 'fee-info': return handleFeeInfo(req, res);
+ case 'resolve-github-shareholder': return handleResolveGithubShareholder(req, res);
+ case 'create-social-fee-pda-prep': return handleCreateSocialFeePdaPrep(req, res);
+ case 'github-resolve': return handleGithubResolve(req, res);
+ case 'social-fee-claim-status': return handleSocialFeeClaimStatus(req, res);
case 'collect-creator-fee-agent': return handleCollectCreatorFeeAgent(req, res);
case 'distribute-creator-fees-agent': return handleDistributeCreatorFeesAgent(req, res);
case 'fee-sharing-agent': return handleFeeSharingAgent(req, res);
@@ -1037,7 +1048,7 @@ async function handleLaunchConfirm(req, res) {
const body = parse(launchConfirmSchema, await readJson(req));
const [pending] = await sql`
- select id, payload from agent_registrations_pending
+ select id, payload, metadata_uri from agent_registrations_pending
where user_id=${user.id} and payload->>'prep_id'=${body.prep_id}
and expires_at > now()
order by created_at desc limit 1
@@ -1045,6 +1056,10 @@ async function handleLaunchConfirm(req, res) {
if (!pending) return error(res, 404, 'not_found', 'prep not found or expired');
const p = pending.payload;
if (p.kind !== 'pump_launch') return error(res, 400, 'wrong_kind', 'prep is not a pump launch');
+ // metadata_uri lives as a top-level column on the pending row (= launch-prep
+ // `uri`), not inside the payload JSON. Thread it through so client-signed
+ // launches persist their metadata like the launch-agent path does.
+ const metadataUri = pending.metadata_uri || p.metadata_uri || null;
let tx;
try {
@@ -1070,10 +1085,10 @@ async function handleLaunchConfirm(req, res) {
const agentAuthority = p.creator_address || p.wallet_address;
const [row] = await sql`
insert into pump_agent_mints
- (agent_id, user_id, network, mint, name, symbol, agent_authority, buyback_bps)
+ (agent_id, user_id, network, mint, name, symbol, metadata_uri, agent_authority, buyback_bps)
values
(${p.agent_id}, ${user.id}, ${p.network}, ${p.mint},
- ${p.name}, ${p.symbol}, ${agentAuthority}, ${p.buyback_bps})
+ ${p.name}, ${p.symbol}, ${metadataUri}, ${agentAuthority}, ${p.buyback_bps})
returning id, mint, network, buyback_bps, created_at
`;
@@ -2892,7 +2907,9 @@ const updateFeeSharesSchema = z.object({
// sharing_config. Right after create-fee-sharing-prep this is `[creator]`
// at 10_000 bps; after a prior update it's whatever was last set. The SDK
// uses these to derive the existing PDA accounts that must be passed in.
- current_shareholders: z.array(z.string().min(32).max(44)).min(1).max(10),
+ // Optional — when omitted the handler decodes the current set from the
+ // on-chain sharing_config so the client never has to track it.
+ current_shareholders: z.array(z.string().min(32).max(44)).min(1).max(10).optional(),
new_shareholders: z
.array(
z.object({
@@ -2927,11 +2944,9 @@ async function handleUpdateFeeSharesPrep(req, res) {
const payerPk = solanaPubkey(body.wallet_address);
if (!mintPk || !payerPk) return error(res, 400, 'validation_error', 'invalid pubkeys');
- const currentShareholders = body.current_shareholders.map((s) => {
- const pk = solanaPubkey(s);
- if (!pk) throw Object.assign(new Error(`invalid current shareholder ${s}`), { status: 400, code: 'validation_error' });
- return pk;
- });
+ const guard = await assertCoinNotOwnedByOther({ userId: user.id, mint: body.mint, network: body.network, res });
+ if (guard.blocked) return;
+
const newShareholders = body.new_shareholders.map((s) => {
const addr = solanaPubkey(s.address);
if (!addr) throw Object.assign(new Error(`invalid shareholder ${s.address}`), { status: 400, code: 'validation_error' });
@@ -2939,7 +2954,28 @@ async function handleUpdateFeeSharesPrep(req, res) {
});
try {
- const { sdk } = await getPumpSdk({ network: body.network });
+ const { sdk, connection } = await getPumpSdk({ network: body.network });
+
+ // Current shareholders: trust the client list when supplied, otherwise
+ // decode them from the on-chain sharing_config so callers don't have to
+ // track on-chain state themselves.
+ let currentShareholders;
+ if (body.current_shareholders?.length) {
+ currentShareholders = body.current_shareholders.map((s) => {
+ const pk = solanaPubkey(s);
+ if (!pk) throw Object.assign(new Error(`invalid current shareholder ${s}`), { status: 400, code: 'validation_error' });
+ return pk;
+ });
+ } else {
+ const { feeSharingConfigPda } = await import('@pump-fun/pump-sdk');
+ const cfgInfo = await connection.getAccountInfo(feeSharingConfigPda(mintPk));
+ if (!cfgInfo) {
+ return error(res, 409, 'no_sharing_config', 'no fee-sharing config for this coin — create one first via create-fee-sharing-prep');
+ }
+ const cfg = sdk.decodeSharingConfig(cfgInfo);
+ currentShareholders = cfg.shareholders.map((s) => new PublicKey(s.address));
+ }
+
const ix = await sdk.updateFeeShares({
authority: payerPk,
mint: mintPk,
@@ -2990,6 +3026,9 @@ async function handleCreateFeeSharingPrep(req, res) {
const payerPk = solanaPubkey(body.wallet_address);
if (!mintPk || !creatorPk || !payerPk) return error(res, 400, 'validation_error', 'invalid pubkeys');
+ const guard = await assertCoinNotOwnedByOther({ userId: user.id, mint: body.mint, network: body.network, res });
+ if (guard.blocked) return;
+
try {
const { canonicalPumpPoolPda } = await import('@pump-fun/pump-swap-sdk');
const { bondingCurvePda } = await import('@pump-fun/pump-sdk');
@@ -3024,6 +3063,184 @@ 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');
}
}
+
+// Soft ownership guard for connected-wallet fee/delegation actions. If this mint
+// was launched through three.ws (a pump_agent_mints row exists), it must belong
+// to the session user — this stops one account building fee txs against another
+// account's coin. Coins launched outside three.ws have no row and are allowed
+// (the on-chain sharing-config admin signature is the real gate either way).
+async function assertCoinNotOwnedByOther({ userId, mint, network, res }) {
+ const [row] = await sql`
+ select id, user_id from pump_agent_mints
+ where mint=${mint} and network=${network}
+ limit 1
+ `;
+ if (row && row.user_id !== userId) {
+ error(res, 403, 'forbidden', 'this coin belongs to another account');
+ return { blocked: true };
+ }
+ return { blocked: false, row: row || null };
+}
+
+// pump.fun social platform ids (matches the SDK's Platform enum):
+// Pump = 0, X = 1, GitHub = 2
+const SOCIAL_PLATFORM_ID = { pump: 0, x: 1, github: 2 };
+
+// ── resolve-github-shareholder ─────────────────────────────────────────────
+// Turns a GitHub identity into a concrete fee-share recipient address so the
+// delegation UI never has to know the mapping. If the GitHub user is on
+// three.ws (linked via the existing GitHub OAuth) and has a linked Solana
+// wallet, we return that wallet — a fully-claimable shareholder paid by the
+// permissionless distribute crank. Otherwise we return the pump.fun social-fee
+// escrow PDA for their numeric id; fees can be routed into it, but the final
+// claim is brokered by pump.fun's own app (we don't hold the social-claim
+// authority), so we flag claimable_now:false and explain.
+
+const resolveGithubShareholderSchema = z
+ .object({
+ github_username: z.string().trim().min(1).max(40).optional(),
+ github_user_id: z.string().trim().regex(/^\d{1,20}$/).optional(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ })
+ .refine((b) => b.github_username || b.github_user_id, {
+ message: 'github_username or github_user_id required',
+ });
+
+async function handleResolveGithubShareholder(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(resolveGithubShareholderSchema, await readJson(req));
+ const login = body.github_username ? body.github_username.replace(/^@/, '') : null;
+
+ // Look up the GitHub identity in social_connections (written by the existing
+ // /api/auth/github OAuth flow — provider_uid is the numeric GitHub user id).
+ const [conn] = await sql`
+ select user_id, provider_uid, username
+ from social_connections
+ where provider='github' and disconnected_at is null
+ and (${login}::text is not null and lower(username)=lower(${login})
+ or ${body.github_user_id}::text is not null and provider_uid=${body.github_user_id})
+ order by connected_at desc
+ limit 1
+ `;
+
+ const { socialFeePda } = await import('@pump-fun/pump-sdk');
+ const platform = SOCIAL_PLATFORM_ID.github;
+
+ if (conn) {
+ // Prefer the recipient's primary linked Solana wallet — fully claimable.
+ const [wallet] = await sql`
+ select address from user_wallets
+ where user_id=${conn.user_id} and chain_type='solana'
+ order by is_primary desc, created_at asc
+ limit 1
+ `;
+ if (wallet) {
+ return json(res, 200, {
+ mode: 'wallet',
+ address: wallet.address,
+ github_username: conn.username,
+ github_user_id: conn.provider_uid,
+ claimable_now: true,
+ note: 'Linked Solana payout wallet — pays out via the permissionless distribute crank.',
+ });
+ }
+ // On three.ws but no Solana wallet linked yet → escrow PDA, claim deferred.
+ return json(res, 200, {
+ mode: 'social_pda',
+ address: socialFeePda(String(conn.provider_uid), platform).toBase58(),
+ github_username: conn.username,
+ github_user_id: conn.provider_uid,
+ claimable_now: false,
+ note: 'This GitHub user has no Solana payout wallet linked yet. Fees accrue in a pump.fun social-fee escrow; ask them to link a Solana wallet on three.ws to claim directly.',
+ });
+ }
+
+ // Not on three.ws. We can only derive the escrow PDA from a numeric id —
+ // pump.fun keys social-fee PDAs by the numeric GitHub user id, not the login.
+ if (body.github_user_id) {
+ return json(res, 200, {
+ mode: 'social_pda',
+ address: socialFeePda(String(body.github_user_id), platform).toBase58(),
+ github_user_id: body.github_user_id,
+ claimable_now: false,
+ note: 'This GitHub user is not on three.ws. Fees accrue in a pump.fun social-fee escrow they can claim once they connect GitHub and link a Solana wallet.',
+ });
+ }
+ return json(res, 200, {
+ mode: 'unresolved',
+ github_username: login,
+ claimable_now: false,
+ note: 'No three.ws account found for that GitHub username. Provide the numeric GitHub user id to route into a pump.fun social-fee escrow, or ask them to sign in with GitHub and link a Solana wallet.',
+ });
+}
+
+// ── create-social-fee-pda-prep ─────────────────────────────────────────────
+// Initialises the pump.fun social-fee escrow PDA for a (social_user_id,
+// platform) pair so a subsequent update-fee-shares-prep can name it as a
+// shareholder address. Idempotent on-chain (no-op if it already exists). The
+// returned tx is signed by the connected wallet (the coin admin/payer).
+
+const createSocialFeePdaPrepSchema = z.object({
+ wallet_address: z.string().min(32).max(44), // payer / signer
+ social_user_id: z.string().trim().min(1).max(20), // numeric social id (SDK caps at 20 chars)
+ platform: z.enum(['github', 'x', 'pump']).default('github'),
+ mint: z.string().min(32).max(44).optional(), // when set, enforces coin ownership
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+async function handleCreateSocialFeePdaPrep(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(createSocialFeePdaPrepSchema, await readJson(req));
+ const payerPk = solanaPubkey(body.wallet_address);
+ if (!payerPk) return error(res, 400, 'validation_error', 'invalid wallet_address');
+
+ if (body.mint) {
+ const guard = await assertCoinNotOwnedByOther({ userId: user.id, mint: body.mint, network: body.network, res });
+ if (guard.blocked) return;
+ }
+
+ const platform = SOCIAL_PLATFORM_ID[body.platform];
+
+ try {
+ const { sdk } = await getPumpSdk({ network: body.network });
+ const { socialFeePda } = await import('@pump-fun/pump-sdk');
+ const ix = await sdk.createSocialFeePda({
+ payer: payerPk,
+ userId: body.social_user_id,
+ platform,
+ });
+ const tx_base64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: payerPk,
+ instructions: Array.isArray(ix) ? ix : [ix],
+ });
+ return json(res, 201, {
+ social_fee_pda: socialFeePda(body.social_user_id, platform).toBase58(),
+ platform: body.platform,
+ social_user_id: body.social_user_id,
+ network: body.network,
+ tx_base64,
+ });
+ } catch (e) {
+ return error(res, e.status || 502, e.code || 'pump_sdk_error', e.message || 'failed to build create-social-fee-pda 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
@@ -3418,4 +3635,127 @@ async function handleFeeSharingAgent(req, res) {
}
}
+// ── github-resolve ─────────────────────────────────────────────────────────
+// Validate a GitHub handle and return its public profile + numeric id. The
+// numeric id is what pump.fun's social-fee program keys on (platform=2), and
+// the avatar/profile let the launch UI confirm "rewards → @handle" before the
+// user delegates fees. Read-only; best-effort (GitHub rate-limits unauthed IPs
+// at 60/hr — set GITHUB_TOKEN to raise that).
+
+async function handleGithubResolve(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 handle = (url.searchParams.get('handle') || '').replace(/^@/, '').trim();
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/.test(handle)) {
+ return error(res, 400, 'validation_error', 'invalid github handle');
+ }
+
+ try {
+ const headers = { 'user-agent': 'three.ws', accept: 'application/vnd.github+json' };
+ if (process.env.GITHUB_TOKEN) headers.authorization = `Bearer ${process.env.GITHUB_TOKEN}`;
+ const gh = await fetch(`https://api.github.com/users/${encodeURIComponent(handle)}`, { headers });
+ if (gh.status === 404) return error(res, 404, 'github_user_not_found', `@${handle} not found on GitHub`);
+ if (gh.status === 403) return error(res, 429, 'github_rate_limited', 'GitHub rate limit — try again shortly');
+ if (!gh.ok) return error(res, 502, 'github_error', `github responded ${gh.status}`);
+ const j = await gh.json();
+ if (!j?.id) return error(res, 502, 'github_error', 'github id missing');
+ return json(res, 200, {
+ ok: true,
+ login: j.login,
+ id: String(j.id), // social-fee user_id (≤20 chars, fits u64)
+ name: j.name || null,
+ avatar_url: j.avatar_url || null,
+ html_url: j.html_url || `https://github.com/${j.login}`,
+ type: j.type || 'User',
+ });
+ } catch (e) {
+ return error(res, 502, 'github_error', e.message || 'github lookup failed');
+ }
+}
+
+// Read pump.fun's global FeeProgramGlobal account and decode the single field we
+// need — `social_claim_authority` — the only signer allowed to release social
+// (GitHub/X) fee claims. We surface it so the UI can be honest that claiming
+// native social rewards is gated by pump.fun, not self-custodial. No exported
+// decoder exists for FeeProgramGlobal, so we slice the known layout:
+// [8 disc][1 bump][32 authority][1 disable_flags][32 social_claim_authority]…
+async function readSocialClaimAuthority(connection) {
+ try {
+ const { FEE_PROGRAM_GLOBAL_PDA } = await import('@pump-fun/pump-sdk');
+ const info = await connection.getAccountInfo(FEE_PROGRAM_GLOBAL_PDA);
+ if (!info?.data || info.data.length < 8 + 1 + 32 + 1 + 32) return null;
+ const off = 8 + 1 + 32 + 1;
+ return new PublicKey(info.data.subarray(off, off + 32)).toBase58();
+ } catch { return null; }
+}
+
+// ── social-fee-claim-status ────────────────────────────────────────────────
+// Read-only view of a GitHub/X identity's pump.fun social-fee PDA: how much has
+// accrued and been claimed, and the gated deep-link to claim it. We CANNOT build
+// a claim tx ourselves — claim_social_fee_pda requires pump.fun's global
+// `social_claim_authority` to co-sign — so this endpoint is read + deep-link.
+// Self-custodial "reward" delegation is the fee-sharing split (see
+// fee-sharing-agent / update-fee-shares-prep), which IS claimable directly.
+
+async function handleSocialFeeClaimStatus(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 userId = (url.searchParams.get('user_id') || '').trim();
+ const platform = Number(url.searchParams.get('platform') ?? '2'); // 0=pump 1=X 2=GitHub
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ if (!/^\d{1,20}$/.test(userId)) return error(res, 400, 'validation_error', 'numeric user_id required');
+ if (![0, 1, 2].includes(platform)) return error(res, 400, 'validation_error', 'platform must be 0,1,2');
+
+ try {
+ const connection = getConnection({ network });
+ const { socialFeePda, PUMP_SDK } = await import('@pump-fun/pump-sdk');
+ const pda = socialFeePda(userId, platform);
+ const info = await connection.getAccountInfo(pda);
+
+ let decoded = null;
+ let claimableLamports = 0n;
+ if (info) {
+ claimableLamports = BigInt(info.lamports) - MIN_RENT_EXEMPTION_LAMPORTS;
+ if (claimableLamports < 0n) claimableLamports = 0n;
+ try {
+ const d = PUMP_SDK.decodeSocialFeePda(info);
+ decoded = {
+ user_id: d.userId,
+ platform: Number(d.platform),
+ total_claimed_lamports: d.totalClaimed?.toString?.() ?? '0',
+ last_claimed: d.lastClaimed?.toString?.() ?? '0',
+ };
+ } catch { /* layout drift — still return the balance */ }
+ }
+
+ const social_claim_authority = await readSocialClaimAuthority(connection);
+ return json(res, 200, {
+ user_id: userId,
+ platform,
+ network,
+ social_fee_pda: pda.toBase58(),
+ exists: !!info,
+ claimable_lamports: claimableLamports.toString(),
+ claimable_sol: Number(claimableLamports) / LAMPORTS_PER_SOL,
+ decoded,
+ // Claiming is gated: only pump.fun's social_claim_authority can sign.
+ gated: true,
+ social_claim_authority,
+ claim_url: 'https://pump.fun/profile',
+ });
+ } catch (e) {
+ return error(res, e.status || 502, e.code || 'pump_sdk_error', e.message || 'failed to read social fee status');
+ }
+}
+
function _sse(res, event, data) { res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); }
diff --git a/public/studio/fees-panel.js b/public/studio/fees-panel.js
index 5ae1b8661..f51484fd5 100644
--- a/public/studio/fees-panel.js
+++ b/public/studio/fees-panel.js
@@ -470,16 +470,49 @@ export function mountFeesPanel(container, opts = {}) {
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 },
+ gh: { login: c.login, avatar: c.avatar_url, url: c.html_url, resolving: true },
}));
s.editing = true;
+ render();
+ // Auto-resolve each contributor to their three.ws-linked Solana payout
+ // wallet so the reward split pays real people without manual address
+ // entry. Best-effort and in parallel — anyone we can't resolve is left
+ // for manual entry (or removal).
+ resolveContributorWallets();
} catch (e) {
s.githubError = friendlyError(e.message || String(e));
+ s.githubBusy = false;
+ render();
}
s.githubBusy = false;
render();
}
+ // Fill in each GitHub contributor's linked Solana wallet via the
+ // resolve-github-shareholder bridge. Only auto-fills a real linked wallet
+ // ('wallet' mode) so the split always pays a claimable address; contributors
+ // with no three.ws wallet are flagged so the creator can add one or drop them.
+ async function resolveContributorWallets() {
+ await Promise.all(s.rows.map(async (row) => {
+ if (!row.gh?.login || row.address) { if (row.gh) row.gh.resolving = false; return; }
+ try {
+ const r = await fetch('/api/pump/resolve-github-shareholder', {
+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ github_username: row.gh.login, network }),
+ });
+ const d = await r.json();
+ if (r.ok && d.mode === 'wallet' && d.address) {
+ row.address = d.address;
+ row.gh.linked = true;
+ } else {
+ row.gh.unlinked = true;
+ }
+ } catch { row.gh.unlinked = true; }
+ row.gh.resolving = false;
+ }));
+ if (_alive) render();
+ }
+
// ── Delegation editor row helpers ─────────────────────────────────────────────
function startEditing(seed) {
@@ -615,7 +648,12 @@ export function mountFeesPanel(container, opts = {}) {
<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>` : ''}
+ ${r.gh ? `<span class="fp-share-gh"><img src="${esc(r.gh.avatar)}" alt="" />@${esc(r.gh.login)}${
+ r.gh.resolving ? ` · <span style="color:rgba(255,255,255,.4)">resolving…</span>`
+ : r.gh.linked ? ` · <span style="color:#a4f0bc">linked ✓</span>`
+ : r.gh.unlinked ? ` · <span style="color:rgba(246,200,114,.9)" title="No three.ws-linked Solana wallet — paste theirs, or ask them to connect GitHub + link a wallet on three.ws">add wallet</span>`
+ : ''
+ }</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>
diff --git a/src/avatar-page.js b/src/avatar-page.js
index cb8f8af36..7149c20f8 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -276,6 +276,10 @@ function renderShell(glbUrl) {
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>
Launch Pump.fun
</button>
+ <button class="av-owner-btn" id="av-fees-rewards" type="button" hidden>
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M14.5 9.3a2.6 2.6 0 0 0-4.9.9c0 2.7 4.9 1.4 4.9 4.1a2.6 2.6 0 0 1-4.9.9M12 6.5v11"/></svg>
+ Fees &amp; rewards
+ </button>
</div>
` : ''}
<nav class="av-tabs" role="tablist">
@@ -615,6 +619,28 @@ function bindShareButtons() {
function bindOwnerActions() {
$('av-deploy-onchain')?.addEventListener('click', openDeployOnchain);
$('av-launch-pumpfun')?.addEventListener('click', openLaunchPumpFun);
+ $('av-fees-rewards')?.addEventListener('click', openFeesPanel);
+ checkAvatarCoin();
+}
+
+// Resolve whether this avatar already has a launched coin. If so, reveal the
+// "Fees & rewards" control so the owner gets full claim/split/delegation
+// control. Also honors ?launch=1 (deep-link from the avatar-studio save flow)
+// by opening the launch modal immediately.
+let avatarCoin = null;
+async function checkAvatarCoin() {
+ if (new URLSearchParams(location.search).get('launch') === '1') openLaunchPumpFun();
+ const id = avatar?.id || avatarId;
+ if (!id) return;
+ try {
+ const r = await fetch(`/api/pump/by-agent?avatar_id=${encodeURIComponent(id)}`, { credentials: 'include' });
+ if (!r.ok) return;
+ const { data } = await r.json();
+ if (!data?.mint) return;
+ avatarCoin = data;
+ const feesBtn = $('av-fees-rewards');
+ if (feesBtn) feesBtn.hidden = false;
+ } catch { /* best-effort — no coin means no button, which is correct */ }
}
async function openDeployOnchain() {
@@ -643,43 +669,49 @@ async function openDeployOnchain() {
}
}
+// Shared modal chrome for the pump.fun launch + fees panels. Returns the inner
+// mount node plus a close() handle; closes on ×, backdrop click, and Escape.
+function openPumpModal(title) {
+ const backdrop = document.createElement('div');
+ backdrop.className = 'av-pump-backdrop';
+ const modal = document.createElement('div');
+ modal.className = 'av-pump-modal';
+ const header = document.createElement('div');
+ header.className = 'av-pump-header';
+ header.innerHTML = `
+ <span class="av-pump-title">${esc(title)}</span>
+ <button class="av-pump-close" type="button" aria-label="Close">×</button>
+ `;
+ const inner = document.createElement('div');
+ inner.className = 'av-pump-inner';
+ modal.appendChild(header);
+ modal.appendChild(inner);
+ backdrop.appendChild(modal);
+ document.body.appendChild(backdrop);
+ const onEsc = (e) => { if (e.key === 'Escape') close(); };
+ const close = () => { backdrop.remove(); document.removeEventListener('keydown', onEsc); };
+ header.querySelector('.av-pump-close').addEventListener('click', close);
+ backdrop.addEventListener('click', (e) => { if (e.target === backdrop) close(); });
+ document.addEventListener('keydown', onEsc);
+ return { inner, close };
+}
+
+async function fetchCurrentUser() {
+ try {
+ const r = await fetch('/api/auth/me', { credentials: 'include' });
+ if (r.ok) return (await r.json()).user || null;
+ } catch { /* best-effort */ }
+ return null;
+}
+
async function openLaunchPumpFun() {
const btn = $('av-launch-pumpfun');
- if (!btn || btn.disabled) return;
- btn.disabled = true;
+ if (btn?.disabled) return;
+ if (btn) btn.disabled = true;
try {
- let user = null;
- try {
- const r = await fetch('/api/auth/me', { credentials: 'include' });
- if (r.ok) user = (await r.json()).user || null;
- } catch { /* best-effort */ }
-
- const backdrop = document.createElement('div');
- backdrop.className = 'av-pump-backdrop';
-
- const modal = document.createElement('div');
- modal.className = 'av-pump-modal';
-
- const header = document.createElement('div');
- header.className = 'av-pump-header';
- header.innerHTML = `
- <span class="av-pump-title">Launch on Pump.fun</span>
- <button class="av-pump-close" type="button" aria-label="Close">×</button>
- `;
- const inner = document.createElement('div');
- inner.className = 'av-pump-inner';
-
- modal.appendChild(header);
- modal.appendChild(inner);
- backdrop.appendChild(modal);
- document.body.appendChild(backdrop);
-
- const closeModal = () => backdrop.remove();
- header.querySelector('.av-pump-close').addEventListener('click', closeModal);
- backdrop.addEventListener('click', (e) => { if (e.target === backdrop) closeModal(); });
-
- const launchPanelUrl = '/studio/launch-panel.js';
- const { mountLaunchPanel } = await import(/* @vite-ignore */ launchPanelUrl);
+ const user = await fetchCurrentUser();
+ const { inner } = openPumpModal('Launch on Pump.fun');
+ const { mountLaunchPanel } = await import(/* @vite-ignore */ '/studio/launch-panel.js');
mountLaunchPanel(inner, {
getAvatar: () => ({ ...avatar, id: avatar.id || avatarId }),
getUser: () => user,
@@ -688,7 +720,42 @@ async function openLaunchPumpFun() {
} catch (err) {
console.error('[avatar] launch pump.fun failed', err);
} finally {
- btn.disabled = false;
+ if (btn) btn.disabled = false;
+ }
+}
+
+// Full creator-fee control for the avatar's coin: claim, split/delegate to
+// contributors, distribute, and view recent claims. Mounts the shared fees
+// panel against the coin resolved from /api/pump/by-agent.
+async function openFeesPanel() {
+ const btn = $('av-fees-rewards');
+ if (btn?.disabled) return;
+ if (btn) btn.disabled = true;
+ try {
+ if (!avatarCoin?.mint) {
+ const id = avatar?.id || avatarId;
+ const r = await fetch(`/api/pump/by-agent?avatar_id=${encodeURIComponent(id)}`, { credentials: 'include' });
+ const { data } = r.ok ? await r.json() : { data: null };
+ avatarCoin = data;
+ }
+ if (!avatarCoin?.mint) { alert('No coin launched for this avatar yet — launch one first.'); return; }
+ const user = await fetchCurrentUser();
+ const { inner } = openPumpModal('Fees & rewards');
+ const { mountFeesPanel } = await import(/* @vite-ignore */ '/studio/fees-panel.js');
+ mountFeesPanel(inner, {
+ mint: avatarCoin.mint,
+ network: avatarCoin.network || 'mainnet',
+ creator: avatarCoin.agent_authority || null,
+ avatarId: avatar.id || avatarId,
+ agentId: avatar.agent_id || null,
+ symbol: avatarCoin.symbol || '',
+ name: avatarCoin.name || '',
+ getUser: () => user,
+ });
+ } catch (err) {
+ console.error('[avatar] open fees panel failed', err);
+ } finally {
+ if (btn) btn.disabled = false;
}
}
diff --git a/src/avatar-studio.js b/src/avatar-studio.js
index 227d3cd0a..ab4e32624 100644
--- a/src/avatar-studio.js
+++ b/src/avatar-studio.js
@@ -1214,10 +1214,11 @@ async function saveAvatar() {
await new Promise((r) => setTimeout(r, 700));
hideSaveOverlay();
- // Show a save-success toast briefly before redirecting
+ // Show a save-success toast with next-step CTAs (launch a coin / view).
+ // Give the user time to choose; fall back to the avatar page if they don't.
showSaveToast(avatar.id);
- await new Promise((r) => setTimeout(r, 1400));
+ await new Promise((r) => setTimeout(r, 5000));
window.location.href = `/avatars/${encodeURIComponent(avatar.id)}`;
} catch (err) {
hideSaveOverlay();
@@ -1268,10 +1269,14 @@ async function uploadEditedAvatar(avatarId, name, glbBlob, onProgress) {
function showSaveToast(avatarId) {
const el = document.createElement('div');
el.className = 'as-toast';
+ // Saved avatars are real, on-chain-launchable assets — surface the coin
+ // path as a first-class next step, not just "view". The ?launch=1 deep-link
+ // auto-opens the launch panel on the avatar page.
el.innerHTML = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="as-toast-icon" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>
- <span>Saved! Opening your avatar…</span>
- <a href="/avatars/${esc(avatarId)}" class="as-toast-link">View now</a>
+ <span>Saved to your library.</span>
+ <a href="/avatars/${esc(avatarId)}?launch=1" class="as-toast-link" style="font-weight:600">🪙 Launch a coin →</a>
+ <a href="/avatars/${esc(avatarId)}" class="as-toast-link">View avatar</a>
`;
document.body.appendChild(el);
// Animate in
diff --git a/src/dashboard-next/pages/tokens.js b/src/dashboard-next/pages/tokens.js
index c13c17cda..b3d835e29 100644
--- a/src/dashboard-next/pages/tokens.js
+++ b/src/dashboard-next/pages/tokens.js
@@ -83,9 +83,10 @@ function toast(msg) {
const fromDash = dashTokens.find((t) => t.mint === mint || t.address === mint);
return {
agent: a,
- mint,
+ mint: mint || byAgent?.data?.mint || null,
token: byAgent?.token || fromDash || null,
stats: byAgent?.stats || fromDash?.stats || null,
+ coin: byAgent?.data || null, // { agent_authority, network, symbol, name, sharing_config }
};
}),
);
@@ -165,7 +166,7 @@ function renderSummaryStrip(tokenData) {
// ── Token card ─────────────────────────────────────────────────────────────
-function renderTokenCard({ agent, mint, token, stats }) {
+function renderTokenCard({ agent, mint, token, stats, coin }) {
const panel = document.createElement('div');
panel.className = 'dn-panel';
@@ -226,6 +227,7 @@ function renderTokenCard({ agent, mint, token, stats }) {
${mint ? `
<div style="display:flex;gap:8px;flex-wrap:wrap">
+ <button class="dn-btn primary" data-action="fees" style="font-size:12.5px">Fees &amp; rewards</button>
<a class="dn-btn" href="/pump-3d-agent?mint=${encodeURIComponent(mint)}" target="_blank" rel="noopener" style="font-size:12.5px">3D Agent view ↗</a>
<a class="dn-btn" href="https://solscan.io/token/${encodeURIComponent(mint)}" target="_blank" rel="noopener" style="font-size:12.5px">Solscan ↗</a>
${mint ? `<button class="dn-btn" data-action="copy-mint" data-mint="${esc(mint)}" style="font-size:12.5px">Copy CA</button>` : ''}
@@ -244,9 +246,63 @@ function renderTokenCard({ agent, mint, token, stats }) {
});
});
+ panel.querySelector('[data-action="fees"]')?.addEventListener('click', () => {
+ openFeesModal({
+ mint,
+ network: coin?.network || 'mainnet',
+ creator: coin?.agent_authority || null,
+ agentId: agent.id,
+ symbol: ticker,
+ name: coin?.name || agent.name || '',
+ });
+ });
+
return panel;
}
+// ── Fees & rewards modal ────────────────────────────────────────────────────
+// Mounts the shared studio fees panel against a token so creators get full
+// claim / split / delegate / distribute control without leaving the dashboard.
+
+let _meCache;
+async function getMe() {
+ if (_meCache !== undefined) return _meCache;
+ try { _meCache = (await get('/api/auth/me'))?.user || null; }
+ catch { _meCache = null; }
+ return _meCache;
+}
+
+async function openFeesModal({ mint, network, creator, agentId, symbol, name }) {
+ const backdrop = document.createElement('div');
+ backdrop.style.cssText = 'position:fixed;inset:0;z-index:1000;background:rgba(0,0,0,.62);backdrop-filter:blur(4px);display:flex;align-items:flex-start;justify-content:center;padding:5vh 16px;overflow:auto';
+ const panel = document.createElement('div');
+ panel.style.cssText = 'background:var(--nxt-bg,#0d0d12);border:1px solid var(--nxt-stroke,rgba(255,255,255,.1));border-radius:14px;max-width:560px;width:100%;box-shadow:0 24px 80px rgba(0,0,0,.5)';
+ const head = document.createElement('div');
+ head.style.cssText = 'display:flex;align-items:center;justify-content:space-between;padding:14px 18px;border-bottom:1px solid var(--nxt-stroke,rgba(255,255,255,.08))';
+ head.innerHTML = `<strong style="font-size:15px">Fees &amp; rewards · ${esc(symbol || 'Coin')}</strong><button type="button" aria-label="Close" style="background:none;border:none;color:inherit;font-size:22px;line-height:1;cursor:pointer">×</button>`;
+ const inner = document.createElement('div');
+ inner.style.cssText = 'padding:8px';
+ panel.append(head, inner);
+ backdrop.appendChild(panel);
+ document.body.appendChild(backdrop);
+ const onEsc = (e) => { if (e.key === 'Escape') close(); };
+ const close = () => { backdrop.remove(); document.removeEventListener('keydown', onEsc); };
+ head.querySelector('button').addEventListener('click', close);
+ backdrop.addEventListener('click', (e) => { if (e.target === backdrop) close(); });
+ document.addEventListener('keydown', onEsc);
+ try {
+ const user = await getMe();
+ const { mountFeesPanel } = await import(/* @vite-ignore */ '/studio/fees-panel.js');
+ mountFeesPanel(inner, {
+ mint, network: network || 'mainnet', creator: creator || null,
+ agentId: agentId || null, symbol: symbol || '', name: name || '',
+ getUser: () => user,
+ });
+ } catch (err) {
+ inner.innerHTML = `<div style="padding:24px;color:var(--nxt-ink-fade,#999)">Couldn't load the fees panel: ${esc(err.message || 'error')}</div>`;
+ }
+}
+
function statCell(label, value) {
return `
<div style="padding:10px;background:rgba(255,255,255,0.02);border-radius:8px;border:1px solid var(--nxt-stroke)">