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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(copy): add the alpha-drip leader panel, the copier seat, and its documentation
nirholasd5fe4648ccdc
diff --git a/api/copy/alpha-drip.js b/api/copy/alpha-drip.jsindex 49d43f1e4..95048651c 100644--- a/api/copy/alpha-drip.js+++ b/api/copy/alpha-drip.js@@ -91,7 +91,39 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (await rateLimited(req, res, limits.api, clientIp(req))) return;- const leaderFromQuery = String(req.query?.leader_agent_id || '').trim();+ const params = new URL(req.url, 'http://x').searchParams;+ const leaderFromQuery = String(params.get('leader_agent_id') || '').trim();++ // ?mine=1 — every agent the caller owns that someone is actually copying,+ // with its current ladder. This is what the leader's editor lists, and it is+ // one query rather than one request per agent.+ if (req.method === 'GET' && params.get('mine') === '1') {+ const auth = await requireUser(req, res);+ if (!auth) return;+ const rows = await sql`+ select a.id, a.name,+ count(s.id) filter (where s.status = 'active') as copiers,+ d.enabled, d.schedule, d.public_delay_sec, d.disclosure, d.capacity_note, d.updated_at+ from agent_identities a+ join copy_subscriptions s on s.leader_agent_id = a.id and s.status = 'active'+ left join copy_alpha_drip d on d.leader_agent_id = a.id+ where a.user_id = ${auth.userId} and a.deleted_at is null+ group by a.id, a.name, d.enabled, d.schedule, d.public_delay_sec, d.disclosure, d.capacity_note, d.updated_at+ order by copiers desc, a.name asc+ `;+ const leaders = rows.map((row) => {+ const norm = row.enabled == null ? { ok: false } : normalizeDripConfig(row);+ const config = norm.ok ? norm.value : emptyDripConfig();+ return {+ leader_agent_id: row.id,+ leader_name: row.name,+ copiers: Number(row.copiers) || 0,+ updated_at: row.updated_at || null,+ drip: present(config),+ };+ });+ return json(res, 200, { leaders });+ }if (req.method === 'GET') {if (!isUuid(leaderFromQuery)) return error(res, 400, 'invalid_leader', 'leader_agent_id must be an agent UUID');diff --git a/docs/alpha-drip.md b/docs/alpha-drip.mdnew file mode 100644index 000000000..934c3dd4e--- /dev/null+++ b/docs/alpha-drip.md@@ -0,0 +1,195 @@+# Alpha-drip: tiered release of a leader's signal++A leader's edge decays in seconds. By the time a call has been forwarded to a+thousand followers, the fill the thousandth one gets is not the fill the leader+got. Alpha-drip is how a leader on three.ws prices that: **$THREE holders in+higher tiers are shown the copy intent first, everyone else after a delay the+leader sets.**++It is off by default. A leader who never touches it releases every signal to+every copier at the same moment, which is exactly what [copy+trading](./copy-trading.md) did before this existed.++> **A drip delays the reveal, never the record.** The intent row is written in+> full the moment the leader trades, and the trade lands in the leader's public+> track record either way. There is no setting here that hides a trade, and the+> API has no field that could express one. What a ladder controls is when a+> given copier is shown the coin and the size.++Related reading: [copy trading](./copy-trading.md) for the engine the ladder sits+on, [the $THREE token page](https://three.ws/three-token) for the tier+thresholds, and [trader passport](./trader-passport.md) for the public record a+drip cannot touch.++---++## What a copier sees++A copier whose seat has not been reached yet gets a locked row in+[/dashboard/copy](https://three.ws/dashboard/copy): the leader's name, the fact+that they fired, their own tier, and a countdown. The coin, the size, the+leader's transaction, and the safety snapshot are all withheld until the+countdown reaches zero, at which point the row unlocks in place and becomes an+ordinary intent with the full act window.++Acting early is not possible, and not merely unrendered: `POST+/api/copy/executions` refuses an unreleased intent with `409 not_released` and+returns the release time, and the guard is in the same SQL statement as the+status change so it cannot be raced.++The seat is shown **before** anyone subscribes, on the copy panel of the+leader's trader page, along with the ladder and the leader's disclosure. A delay+discovered from an empty inbox is the version of this feature that destroys+trust, so the number is on the page where the decision is made.++---++## What a leader sets++On [/dashboard/copy](https://three.ws/dashboard/copy), under **Your signal+release**, every agent the leader owns that somebody is actually copying gets a+ladder editor:++| Field | What it does |+| --- | --- |+| **Delay (s)** per tier | How long a copier in that $THREE tier waits before the intent is revealed. A blank tier inherits the next tier down. |+| **Max copy (◎)** per tier | Caps the size of a copy from that tier, so an early tier does not exhaust the leader's capacity before later tiers get a fill. |+| **Everyone else** | The delay for copiers holding no $THREE. Always the longest wait on the ladder. |+| **Disclosure** | The leader's own sentence to subscribers. The standing platform sentence is appended to it and cannot be removed. |+| **Capacity note** | Why the size caps are set the way they are. |++Two rules are enforced by the server (`api/_lib/alpha-drip.js`) and mirrored in+the form so a leader is told before they save rather than after:++1. **A higher tier can never wait longer than a lower one.** Paying more can+ only ever help. The public delay is checked against the paid tiers too.+2. **No delay may exceed 900 seconds** (15 minutes), for any tier.++**Suggest a ladder** asks the LLM chain for a draft tuned to how fast this+leader's edge actually decays. The draft is validated through the same+normalizer as a hand-written ladder, so a model can never talk a ladder past a+rule, and nothing is live until the leader saves it.++### The fairness warning++The half-life is measured, not assumed: it is the median hold time of the+leader's own profitable closed positions+(`api/_lib/alpha-drip-stats.js`), over their last 200, and it is null below five+such closes rather than a guess from a thin sample.++When the slowest tier waits longer than that half-life, saving the ladder+returns a warning that says so and recommends equal release. The slowest tier is+otherwise being sold a signal that is already spent, and that is worth saying+out loud rather than shipping quietly.++---++## API++### `GET /api/copy/alpha-drip?leader_agent_id=<uuid>`++Public. Returns the leader's ladder, the summary line, and the standing+disclosure. A signed-in caller also gets a `you` block with the seat their own+$THREE balance buys.++```bash+curl -s 'https://three.ws/api/copy/alpha-drip?leader_agent_id=00000000-0000-0000-0000-000000000000'+```++```json+{+ "leader_agent_id": "00000000-0000-0000-0000-000000000000",+ "leader_name": "Nine",+ "drip": {+ "enabled": true,+ "schedule": [+ { "tier": "gold", "delay_sec": 0, "max_copy_size_sol": 0.5 },+ { "tier": "bronze", "delay_sec": 20, "max_copy_size_sol": null }+ ],+ "public_delay_sec": 60,+ "summary": "Gold+ instant, Bronze+ after 20s, everyone else after 1m.",+ "disclosure": "Gold and above get my calls the moment I fire. This is the leader gating their own call as a subscription. It is not privileged access to anyone else's orderflow, and every trade still lands in the leader's public track record.",+ "longest_delay_sec": 60,+ "tiers": [{ "id": "member", "label": "Member", "min_usd": 0 }]+ },+ "you": {+ "tier": "silver",+ "tier_label": "Silver",+ "delay_sec": 20,+ "delay_label": "20s",+ "matched_tier": "bronze",+ "max_copy_size_sol": null+ }+}+```++### `GET /api/copy/alpha-drip?mine=1`++Signed in. Every agent the caller owns that has at least one active copier, with+its current ladder and copier count. This is what the leader's editor lists.++### `POST /api/copy/alpha-drip`++Owner only, CSRF-guarded. Saves the ladder.++```bash+curl -s https://three.ws/api/copy/alpha-drip \+ -H 'content-type: application/json' \+ -H "x-csrf-token: $CSRF" -b cookies.txt \+ -d '{+ "leader_agent_id": "00000000-0000-0000-0000-000000000000",+ "enabled": true,+ "schedule": [+ { "tier": "gold", "delay_sec": 0, "max_copy_size_sol": 0.5 },+ { "tier": "bronze", "delay_sec": 20 }+ ],+ "public_delay_sec": 60,+ "disclosure": "Gold and above get my calls the moment I fire."+ }'+```++Returns the saved ladder plus a `fairness` block. A ladder that breaks a release+rule is refused with `400 invalid_config` and the rule it broke.++Send `{ "action": "recommend", "leader_agent_id": "..." }` instead to get a+draft. The response carries `"applied": false`: a draft is never saved for you.++---++## How it runs++`api/cron/copy-fanout.js` is the only writer. Per tick:++1. **Release what is due.** Alerts held back by a drip go out the moment their+ reveal passes. The release cadence is the fanout cadence, so there is no+ second cron to keep in sync.+2. **Load the ladders** for every leader in the batch, in one query. A leader+ with the drip off costs nothing: no config row, no balance read, no branch.+3. **Price each copier** against their live $THREE balance, memoized per wallet+ for the tick, so a copier following three leaders is priced once.+4. **Apply the tier's size cap** after the copy engine has sized and gated the+ order, never before, so the copier's own caps still bind first. A cap that+ pushes an order under the copier's minimum is recorded as a+ `drip_capacity_cap` skip rather than filled as dust.+5. **Write the intent in full**, with `visible_at` set to the copier's reveal+ time and `expires_at` pushed out to match, so a dripped copier still gets a+ full 30-minute act window.++Telegram alerts follow the same seat: an instant seat is notified inline at+fanout, a delayed one is notified on release, so the alert cannot leak the coin+ahead of the copier's own reveal.++---++## What this is not++Alpha-drip is a leader gating **their own** self-produced signal as a+subscription product, the same thing a paid signal group has always sold, except+enforced by the fanout instead of by trust. It is not access to anyone else's+orderflow: three.ws does not route third-party orders, has nothing to reorder,+and no code path here reads another trader's pending activity. The standing+disclosure says exactly that, on every surface, and a leader cannot remove it.++Every trade a leader makes remains in their public track record, their+[trader passport](./trader-passport.md), and the leaderboard, at the moment it+happens, regardless of any ladder.diff --git a/docs/copy-trading.md b/docs/copy-trading.mdindex 33d9b2b19..9c9682193 100644--- a/docs/copy-trading.md+++ b/docs/copy-trading.md@@ -11,6 +11,8 @@ Both are Solana-native. Both run on `mainnet` and `devnet`. Neither is a paper-tIf you want to feel a leader's edge before committing money, that is a *separate* surface: [Ghost-copy](./ghost-copy.md) replays a leader's real closed trades against a wallet that does not exist. It never touches either engine below and never produces an intent.+A leader can also price *when* each copier is shown their signal: [alpha-drip](./alpha-drip.md) releases the copy intent to higher $THREE tiers first and everyone else after a delay the leader sets. It is off unless a leader turns it on, it delays the reveal and never the record, and the copier is shown the seat they get before they subscribe.+Related reading: [Smart Money Radar](./smart-money.md) for the first-party wallet reputation graph, [the trading surfaces](./trading-surfaces.md) for the screeners and the trading cockpit these leaders trade from, [agent wallets](./agent-wallets.md) for the custody and spend-policy model, and [signal marketplace](./signals.md) for the paid-feed variant that reuses the same guarded executor.---diff --git a/src/alpha-drip-panel.js b/src/alpha-drip-panel.jsnew file mode 100644index 000000000..b2d5be09f--- /dev/null+++ b/src/alpha-drip-panel.js@@ -0,0 +1,376 @@+/**+ * Alpha-drip editor — a leader prices the latency of their own signal.+ *+ * Mounted on the copy dashboard for every agent the signed-in user owns that+ * someone is actually copying. The leader sets how long each $THREE tier waits+ * before the copy intent is revealed to them; higher tiers can never wait+ * longer, and the public delay is always the longest.+ *+ * The server is the authority on every rule here (api/_lib/alpha-drip.js). This+ * form mirrors them so the leader is told immediately rather than after a+ * round trip, and it never invents a rule the server does not enforce.+ *+ * Import and call `mountAlphaDripPanel(el)`.+ */++import { escapeHtml } from './trader-format.js';++const $ = (sel, root) => root.querySelector(sel);+const $$ = (sel, root) => Array.from(root.querySelectorAll(sel));++const STYLE_ID = 'alpha-drip-styles';+const STYLE = `+.ad-lead { border: 1px solid var(--nxt-stroke, #23262e); border-radius: 10px; padding: 14px; margin-bottom: 12px; background: var(--nxt-bg-2, #14161b); }+.ad-lead:last-child { margin-bottom: 0; }+.ad-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; flex-wrap: wrap; }+.ad-name { font-weight: 600; font-size: 14px; }+.ad-copiers { font-size: 12px; color: var(--nxt-ink-dim, #8b90a0); font-variant-numeric: tabular-nums; }+.ad-summary { font-size: 12.5px; color: var(--nxt-ink-dim, #8b90a0); margin: 6px 0 0; }+.ad-modes { display: flex; gap: 8px; margin: 12px 0; flex-wrap: wrap; }+.ad-mode { font-size: 12px; padding: 6px 12px; border-radius: 999px; border: 1px solid var(--nxt-stroke, #23262e); background: transparent; color: var(--nxt-ink, #e7e9ee); cursor: pointer; transition: border-color .14s ease, background .14s ease, transform .14s ease; }+.ad-mode:hover { border-color: var(--nxt-stroke-strong, #3a3f4b); transform: translateY(-1px); }+.ad-mode:focus-visible { outline: 2px solid var(--nxt-accent, #63e6be); outline-offset: 2px; }+.ad-mode[aria-pressed="true"] { background: var(--nxt-accent, #63e6be); color: #061018; border-color: transparent; }+.ad-grid { display: grid; gap: 8px; margin: 12px 0; }+.ad-row { display: grid; grid-template-columns: minmax(96px, 1.1fr) minmax(84px, 1fr) minmax(84px, 1fr); gap: 8px; align-items: center; }+.ad-row-h { font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: var(--nxt-ink-dim, #8b90a0); }+.ad-tier { font-size: 13px; display: flex; flex-direction: column; gap: 1px; }+.ad-tier small { font-size: 11px; color: var(--nxt-ink-dim, #8b90a0); }+.ad-lead input[type="number"], .ad-lead textarea { width: 100%; font: inherit; font-size: 13px; padding: 7px 9px; border-radius: 7px; border: 1px solid var(--nxt-stroke, #23262e); background: var(--nxt-bg, #0d0f13); color: var(--nxt-ink, #e7e9ee); transition: border-color .14s ease; }+.ad-lead input[type="number"]:hover, .ad-lead textarea:hover { border-color: var(--nxt-stroke-strong, #3a3f4b); }+.ad-lead input[type="number"]:focus-visible, .ad-lead textarea:focus-visible { outline: 2px solid var(--nxt-accent, #63e6be); outline-offset: 1px; border-color: transparent; }+.ad-lead textarea { resize: vertical; min-height: 58px; }+.ad-field { margin: 10px 0; }+.ad-field label { display: block; font-size: 12px; color: var(--nxt-ink-dim, #8b90a0); margin-bottom: 4px; }+.ad-note { font-size: 12px; color: var(--nxt-ink-dim, #8b90a0); margin: 8px 0 0; line-height: 1.5; }+.ad-warn { font-size: 12px; color: var(--nxt-warn, #f59e0b); margin: 8px 0 0; line-height: 1.5; }+.ad-err { font-size: 12px; color: var(--nxt-danger, #f87171); margin: 8px 0 0; }+.ad-ok { font-size: 12px; color: var(--nxt-success, #4ade80); margin: 8px 0 0; }+.ad-actions { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; }+.ad-btn { font-size: 12px; padding: 6px 14px; border-radius: 7px; border: 1px solid var(--nxt-stroke, #23262e); background: var(--nxt-bg-2, #14161b); color: var(--nxt-ink, #e7e9ee); cursor: pointer; transition: border-color .14s ease, transform .14s ease, opacity .14s ease; }+.ad-btn:hover:not(:disabled) { border-color: var(--nxt-stroke-strong, #3a3f4b); transform: translateY(-1px); }+.ad-btn:focus-visible { outline: 2px solid var(--nxt-accent, #63e6be); outline-offset: 2px; }+.ad-btn:disabled { opacity: .55; cursor: progress; }+.ad-btn.primary { background: var(--nxt-accent, #63e6be); color: #061018; border-color: transparent; }+.ad-sk { height: 74px; border-radius: 10px; background: var(--nxt-bg-2, #14161b); animation: ad-pulse 1.4s ease infinite; }+@keyframes ad-pulse { 0%, 100% { opacity: .55 } 50% { opacity: 1 } }+.ad-fold { transition: opacity .16s ease; }+.ad-fold[hidden] { display: none; }+@media (max-width: 560px) {+ .ad-row { grid-template-columns: 1fr 1fr; }+ .ad-row .ad-tier { grid-column: 1 / -1; }+}+@media (prefers-reduced-motion: reduce) {+ .ad-btn, .ad-mode, .ad-lead input, .ad-lead textarea, .ad-fold { transition: none; }+ .ad-sk { animation: none; }+}`;++function ensureStyles() {+ if (document.getElementById(STYLE_ID)) return;+ const tag = document.createElement('style');+ tag.id = STYLE_ID;+ tag.textContent = STYLE;+ document.head.appendChild(tag);+}++// A CSRF token is single-use — the server burns it on first use and returns it+// as { data: { token } } — so it is fetched per mutation and never cached.+async function csrfToken() {+ try {+ const r = await fetch('/api/csrf-token', { credentials: 'include' });+ if (!r.ok) return null;+ const j = await r.json().catch(() => null);+ return j?.data?.token || null;+ } catch {+ return null;+ }+}++async function api(path, opts = {}) {+ const headers = { accept: 'application/json', ...(opts.headers || {}) };+ if (opts.body) {+ headers['content-type'] = 'application/json';+ const token = await csrfToken();+ if (token) headers['x-csrf-token'] = token;+ }+ const res = await fetch(path, { credentials: 'include', ...opts, headers });+ const body = await res.json().catch(() => ({}));+ return { ok: res.ok, status: res.status, body };+}++/** "45s" / "2m 30s" — matches formatDelay() in api/_lib/alpha-drip.js. */+export function formatDelay(sec) {+ const s = Math.max(0, Math.round(Number(sec) || 0));+ if (s < 60) return `${s}s`;+ const m = Math.floor(s / 60);+ const r = s % 60;+ return r ? `${m}m ${r}s` : `${m}m`;+}++/**+ * Mirror of the server's monotonicity rule, so a leader is told before they+ * save instead of after. The server still re-checks everything.+ */+export function validateLadder(rows, publicDelay) {+ const priced = rows.filter((r) => r.delay_sec != null);+ // rows arrive high tier first+ let prev = 0;+ for (const r of priced) {+ if (r.delay_sec < prev) return `${r.label} waits less than a higher tier — a higher tier can never wait longer.`;+ prev = r.delay_sec;+ }+ if (priced.length && publicDelay < prev) return 'Everyone else must wait at least as long as the slowest paid tier.';+ if (!priced.length && publicDelay === 0) return 'Set at least one delay, or switch back to releasing to everyone at once.';+ return null;+}++export async function mountAlphaDripPanel(el) {+ ensureStyles();+ el.innerHTML = `<div class="ad-sk" role="status" aria-label="Loading your signal release settings"></div>`;++ let res;+ try {+ res = await api('/api/copy/alpha-drip?mine=1');+ } catch {+ return renderError(el, 'Could not reach the server.', () => mountAlphaDripPanel(el));+ }+ if (res.status === 401) { el.innerHTML = ''; return; }+ if (!res.ok) return renderError(el, res.body?.message || 'Could not load your release settings.', () => mountAlphaDripPanel(el));++ const leaders = res.body.leaders || [];+ // Nothing to price until somebody is copying you. Render nothing rather than+ // an empty box: the copy dashboard already tells a non-leader what to do next.+ if (!leaders.length) { el.innerHTML = ''; return; }++ el.innerHTML = leaders.map(leaderCard).join('');+ for (const leader of leaders) wireCard(el, leader);+}++function renderError(el, message, retry) {+ el.innerHTML = `+ <div class="ad-lead">+ <p class="ad-err">${escapeHtml(message)}</p>+ <div class="ad-actions"><button type="button" class="ad-btn" data-ad-retry>Try again</button></div>+ </div>`;+ $('[data-ad-retry]', el)?.addEventListener('click', retry);+}++function leaderCard(leader) {+ const id = leader.leader_agent_id;+ const drip = leader.drip;+ const tiers = drip.tiers || [];+ const byTier = new Map((drip.schedule || []).map((e) => [e.tier, e]));+ // High tier first: the seat a leader prices first is the one they sell.+ const ordered = [...tiers].reverse();++ const rows = ordered.map((t) => {+ const entry = byTier.get(t.id);+ return `+ <div class="ad-row" data-tier="${escapeHtml(t.id)}">+ <span class="ad-tier">${escapeHtml(t.label)}<small>holds $${t.min_usd}+ of $THREE</small></span>+ <input type="number" min="0" max="900" step="1" inputmode="numeric"+ data-ad-delay="${escapeHtml(t.id)}"+ value="${entry ? entry.delay_sec : ''}"+ placeholder="inherit"+ aria-label="${escapeHtml(t.label)} tier delay in seconds" />+ <input type="number" min="0" step="0.001" inputmode="decimal"+ data-ad-cap="${escapeHtml(t.id)}"+ value="${entry && entry.max_copy_size_sol != null ? entry.max_copy_size_sol : ''}"+ placeholder="no cap"+ aria-label="${escapeHtml(t.label)} tier max copy size in SOL" />+ </div>`;+ }).join('');++ return `+ <div class="ad-lead" data-ad-leader="${escapeHtml(id)}">+ <div class="ad-head">+ <span class="ad-name">${escapeHtml(leader.leader_name || 'Your trader')}</span>+ <span class="ad-copiers">${leader.copiers} ${leader.copiers === 1 ? 'copier' : 'copiers'}</span>+ </div>+ <p class="ad-summary" data-ad-summary>${escapeHtml(drip.summary)}</p>++ <div class="ad-modes" role="group" aria-label="Signal release mode">+ <button type="button" class="ad-mode" data-ad-mode="off" aria-pressed="${drip.enabled ? 'false' : 'true'}">Everyone at once</button>+ <button type="button" class="ad-mode" data-ad-mode="on" aria-pressed="${drip.enabled ? 'true' : 'false'}">Tiered release</button>+ </div>++ <div class="ad-fold" data-ad-fold ${drip.enabled ? '' : 'hidden'}>+ <div class="ad-row ad-row-h" aria-hidden="true">+ <span>$THREE tier</span><span>Delay (s)</span><span>Max copy (◎)</span>+ </div>+ <div class="ad-grid">+ ${rows}+ <div class="ad-row" data-tier="__public">+ <span class="ad-tier">Everyone else<small>holds no $THREE</small></span>+ <input type="number" min="0" max="900" step="1" inputmode="numeric"+ data-ad-public value="${drip.public_delay_sec}"+ aria-label="Public delay in seconds" />+ <span></span>+ </div>+ </div>+ <div class="ad-field">+ <label for="ad-disc-${escapeHtml(id)}">What subscribers are told (optional)</label>+ <textarea id="ad-disc-${escapeHtml(id)}" data-ad-disclosure maxlength="280"+ placeholder="e.g. Gold and above get my calls the moment I fire.">${escapeHtml(drip.leader_note || '')}</textarea>+ </div>+ <div class="ad-field">+ <label for="ad-cap-${escapeHtml(id)}">Capacity note (optional)</label>+ <textarea id="ad-cap-${escapeHtml(id)}" data-ad-capacity maxlength="280"+ placeholder="e.g. Early tiers are size-capped so later tiers still get a fill.">${escapeHtml(drip.capacity_note || '')}</textarea>+ </div>+ <p class="ad-note">Leave a tier blank to inherit the next tier down. Every trade still lands in your public track record either way: a ladder delays the reveal, never the record.</p>+ </div>++ <div class="ad-actions">+ <button type="button" class="ad-btn primary" data-ad-save>Save release</button>+ <button type="button" class="ad-btn" data-ad-suggest>Suggest a ladder</button>+ <a class="ad-btn" href="/docs/alpha-drip">How this works</a>+ </div>+ <p class="ad-warn" data-ad-warn hidden></p>+ <p class="ad-err" data-ad-err hidden></p>+ <p class="ad-ok" data-ad-ok hidden></p>+ </div>`;+}++function wireCard(root, leader) {+ const card = $(`[data-ad-leader="${CSS.escape(leader.leader_agent_id)}"]`, root);+ if (!card) return;+ const fold = $('[data-ad-fold]', card);+ const warn = $('[data-ad-warn]', card);+ const err = $('[data-ad-err]', card);+ const okMsg = $('[data-ad-ok]', card);+ const summary = $('[data-ad-summary]', card);+ const tierLabels = new Map((leader.drip.tiers || []).map((t) => [t.id, t.label]));++ const say = (node, text) => {+ node.textContent = text || '';+ node.hidden = !text;+ };+ const clear = () => { say(err, ''); say(okMsg, ''); };++ const enabled = () => $('[data-ad-mode="on"]', card).getAttribute('aria-pressed') === 'true';++ const readLadder = () => {+ const rows = $$('[data-ad-delay]', card).map((input) => {+ const tier = input.dataset.adDelay;+ const raw = input.value.trim();+ const cap = $(`[data-ad-cap="${CSS.escape(tier)}"]`, card).value.trim();+ return {+ tier,+ label: tierLabels.get(tier) || tier,+ delay_sec: raw === '' ? null : Math.round(Number(raw)),+ max_copy_size_sol: cap === '' ? null : Number(cap),+ };+ });+ const pub = Math.round(Number($('[data-ad-public]', card).value.trim() || 0));+ return { rows, publicDelay: Number.isFinite(pub) ? pub : 0 };+ };++ const describe = () => {+ if (!enabled()) return 'Every copier gets this leader\'s signal at the same moment.';+ const { rows, publicDelay } = readLadder();+ const parts = rows+ .filter((r) => r.delay_sec != null)+ .map((r) => `${r.label}+ ${r.delay_sec === 0 ? 'instant' : `after ${formatDelay(r.delay_sec)}`}`);+ parts.push(`everyone else ${publicDelay === 0 ? 'instant' : `after ${formatDelay(publicDelay)}`}`);+ return `${parts.join(', ')}.`;+ };++ const refresh = () => {+ summary.textContent = describe();+ if (!enabled()) { say(warn, ''); return; }+ const { rows, publicDelay } = readLadder();+ say(warn, validateLadder(rows, publicDelay) || '');+ };++ for (const btn of $$('[data-ad-mode]', card)) {+ btn.addEventListener('click', () => {+ const on = btn.dataset.adMode === 'on';+ $('[data-ad-mode="on"]', card).setAttribute('aria-pressed', String(on));+ $('[data-ad-mode="off"]', card).setAttribute('aria-pressed', String(!on));+ fold.hidden = !on;+ clear();+ refresh();+ });+ }+ for (const input of $$('input[type="number"]', card)) {+ input.addEventListener('input', () => { clear(); refresh(); });+ }++ $('[data-ad-save]', card).addEventListener('click', async (ev) => {+ const btn = ev.currentTarget;+ clear();+ const { rows, publicDelay } = readLadder();+ if (enabled()) {+ const problem = validateLadder(rows, publicDelay);+ if (problem) return say(err, problem);+ }+ btn.disabled = true;+ btn.textContent = 'Saving…';+ try {+ const res = await api('/api/copy/alpha-drip', {+ method: 'POST',+ body: JSON.stringify({+ leader_agent_id: leader.leader_agent_id,+ enabled: enabled(),+ public_delay_sec: enabled() ? publicDelay : 0,+ schedule: enabled() ? rows.filter((r) => r.delay_sec != null).map((r) => ({+ tier: r.tier, delay_sec: r.delay_sec, max_copy_size_sol: r.max_copy_size_sol,+ })) : [],+ disclosure: $('[data-ad-disclosure]', card).value.trim() || null,+ capacity_note: $('[data-ad-capacity]', card).value.trim() || null,+ }),+ });+ if (!res.ok) return say(err, res.body?.message || 'Could not save the release ladder.');+ summary.textContent = res.body.drip.summary;+ say(warn, res.body.fairness?.warning || '');+ say(okMsg, 'Saved. New signals release on this ladder.');+ } catch {+ say(err, 'Could not reach the server. Try again.');+ } finally {+ btn.disabled = false;+ btn.textContent = 'Save release';+ }+ });++ $('[data-ad-suggest]', card).addEventListener('click', async (ev) => {+ const btn = ev.currentTarget;+ clear();+ btn.disabled = true;+ btn.textContent = 'Drafting…';+ try {+ const res = await api('/api/copy/alpha-drip', {+ method: 'POST',+ body: JSON.stringify({ action: 'recommend', leader_agent_id: leader.leader_agent_id }),+ });+ if (!res.ok) return say(err, res.body?.message || 'Could not draft a ladder.');+ applySuggestion(card, res.body.suggestion);+ $('[data-ad-mode="on"]', card).setAttribute('aria-pressed', 'true');+ $('[data-ad-mode="off"]', card).setAttribute('aria-pressed', 'false');+ fold.hidden = false;+ refresh();+ say(warn, res.body.fairness?.warning || '');+ say(okMsg, 'Draft loaded. Nothing is live until you save it.');+ } catch {+ say(err, 'Could not reach the server. Try again.');+ } finally {+ btn.disabled = false;+ btn.textContent = 'Suggest a ladder';+ }+ });++ refresh();+}++function applySuggestion(card, suggestion) {+ const byTier = new Map((suggestion.schedule || []).map((e) => [e.tier, e]));+ for (const input of $$('[data-ad-delay]', card)) {+ const entry = byTier.get(input.dataset.adDelay);+ input.value = entry ? String(entry.delay_sec) : '';+ const cap = $(`[data-ad-cap="${CSS.escape(input.dataset.adDelay)}"]`, card);+ cap.value = entry && entry.max_copy_size_sol != null ? String(entry.max_copy_size_sol) : '';+ }+ $('[data-ad-public]', card).value = String(suggestion.public_delay_sec ?? 0);+ if (suggestion.leader_note) $('[data-ad-disclosure]', card).value = suggestion.leader_note;+ if (suggestion.capacity_note) $('[data-ad-capacity]', card).value = suggestion.capacity_note;+}diff --git a/src/copy-panel.js b/src/copy-panel.jsindex 3a3446483..5d6581a66 100644--- a/src/copy-panel.js+++ b/src/copy-panel.js@@ -48,10 +48,55 @@ export async function mountCopyPanel(el, { leaderAgentId, leaderName, network =const { subscriptions = [] } = await res.json().catch(() => ({ subscriptions: [] }));const existing = subscriptions.find((s) => s.leader_agent_id === leaderAgentId && s.network === network);+ // A leader on an alpha-drip releases to higher $THREE tiers first. Show the+ // copier the seat THEY get before they commit, never after: an unexpected+ // delay discovered from an empty inbox is the version of this that erodes+ // trust. Best-effort — a drip read must never block copy setup.+ const drip = await fetchDrip(leaderAgentId);+if (existing && existing.status !== 'stopped') {- return renderActive(el, { existing, leaderName, leaderAgentId, network });+ return renderActive(el, { existing, leaderName, leaderAgentId, network, drip });+ }+ return renderForm(el, { leaderAgentId, leaderName, network, prefill: existing || null, drip });+}++async function fetchDrip(leaderAgentId) {+ try {+ const res = await api(`/api/copy/alpha-drip?leader_agent_id=${encodeURIComponent(leaderAgentId)}`);+ if (!res.ok) return null;+ const body = await res.json().catch(() => null);+ return body?.drip?.enabled ? body : null;+ } catch {+ return null;}- return renderForm(el, { leaderAgentId, leaderName, network, prefill: existing || null });+}++/** The copier-facing seat note: their wait, the ladder, and the disclosure. */+function dripNote(drip) {+ if (!drip) return '';+ const you = drip.you;+ const seat = you+ ? (you.delay_sec === 0+ ? `Your ${escapeHtml(you.tier_label)} seat gets this trader's calls the moment they fire.`+ : `Your ${escapeHtml(you.tier_label)} seat waits ${escapeHtml(fmtDelay(you.delay_sec))} after this trader fires.`)+ : 'Sign in to see the seat your $THREE balance gets.';+ const upgrade = you && you.delay_sec > 0+ ? ` <a href="/three-token">Hold more $THREE to move up →</a>`+ : '';+ return `+ <p class="cp-drip">+ <strong>Tiered release.</strong> ${seat}${upgrade}<br />+ <span class="cp-drip-sub">${escapeHtml(drip.drip.summary)} ${escapeHtml(drip.drip.disclosure || '')}</span>+ </p>`;+}++/** Matches formatDelay() in api/_lib/alpha-drip.js. */+function fmtDelay(sec) {+ const s = Math.max(0, Math.round(Number(sec) || 0));+ if (s < 60) return `${s}s`;+ const m = Math.floor(s / 60);+ const r = s % 60;+ return r ? `${m}m ${r}s` : `${m}m`;}// --- States ------------------------------------------------------------------@@ -74,7 +119,7 @@ function renderError(el, retry) {$('#cp-retry', el)?.addEventListener('click', retry);}-function renderActive(el, { existing, leaderName, leaderAgentId, network }) {+function renderActive(el, { existing, leaderName, leaderAgentId, network, drip = null }) {const s = existing;const sizeLabel = s.sizing_rule === 'fixed' ? `${Number(s.fixed_sol)} SOL fixed`: s.sizing_rule === 'multiplier' ? `${Number(s.multiplier)}× their size`@@ -91,6 +136,7 @@ function renderActive(el, { existing, leaderName, leaderAgentId, network }) {Exits you were already in still come through. Resume when they recover, or edit your limit.</p>` : ''}<p>${escapeHtml(sizeLabel)} · cap ${Number(s.per_trade_cap_sol)} SOL/trade · ${Number(s.daily_budget_sol)} SOL/day${limit ? ` · pause at ${limit}% drawdown` : ''}.New trades arrive as intents in your dashboard.${s.telegram_chat_id ? ` Telegram alerts on.` : ''}</p>+ ${dripNote(drip)}<p class="cp-err" id="cp-toggle-err" hidden></p><div class="cp-actions"><a class="lb-btn lb-btn-primary" href="/dashboard/copy">Manage copies →</a>@@ -117,15 +163,16 @@ function renderActive(el, { existing, leaderName, leaderAgentId, network }) {btn.disabled = false;btn.textContent = label;});- $('#cp-edit', el)?.addEventListener('click', () => renderForm(el, { leaderAgentId, leaderName, network, prefill: s }));+ $('#cp-edit', el)?.addEventListener('click', () => renderForm(el, { leaderAgentId, leaderName, network, prefill: s, drip }));}-function renderForm(el, { leaderAgentId, leaderName, network, prefill }) {+function renderForm(el, { leaderAgentId, leaderName, network, prefill, drip = null }) {const p = prefill || {};const rule = p.sizing_rule || 'fixed';el.innerHTML = `<h2>Copy ${escapeHtml(leaderName || 'this trader')}</h2><p>You sign every trade from your own wallet. We never take custody — these are sized intents, capped by your rules.</p>+ ${dripNote(drip)}<form class="cp-form" id="cp-form" novalidate><label class="cp-field"><span class="cp-label">Your Solana wallet</span>diff --git a/src/dashboard-next/pages/copy.js b/src/dashboard-next/pages/copy.jsindex 73e8645ed..cc5b69b6e 100644--- a/src/dashboard-next/pages/copy.js+++ b/src/dashboard-next/pages/copy.js@@ -11,6 +11,7 @@ import { mountShell } from '../shell.js';import { requireUser, get, post, del, esc, relTime } from '../api.js';import { errorStateHTML, ensureStateKitStyles, attachRetry } from '../../shared/state-kit.js';import { gmgnAddressUrl } from '../../shared/trading-terminals.js';+import { mountAlphaDripPanel, formatDelay } from '../../alpha-drip-panel.js';const SKIP_LABEL = {below_mcap_floor: 'Below your market-cap floor',@@ -24,6 +25,7 @@ const SKIP_LABEL = {daily_budget_spent: 'Daily budget used up',max_open_copies: 'Open-copies cap reached',sizing_unavailable: 'Could not size (no balance)',+ drip_capacity_cap: 'Your tier\'s size cap left the order below your minimum',};const fmtSol = (n) => {@@ -60,6 +62,8 @@ const STYLE = `.cp-tag.sell { color: var(--nxt-warn); border-color: color-mix(in srgb, var(--nxt-warn) 40%, transparent); }.cp-tag.on { color: var(--nxt-success); }.cp-tag.paused { color: var(--nxt-warn); }+.cp-tripped { color: var(--nxt-warn); margin-top: 4px; line-height: 1.45; }+.cp-sub-err { color: var(--nxt-danger); margin-top: 4px; line-height: 1.45; }.cp-tag.skipped, .cp-tag.expired, .cp-tag.dismissed { color: var(--nxt-ink-dim); }.cp-tag.acted { color: var(--nxt-success); }.cp-btn { font-size: 12px; padding: 5px 12px; border-radius: var(--nxt-radius-sm); border: 1px solid var(--nxt-stroke); background: var(--nxt-bg-2); color: var(--nxt-ink); cursor: pointer; text-decoration: none; transition: border-color .14s, transform .14s; white-space: nowrap; }@@ -69,6 +73,10 @@ const STYLE = `.cp-skeleton { height: 56px; border-radius: 10px; background: var(--nxt-bg-2); animation: cp-pulse 1.4s ease infinite; }@keyframes cp-pulse { 0%,100% { opacity: .55 } 50% { opacity: 1 } }.cp-note { font-size: 12px; color: var(--nxt-ink-dim); margin: 0 0 14px; }+.cp-locked { opacity: .92; }+.cp-lock-coin { letter-spacing: .18em; color: var(--nxt-ink-dim); font-weight: 700; }+.cp-countdown { font-variant-numeric: tabular-nums; color: var(--nxt-ink-dim); transition: color .2s ease; }+.cp-locked:hover .cp-countdown { color: var(--nxt-ink); }.cp-oracle { display: inline-flex; }.cp-ob { display: inline-flex; align-items: center; gap: 3px; background: rgba(0,0,0,0.4); border: 1px solid rgba(255,255,255,0.08); border-radius: 6px; padding: 2px 7px; text-decoration: none; font-size: 11px; transition: border-color .12s; }.cp-ob:hover { border-color: rgba(255,255,255,0.22); }@@ -145,10 +153,15 @@ const STYLE = `}</style>`;+// One countdown interval for the whole page; a re-render replaces it rather+// than stacking a second ticker on the same rows.+let _countdownTimer = null;+function img(e) { return e.leader_image || e.leader_avatar || '/favicon.ico'; }function traderHref(agentId) { return `/trader/${encodeURIComponent(agentId)}`; }function intentRow(e) {+ if (e.locked) return lockedIntentRow(e);const isBuy = e.direction === 'buy';const amount = isBuy ? `<span class="cp-amt">${fmtSol(e.planned_sol)}</span>` : `<span class="cp-tag sell">Exit your copy</span>`;const proof = e.leader_buy_sig ? `<a href="https://solscan.io/tx/${esc(e.leader_buy_sig)}" target="_blank" rel="noopener">leader tx ↗</a>` : '';@@ -174,17 +187,71 @@ function intentRow(e) {</div>`;}+/**+ * An intent this copier's $THREE tier has not reached yet. The leader and the+ * fact that they fired are shown — the coin and the size are not, because that+ * is precisely what the leader's release ladder sells. It unlocks in place: the+ * countdown reaches zero and the next poll renders the real row.+ */+function lockedIntentRow(e) {+ const tier = e.drip_tier ? e.drip_tier.charAt(0).toUpperCase() + e.drip_tier.slice(1) : null;+ const held = e.drip_delay_sec ? `held ${formatDelay(e.drip_delay_sec)} on this trader's ladder` : 'held on this trader\'s ladder';+ return `+ <div class="cp-item cp-locked" data-id="${esc(e.id)}" data-unlocks-at="${esc(e.unlocks_at || '')}">+ <img loading="lazy" decoding="async" class="cp-av" src="${esc(img(e))}" alt="" data-fallback="invisible" />+ <div class="cp-mid">+ <div class="cp-title">+ <span class="cp-tag">LOCKED</span>+ <span class="cp-lock-coin" aria-label="Coin hidden until release">•••••</span>+ <span class="cp-sub" style="margin:0">via <a href="${traderHref(e.leader_agent_id)}">${esc(e.leader_name || 'trader')}</a></span>+ </div>+ <div class="cp-sub">${tier ? `${esc(tier)} seat · ` : ''}${held} · <a href="/docs/alpha-drip">why?</a></div>+ </div>+ <div class="cp-side">+ <span class="cp-amt cp-countdown" data-countdown role="timer" aria-live="off">${esc(formatDelay(e.unlocks_in_sec || 0))}</span>+ <a class="cp-btn ghost" href="/three-token" aria-label="Hold more $THREE to unlock this trader's signal sooner">Unlock sooner</a>+ </div>+ </div>`;+}++/**+ * Tick every locked row's countdown, and reload the inbox the moment one hits+ * zero so the real intent replaces it without the copier touching anything.+ */+function startCountdowns(host, reload) {+ const timer = setInterval(() => {+ const rows = Array.from(host.querySelectorAll('.cp-locked[data-unlocks-at]'));+ if (!rows.length) { clearInterval(timer); return; }+ let due = false;+ for (const row of rows) {+ const at = Date.parse(row.dataset.unlocksAt || '');+ const left = Number.isFinite(at) ? Math.max(0, Math.ceil((at - Date.now()) / 1000)) : 0;+ const cell = row.querySelector('[data-countdown]');+ if (cell) cell.textContent = formatDelay(left);+ if (left <= 0) due = true;+ }+ if (due) { clearInterval(timer); reload(); }+ }, 1000);+ return timer;+}+function subRow(s) {const paused = s.status === 'paused';+ // A subscription the drawdown breaker paused was not paused by this user, so+ // the row has to say what happened — "Paused" alone reads as their own doing.+ const tripped = paused && s.paused_reason === 'leader_drawdown_breach';+ const ddLimit = s.max_drawdown_pct == null ? null : Number(s.max_drawdown_pct);return `<div class="cp-item" data-sub="${esc(s.id)}"><img loading="lazy" decoding="async" class="cp-av" src="${esc(img(s))}" alt="" data-fallback="invisible" /><div class="cp-mid"><div class="cp-title"><a href="${traderHref(s.leader_agent_id)}" style="color:inherit;text-decoration:none">${esc(s.leader_name || 'trader')}</a>- <span class="cp-tag ${paused ? 'paused' : 'on'}">${paused ? 'Paused' : '● Active'}</span>+ <span class="cp-tag ${paused ? 'paused' : 'on'}">${tripped ? 'Auto-paused' : paused ? 'Paused' : '● Active'}</span></div>- <div class="cp-sub">${esc(sizingLabel(s))} · cap ${Number(s.per_trade_cap_sol)} ◎ · ${Number(s.daily_budget_sol)} ◎/day · ${Number(s.pending_count) || 0} pending${s.min_oracle_score != null ? ` · Oracle ≥${s.min_oracle_score}` : ''}${s.telegram_chat_id ? ' · TG alerts on' : ''}</div>+ <div class="cp-sub">${esc(sizingLabel(s))} · cap ${Number(s.per_trade_cap_sol)} ◎ · ${Number(s.daily_budget_sol)} ◎/day · ${Number(s.pending_count) || 0} pending${ddLimit ? ` · stop at ${ddLimit}% DD` : ''}${s.min_oracle_score != null ? ` · Oracle ≥${s.min_oracle_score}` : ''}${s.telegram_chat_id ? ' · TG alerts on' : ''}</div>+ ${tripped ? `<div class="cp-sub cp-tripped">This trader fell past your ${ddLimit}% drawdown limit, so new copies stopped. Exits you're already in still arrive. Resume once they recover, or widen the limit on their profile.</div>` : ''}+ <div class="cp-sub cp-sub-err" data-sub-err hidden></div></div><div class="cp-side"><button type="button" class="cp-btn" data-sub-act="${paused ? 'active' : 'paused'}" aria-label="${paused ? 'Resume' : 'Pause'} copying ${esc(s.leader_name || 'trader')}">${paused ? 'Resume' : 'Pause'}</button>@@ -376,6 +443,12 @@ async function loadAndRender(host) {${earningsSection(earnings)}+ <section class="cp-sec" id="cp-drip" hidden>+ <div class="cp-sec-h"><h2>Your signal release</h2></div>+ <p class="cp-note">Price the latency of your own calls: $THREE holders in higher tiers see your intent first, everyone else after the delay you set. The trade still lands in your public track record either way.</p>+ <div id="cp-drip-panel"></div>+ </section>+<section class="cp-sec"><div class="cp-sec-h"><h2>History</h2><span class="cp-count">${hist.length}</span></div>${historyStats(hist)}@@ -392,6 +465,20 @@ async function loadAndRender(host) {// Enrich pending intent rows with Oracle conviction badgesenrichIntentOracle(host.querySelector('#cp-pending'));+ // Locked intents count down in place and reload themselves on release.+ if (_countdownTimer) clearInterval(_countdownTimer);+ _countdownTimer = startCountdowns(host, () => loadAndRender(host));++ // Leader side: price your own signal. The panel renders nothing (and the+ // section stays hidden) unless somebody is actually copying one of your agents.+ const dripHost = host.querySelector('#cp-drip-panel');+ if (dripHost) {+ mountAlphaDripPanel(dripHost).then(() => {+ const section = host.querySelector('#cp-drip');+ if (section) section.hidden = !dripHost.innerHTML.trim();+ });+ }+// Discover section: load top leaderboard traders the user isn't copying yetconst copiedIds = new Set(subs.filter((s) => s.status !== 'stopped').map((s) => s.leader_agent_id));loadDiscover(host, copiedIds);@@ -419,12 +506,22 @@ async function loadAndRender(host) {const row = btn.closest('[data-sub]');const id = row?.dataset.sub;const next = btn.dataset.subAct;+ const errEl = row?.querySelector('[data-sub-err]');+ if (errEl) { errEl.hidden = true; errEl.textContent = ''; }btn.disabled = true;try {if (next === 'stopped') await del(`/api/copy/subscriptions?id=${encodeURIComponent(id)}`);else await post('/api/copy/subscriptions', { id, status: next });loadAndRender(host);- } catch { btn.disabled = false; }+ } catch (err) {+ // A resume the breaker refuses is the common case here, and swallowing it+ // left the button looking broken. Say why it did not take.+ btn.disabled = false;+ if (errEl) {+ errEl.textContent = err?.message || 'Could not change this subscription.';+ errEl.hidden = false;+ }+ }});// Performance fee settlementdiff --git a/src/trader.css b/src/trader.cssindex b3b94b96f..7c6fcb7b3 100644--- a/src/trader.css+++ b/src/trader.css@@ -255,6 +255,25 @@background: var(--surface-2);}.cp-tripped strong { display: block; color: var(--ink-bright); margin-bottom: 2px; }++/* Alpha-drip: the seat this copier's $THREE tier gets on the leader's signal.+ Same left-rule treatment as the breaker notice, in the accent rather than the+ warn colour, because it is an offer and not a problem. */+.cp-drip {+ font-size: var(--text-xs);+ color: var(--ink-dim);+ line-height: 1.5;+ margin: 0 0 var(--space-sm);+ padding: var(--space-sm) var(--space-md);+ border-left: 2px solid var(--accent);+ border-radius: 0 var(--radius-sm) var(--radius-sm) 0;+ background: var(--surface-2);+}+.cp-drip strong { color: var(--ink-bright); }+.cp-drip a { color: var(--accent); text-decoration: none; border-bottom: 1px solid transparent; transition: border-color .14s ease; }+.cp-drip a:hover { border-bottom-color: currentColor; }+.cp-drip a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 2px; }+.cp-drip-sub { display: inline-block; margin-top: 2px; color: var(--ink-faint); }.cp-err .cp-unmet {list-style: none;margin: var(--space-2xs) 0;