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
Copy trading: Telegram notifications for buy intents
nirholas21f134c182b8
diff --git a/api/_lib/copy-engine.js b/api/_lib/copy-engine.jsindex 94e68fc45..bba2f6a82 100644--- a/api/_lib/copy-engine.js+++ b/api/_lib/copy-engine.js@@ -51,6 +51,13 @@ export function normalizeSubscriptionInput(raw = {}) {return { ok: false, error: 'min_oracle_score must be between 0 and 100' };}+ // Telegram chat ID: numeric string (positive or negative integer).+ const tgRaw = raw.telegram_chat_id == null ? null : String(raw.telegram_chat_id).trim();+ const telegramChatId = tgRaw === '' || tgRaw === null ? null : tgRaw;+ if (telegramChatId != null && !/^-?[0-9]+$/.test(telegramChatId)) {+ return { ok: false, error: 'telegram_chat_id must be a numeric Telegram chat ID' };+ }+return {ok: true,value: {@@ -68,6 +75,7 @@ export function normalizeSubscriptionInput(raw = {}) {require_safety_pass: raw.require_safety_pass === true,min_oracle_score: minOracleScore,perf_fee_bps: perfBps,+ telegram_chat_id: telegramChatId,},};}diff --git a/api/_lib/migrations/20260616220000_copy_telegram.sql b/api/_lib/migrations/20260616220000_copy_telegram.sqlnew file mode 100644index 000000000..92c24960f--- /dev/null+++ b/api/_lib/migrations/20260616220000_copy_telegram.sql@@ -0,0 +1,12 @@+-- Copy subscriptions: per-subscription Telegram chat ID for intent notifications.+-- When set, the fanout cron sends a Telegram message each time a new pending+-- intent is generated for this subscription, letting the copier act immediately.+-- Idempotent.+alter table copy_subscriptions+ add column if not exists telegram_chat_id text+ check (telegram_chat_id ~ '^-?[0-9]+$');++comment on column copy_subscriptions.telegram_chat_id is+ 'Optional Telegram chat ID (numeric string). When set, copier receives a+ message each time the fanout cron creates a pending copy intent for this+ subscription — buy alerts only (sell intents are informational, not urgent).';diff --git a/api/copy/subscriptions.js b/api/copy/subscriptions.jsindex 1bf4f2a50..399d2e5f0 100644--- a/api/copy/subscriptions.js+++ b/api/copy/subscriptions.js@@ -121,12 +121,14 @@ export default wrap(async (req, res) => {copier_user_id, copier_wallet, leader_agent_id, leader_wallet, network, status,sizing_rule, fixed_sol, multiplier, pct_balance,per_trade_cap_sol, min_order_sol, daily_budget_sol, max_open_copies,- mcap_floor_usd, mcap_ceiling_usd, copy_sells, require_safety_pass, min_oracle_score, perf_fee_bps+ mcap_floor_usd, mcap_ceiling_usd, copy_sells, require_safety_pass, min_oracle_score, perf_fee_bps,+ telegram_chat_id) values (${userId}, ${wallet}, ${leaderId}, ${leaderWallet}, ${network}, 'active',${v.sizing_rule}, ${v.fixed_sol}, ${v.multiplier}, ${v.pct_balance},${v.per_trade_cap_sol}, ${v.min_order_sol}, ${v.daily_budget_sol}, ${v.max_open_copies},- ${v.mcap_floor_usd}, ${v.mcap_ceiling_usd}, ${v.copy_sells}, ${v.require_safety_pass}, ${v.min_oracle_score}, ${v.perf_fee_bps}+ ${v.mcap_floor_usd}, ${v.mcap_ceiling_usd}, ${v.copy_sells}, ${v.require_safety_pass}, ${v.min_oracle_score}, ${v.perf_fee_bps},+ ${v.telegram_chat_id || null})on conflict (copier_user_id, leader_agent_id, network) do update setcopier_wallet = excluded.copier_wallet,@@ -146,6 +148,7 @@ export default wrap(async (req, res) => {require_safety_pass = excluded.require_safety_pass,min_oracle_score = excluded.min_oracle_score,perf_fee_bps = excluded.perf_fee_bps,+ telegram_chat_id = excluded.telegram_chat_id,updated_at = now()returning *`;diff --git a/api/cron/copy-fanout.js b/api/cron/copy-fanout.jsindex 284c21060..8b93e631b 100644--- a/api/cron/copy-fanout.js+++ b/api/cron/copy-fanout.js@@ -28,6 +28,50 @@ import { planCopyOrder } from '../_lib/copy-engine.js';const NETWORKS = ['mainnet', 'devnet'];const lamToSol = (l) => (l == null ? 0 : Number(BigInt(l)) / 1e9);+// ── Telegram notification helpers ─────────────────────────────────────────────++async function sendTg(chatId, text) {+ const token = process.env.TELEGRAM_BOT_TOKEN;+ if (!token || !chatId) return;+ try {+ await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ chat_id: chatId, text, disable_web_page_preview: true }),+ signal: AbortSignal.timeout(5000),+ });+ } catch { /* best-effort */ }+}++function buyIntentMessage({ sym, name, plannedSol, leaderName, oracleScore, oracleTier, mint, network, traderUrl }) {+ const coin = sym ? `$${sym}${name ? ` (${name})` : ''}` : mint?.slice(0, 8) || 'unknown';+ const tier = oracleTier ? ` [${oracleTier.toUpperCase()}]` : '';+ const score = oracleScore != null ? ` · score ${Math.round(oracleScore)}` : '';+ const net = network === 'devnet' ? ' [devnet]' : '';+ const lines = [+ `⚡ Copy Trade Intent${net}`,+ `${coin}${tier}${score}`,+ `Leader: ${leaderName || 'unknown'}`,+ `Your order: ${plannedSol != null ? `${plannedSol.toFixed(4)} SOL` : 'sized by your rules'}`,+ ``,+ `Act now → https://three.ws${traderUrl}/dashboard/copy`,+ mint ? `pump.fun → https://pump.fun/${mint}` : '',+ ].filter((l) => l !== undefined);+ return lines.join('\n');+}++// Fetch agent display name (cached per run).+const _agentNameCache = new Map();+async function agentName(agentId) {+ if (_agentNameCache.has(agentId)) return _agentNameCache.get(agentId);+ try {+ const [row] = await sql`select name from agent_identities where id = ${agentId} limit 1`;+ const n = row?.name || null;+ _agentNameCache.set(agentId, n);+ return n;+ } catch { return null; }+}+function requireCron(req, res) {const secret = process.env.CRON_SECRET || env.CRON_SECRET;if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }@@ -150,6 +194,16 @@ async function fanoutBuys(network, stats) {if (status === 'pending') {spent.set(sub.id, (spent.get(sub.id) || 0) + (planned || 0));open.set(sub.id, (open.get(sub.id) || 0) + 1);+ // Telegram notify copier of the new buy intent (best-effort, async).+ if (sub.telegram_chat_id) {+ const leader = await agentName(pos.agent_id);+ sendTg(sub.telegram_chat_id, buyIntentMessage({+ sym: pos.symbol, name: pos.name, plannedSol: planned,+ leaderName: leader, oracleScore: score,+ oracleTier: null, mint: pos.mint, network,+ traderUrl: `/trader/${pos.agent_id}`,+ }));+ }}}}@@ -278,6 +332,18 @@ async function fanoutOracleBuys(network, stats) {if (status === 'pending') {spent.set(sub.id, (spent.get(sub.id) || 0) + (planned || 0));open.set(sub.id, (open.get(sub.id) || 0) + 1);+ // Telegram notify copier of the new oracle-sourced buy intent (best-effort).+ if (sub.telegram_chat_id) {+ const leader = await agentName(action.agent_id);+ sendTg(sub.telegram_chat_id, buyIntentMessage({+ sym: action.symbol, name: null, plannedSol: planned,+ leaderName: leader,+ oracleScore: action.conviction != null ? Number(action.conviction) : null,+ oracleTier: action.tier || null,+ mint: action.mint, network,+ traderUrl: `/trader/${action.agent_id}`,+ }));+ }}}}diff --git a/src/copy-panel.js b/src/copy-panel.jsindex 5e89aa56e..afb72da3a 100644--- a/src/copy-panel.js+++ b/src/copy-panel.js@@ -160,6 +160,14 @@ function renderForm(el, { leaderAgentId, leaderName, network, prefill }) {</div><label class="cp-check"><input type="checkbox" id="cp-sells" ${p.copy_sells === false ? '' : 'checked'} /> <span>Mirror their exits too</span></label><label class="cp-check"><input type="checkbox" id="cp-safe" ${p.require_safety_pass ? 'checked' : ''} /> <span>Only copy when coin safety is confirmed</span></label>+ <div class="cp-row" style="margin-top:10px">+ <label class="cp-field">+ <span class="cp-label">Telegram alerts (optional)</span>+ <input class="cp-input" id="cp-tg" type="text" inputmode="numeric" autocomplete="off" spellcheck="false"+ placeholder="Your Telegram chat ID (numeric)" value="${escapeHtml(p.telegram_chat_id || '')}" pattern="-?[0-9]+" />+ <span class="cp-hint">Get your chat ID from @userinfobot. You'll be notified the moment a buy intent lands.</span>+ </label>+ </div></details><p class="cp-err" id="cp-err" hidden></p>@@ -201,6 +209,7 @@ function renderForm(el, { leaderAgentId, leaderName, network, prefill }) {min_oracle_score: $('#cp-oracle', el).value === '' ? null : Math.round(num('cp-oracle')),copy_sells: $('#cp-sells', el).checked,require_safety_pass: $('#cp-safe', el).checked,+ telegram_chat_id: (() => { const v = ($('#cp-tg', el)?.value || '').trim(); return /^-?[0-9]+$/.test(v) ? v : null; })(),};const btn = $('#cp-submit', el);