Every file in funded-extension.zip (version 0.2.23), exactly as the download ships it. Nothing is compiled or minified: this is the code your browser runs.
The zip's SHA-256 (53.9 KB):
aac20d3fa7fdf93a964ecd26b1a98609bccf4db8181b21fa37a0c172243ccc40
Get-FileHash funded-extension.zipshasum -a 256 funded-extension.zipIf the result matches (capital letters or not), your zip holds exactly the files below. Already unzipped it? Check a file the same way and compare it with its line in the list.
// Funded extension background worker: signs in to Funded, prices pump.fun coins and coins on a Raydium
// LaunchLab curve (StonkFun, bonk.fun…) from the chain (the trader's own browser and the free public
// RPC; when that keeps refusing this connection, Funded's server reads the same accounts) and other coins from
// DexScreener's free API, and sends Buy / Sell clicks to the Funded server, which stamps the time and
// keeps the account. The server prices other coins itself, and every click is later checked against the
// chain's history, so the prices here are a preview the server doesn't simply trust.
import { dexQuote } from "./lib/dex.js";
import { classify, coinPools, findLaunchPool, isAddress, mintMetadata, mintOfCurve, quoteCoin, rememberLaunchPool, setAccountsFallback } from "./lib/solana.js";
const DEFAULT_SERVER = "https://fundedsol.trade";
/** Sites that may sign the extension in: the ones the bridge script runs on, as the manifest lists them. */
const SITE_ORIGINS = chrome.runtime
.getManifest()
.content_scripts.filter((c) => c.js.includes("bridge.js"))
.flatMap((c) => c.matches.map((m) => new URL(m.replace(/\*$/, "")).origin));
const QUOTE_TTL_MS = 700;
/** DexScreener refreshes a pair every few seconds, and the server prices those fills itself. */
const DEX_QUOTE_TTL_MS = 2500;
const ACCOUNT_TTL_MS = 15_000;
// ───────────── storage ─────────────
const local = {
get: async (k) => (await chrome.storage.local.get(k))[k],
set: (k, v) => chrome.storage.local.set({ [k]: v }),
remove: (k) => chrome.storage.local.remove(k),
};
const session = {
get: async (k) => (await chrome.storage.session.get(k))[k],
set: (k, v) => chrome.storage.session.set({ [k]: v }),
};
// versions before 0.2.2 had an optional "your own RPC" setting: clear what it may have saved; and an
// account saved by a version before modes doesn't say which mode it's in
chrome.runtime.onInstalled.addListener(() => chrome.storage.local.remove(["settings", "account"]));
// ───────────── Funded server ─────────────
async function api(path, { method = "GET", body, idem } = {}) {
const auth = await local.get("auth");
if (!auth) return { ok: false, status: 401, body: { error: "Connect your Funded account first", signedOut: true } };
let res;
try {
res = await fetch(auth.server + path, {
method,
headers: { Authorization: `Bearer ${auth.token}`, "Content-Type": "application/json", ...(idem ? { "Idempotency-Key": idem } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(12_000),
});
} catch {
return { ok: false, status: 0, body: { error: "Couldn't reach Funded. Check your connection." } };
}
const json = await res.json().catch(() => ({}));
if (res.status === 401 && json.signedOut) {
// the sign-in was revoked or expired
await local.remove(["auth", "account"]);
}
return { ok: res.ok, status: res.status, body: json };
}
// when Solana's free endpoints keep refusing this connection, Funded's server reads the accounts with its own RPC
setAccountsFallback(async (addresses) => {
const r = await api("/api/ext/accounts", { method: "POST", body: { addresses } });
if (!r.ok || !Array.isArray(r.body.value)) throw new Error(r.body.error ?? "No answer from Funded");
return { value: r.body.value.map((a) => (a ? { owner: a.owner, data: [a.data, "base64"] } : null)) };
});
async function saveAccount(view) {
await local.set("account", { view, at: Date.now() });
return view;
}
/**
* The account of the trader's mode (Challenge or Practice; `view.mode` says which); with `mint`, also
* that coin's totals in it (the panel's PnL bar).
*/
async function account(force, mint) {
const auth = await local.get("auth");
if (!auth) return { signedIn: false };
const cached = await local.get("account");
const fits = !mint || cached?.view?.coin?.mint === mint;
if (!force && cached && fits && Date.now() - cached.at < ACCOUNT_TTL_MS) return { signedIn: true, email: auth.email, server: auth.server, view: cached.view };
const r = await api(`/api/ext/account?modes=1${mint && isAddress(mint) ? `&mint=${mint}` : ""}`);
if (!r.ok) return r.status === 401 ? { signedIn: false } : { signedIn: true, email: auth.email, server: auth.server, view: cached?.view ?? null, error: r.body.error };
return { signedIn: true, email: auth.email, server: auth.server, view: await saveAccount(r.body) };
}
// ───────────── coins ─────────────
const COIN_ERRORS = {
"not-pump": "No price for this coin: it isn't listed with a price on DexScreener.",
"not-sol": "No price for this coin yet: it isn't paired with SOL, and DexScreener doesn't list it.",
migrating: "This coin is moving to PumpSwap. Trading resumes in a moment.",
graduated: "This coin is moving to Raydium. Trading resumes in a moment.",
"curve-type": "No price for this coin: its launchpad's curve isn't supported yet.",
missing: "Couldn't find this coin on chain.",
};
/** Chain answers that send a coin to its DexScreener pair instead (no curve of ours, or it left its curve for another exchange). */
const DEX_FALLBACK = new Set(["not-pump", "not-sol", "migrating", "graduated", "curve-type"]);
/** How long the panel waits to ask again about an address nobody knows yet (a coin or pool seconds old). */
const MISSING_RETRY_MS = 10_000;
/** The coin (mint) behind an address from a site's URL: a mint, a pump.fun curve or a PumpSwap pool. */
async function resolve(address) {
if (!/^[1-9A-Za-z]{32,44}$/.test(address)) return { error: COIN_ERRORS.missing };
const known = (await session.get("resolved")) ?? {};
if (known[address]?.mint) return known[address];
let mint = null;
try {
// a lowercased DexScreener pair may not even be base58: only DexScreener can tell what it is
const c = isAddress(address) ? await classify(address) : { missing: true };
if (c.mint) mint = c.mint;
else if (c.curve) mint = (await dexMint(address)) ?? (await mintOfCurve(address));
// anything else is another DEX's pool (its coin may still be a pump.fun coin), or an address the
// chain doesn't have, like the lowercased pair addresses in DexScreener's URLs: DexScreener knows both
else mint = await dexMint(address);
} catch {
return { error: "Solana's public RPC isn't answering. Retrying…", retry: true };
}
// only answers are remembered: an address nobody knows yet may be seconds old, so the panel asks again
if (!mint) return { error: COIN_ERRORS.missing, retry: MISSING_RETRY_MS };
await session.set("resolved", { ...known, [address]: { mint } });
return { mint };
}
/** The base coin of a trading pair, from DexScreener's free API. */
async function dexMint(pair) {
try {
const r = await fetch(`https://api.dexscreener.com/latest/dex/pairs/solana/${pair}`, { signal: AbortSignal.timeout(6000) }).then((x) => x.json());
const p = r?.pairs?.[0] ?? r?.pair;
return isAddress(p?.baseToken?.address) ? p.baseToken.address : null;
} catch {
return null;
}
}
const quotes = new Map(); // mint → { at, value | promise }
const dexOnly = new Set(); // coins on no curve of ours (or past it): skip the chain lookup
const noLaunch = new Set(); // coins without a LaunchLab curve paired with another token
async function quote(mint, fresh) {
const c = quotes.get(mint);
// DexScreener's listed price changes slowly; a pool read on chain (or GMGN's price) is as fresh as a curve
const ttl = c?.value?.venue === "dex" && !c.value.chain && !c.value.gmgn ? DEX_QUOTE_TTL_MS : QUOTE_TTL_MS;
if (c && (c.promise || (!fresh && Date.now() - c.at < ttl))) return c.promise ?? c.value;
const promise = (async () => {
let q = { error: "not-pump" };
if (!dexOnly.has(mint)) {
try {
q = await quoteCoin(mint);
if (q.error === "not-pump" || q.error === "graduated") dexOnly.add(mint);
} catch {
return { error: "Solana's public RPC isn't answering. Retrying…", retry: true };
}
}
if (q.error && DEX_FALLBACK.has(q.error)) {
try {
const usd = await solUsd();
const d = await dexQuote(mint, usd, gmgnPrice);
if (d) return { ...d, solUsd: usd, at: Date.now() };
} catch {
return { error: "DexScreener isn't answering. Retrying…", retry: true };
}
}
if (q.error === "not-pump" && !noLaunch.has(mint)) {
// not on DexScreener either: a LaunchLab curve paired with another token? (most of StonkFun's are)
let pool = null;
let known = false;
try {
pool = await findLaunchPool(mint);
known = !!pool;
} catch {
/* ask Funded */
}
if (!pool) {
// the coin hasn't traded lately: the free endpoint keeps no older history, so Funded's server looks
const r = await api(`/api/ext/launch-pool?mint=${mint}`);
if (r.ok) {
pool = r.body.pool ? rememberLaunchPool(mint, r.body.pool) : null;
known = true;
}
}
if (pool) {
dexOnly.delete(mint);
try {
q = await quoteCoin(mint);
} catch {
return { error: "Solana's public RPC isn't answering. Retrying…", retry: true };
}
} else if (known) noLaunch.add(mint);
else return { error: "Couldn't look this coin up. Retrying…", retry: true };
}
if (q.error) return { error: COIN_ERRORS[q.error] ?? q.error, code: q.error };
const usd = await solUsd();
if (q.quoteMint) {
// a curve paired with another token: the panel shows it in SOL; the order sends the curve as read
const per = await quoteTokenSol(q.quoteMint, usd);
if (!per) return { error: "No price for the token this coin is paired with. Retrying…", retry: true };
return { ...q, raw: { pool: q.pool, realSol: q.realSol }, pool: { ...q.pool, quote: q.pool.quote * per }, realSol: q.realSol * per, solUsd: usd, at: Date.now() };
}
return { ...q, solUsd: usd, at: Date.now() };
})().then((q) => withPools(mint, q));
quotes.set(mint, { at: Date.now(), promise });
const value = await promise;
quotes.set(mint, { at: Date.now(), value });
if (quotes.size > 50) quotes.delete(quotes.keys().next().value);
return value;
}
/**
* A quote with the coin's pools and the pair it's priced on: a site's chart may be named after any of them
* (Axiom's after the pool it shows), and the panel passes them to chart.js.
*/
async function withPools(mint, q) {
if (q.error) return q;
let pools = [];
try {
pools = await coinPools(mint, q.quoteMint);
} catch {
/* the coin's own address and the page's still name its chart */
}
return { ...q, pools: q.dex?.pair ? [...pools, q.dex.pair] : pools };
}
const DOLLARS = new Set(["EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"]); // USDC, USDT
const tokenSol = new Map(); // a pairing token's mint → { at, value }
/** GMGN's real-time price for a coin, in SOL, through the Funded server (which holds the key): { price, supply } or null. */
async function gmgnPrice(mint) {
const r = await api(`/api/ext/price?mint=${mint}`);
return r.ok && r.body.price > 0 ? r.body : null;
}
/** SOL per one of a token a pump.fun coin is paired with: dollars at the SOL price, others at GMGN's price, else DexScreener's. */
async function quoteTokenSol(mint, usd) {
if (DOLLARS.has(mint)) return usd ? 1 / usd : null;
const c = tokenSol.get(mint);
if (c && Date.now() - c.at < (c.gmgn ? 5_000 : 30_000)) return c.value;
let value = null;
let gmgn = false;
try {
const g = await gmgnPrice(mint);
if (g) [value, gmgn] = [g.price, true];
else {
const d = await dexQuote(mint, usd);
value = d?.pool ? d.pool.quote / d.pool.base : null;
}
} catch {
/* no price this time */
}
if (value) tokenSol.set(mint, { at: Date.now(), value, gmgn });
return value ?? c?.value ?? null;
}
let sol = { at: 0, usd: null };
async function solUsd() {
if (Date.now() - sol.at < 60_000) return sol.usd;
sol.at = Date.now();
try {
const r = await fetch("https://api.coinbase.com/v2/prices/SOL-USD/spot", { signal: AbortSignal.timeout(5000) }).then((x) => x.json());
const v = Number(r?.data?.amount);
if (v > 0) sol.usd = v;
} catch {
/* keep the last price */
}
return sol.usd;
}
/** Name, ticker and logo: pump.fun's own listing, then DexScreener, then the mint's on-chain metadata. */
async function meta(mint) {
const known = (await session.get("meta")) ?? {};
if (known[mint]) return known[mint];
let m = null;
try {
const r = await fetch(`https://frontend-api-v3.pump.fun/coins/${mint}`, { signal: AbortSignal.timeout(5000) }).then((x) => x.json());
if (r?.symbol) m = { symbol: r.symbol, name: r.name ?? r.symbol, image: typeof r.image_uri === "string" && r.image_uri.startsWith("https://") ? r.image_uri : undefined };
} catch {
/* try the next source */
}
if (!m) {
try {
const r = await fetch(`https://api.dexscreener.com/tokens/v1/solana/${mint}`, { signal: AbortSignal.timeout(5000) }).then((x) => x.json());
const p = Array.isArray(r) ? r.find((x) => x?.baseToken?.address === mint) : null;
if (p) m = { symbol: p.baseToken.symbol, name: p.baseToken.name, image: p.info?.imageUrl };
} catch {
/* try the next source */
}
}
if (!m) {
try {
const md = await mintMetadata(mint);
if (md?.symbol) m = { symbol: md.symbol, name: md.name || md.symbol };
} catch {
/* no name: the panel shows the address */
}
}
if (m) await session.set("meta", { ...known, [mint]: m });
return m;
}
// ───────────── trading ─────────────
/**
* A click, for the account of `mode`: the server refuses it if the trader has switched modes since. `idem`:
* the ID of an earlier, identical click whose answer was lost, so if that one went through this one gets
* its result instead of a second fill.
*/
async function order({ mint, side, sol: amount, pct, mode, idem: earlier }) {
const q = await quote(mint, true);
if (q.error) return { error: q.error };
const coin = await meta(mint);
// other coins: the server prices the fill from DexScreener itself; a curve paired with another token
// goes as read, in that token, and the server converts it
const priced = q.venue === "dex" ? { venue: "dex" } : q.raw ? { venue: q.venue, pool: q.raw.pool, realSol: q.raw.realSol, quoteMint: q.quoteMint } : { venue: q.venue, pool: q.pool, realSol: q.realSol };
const body = { mint, side, ...(side === "buy" ? { sol: amount } : { pct }), quote: priced, coin, solUsd: q.solUsd ?? undefined, mode: mode === "practice" ? "practice" : "challenge" };
const idem = typeof earlier === "string" && /^[0-9a-f-]{36}$/.test(earlier) ? earlier : crypto.randomUUID();
let r = await api("/api/ext/order", { method: "POST", body, idem });
// a dropped connection: retry once with the same ID (the server never fills twice)
if (r.status === 0) r = await api("/api/ext/order", { method: "POST", body, idem });
// no answer either time: it may have gone through all the same (the panel checks)
if (r.status === 0) return { error: r.body.error, unconfirmed: true, idem };
if (!r.ok) return { error: r.body.error ?? "Order failed", signedOut: !!r.body.signedOut };
await saveAccount(r.body.account);
return { ok: true, trade: r.body.trade, view: r.body.account };
}
async function simple(path, body) {
const r = await api(path, { method: "POST", body: body ?? {} });
if (!r.ok) return { error: r.body.error ?? "Something went wrong" };
return { ok: true, view: await saveAccount(r.body) };
}
// ───────────── messages ─────────────
const SOUND_KEYS = { buy: "soundBuy", sell: "soundSell" };
const SOUND_VOLUME = 25;
// (1 MB, as base64)
const SOUND_MAX_CHARS = 1_400_000;
/** The trader's own buy and sell sounds and their volume, set on the /extension page: read, or changed first. panel.js plays them. */
async function sounds({ set, clear, volume }) {
if (set) {
const key = SOUND_KEYS[set.side];
if (!key || typeof set.data !== "string" || !set.data || set.data.length > SOUND_MAX_CHARS || !/^[A-Za-z0-9+/]+=*$/.test(set.data)) return { error: "That file can't be used." };
await chrome.storage.local.set({ [key]: { name: String(set.name ?? "").slice(0, 100) || "Your sound", data: set.data } }).catch(() => {
throw new Error("Couldn't save that sound. Try a smaller file.");
});
}
if (SOUND_KEYS[clear]) await local.remove(SOUND_KEYS[clear]);
if (volume !== undefined) {
if (!(Number.isFinite(volume) && volume >= 0 && volume <= 100)) return { error: "That volume can't be used." };
await local.set("soundVolume", volume);
}
const s = await chrome.storage.local.get(["soundBuy", "soundSell", "soundVolume"]);
return { buy: s.soundBuy ?? null, sell: s.soundSell ?? null, volume: s.soundVolume ?? SOUND_VOLUME };
}
const handlers = {
sounds,
resolve: (m) => resolve(m.address),
quote: (m) => quote(m.mint, m.fresh),
meta: (m) => meta(m.mint),
account: (m) => account(m.force, m.mint),
order: (m) => order(m),
refill: (m) => simple("/api/ext/refill", { mode: m.mode === "practice" ? "practice" : "challenge", mint: m.mint }),
mode: (m) => simple("/api/ext/mode", { mode: m.mode === "practice" ? "practice" : "challenge", mint: m.mint }),
signout: async () => {
await api("/api/ext/logout", { method: "POST" });
await local.remove(["auth", "account"]);
return { ok: true };
},
openConnect: async () => {
const auth = await local.get("auth");
await chrome.tabs.create({ url: `${auth?.server ?? DEFAULT_SERVER}/extension?connect=1` });
return { ok: true };
},
openSite: async (m) => {
const auth = await local.get("auth");
await chrome.tabs.create({ url: `${auth?.server ?? DEFAULT_SERVER}${m.path ?? "/dashboard"}` });
return { ok: true };
},
};
chrome.runtime.onMessage.addListener((msg, sender, reply) => {
// the site hands over a sign-in: only from Funded's own pages (where bridge.js runs)
if (msg?.type === "connect") {
const origin = sender.origin ?? (sender.url ? new URL(sender.url).origin : "");
if (!SITE_ORIGINS.includes(origin) || typeof msg.token !== "string" || !/^[A-Za-z0-9_-]{20,100}$/.test(msg.token)) {
reply({ error: "Not allowed" });
return false;
}
(async () => {
await local.set("auth", { token: msg.token, email: String(msg.email ?? ""), server: origin.replace("://www.", "://") });
await local.remove("account");
reply(await account(true));
})();
return true;
}
if (msg?.type === "status") {
(async () => {
const auth = await local.get("auth");
reply({ signedIn: !!auth, email: auth?.email ?? null, version: chrome.runtime.getManifest().version });
})();
return true;
}
const h = handlers[msg?.type];
if (!h || sender.id !== chrome.runtime.id) return false;
h(msg)
.then(reply)
.catch((e) => reply({ error: e?.message ?? "Something went wrong" }));
return true;
});
// Funded extension, on Funded's own site only: lets the /extension page see that the extension is
// installed, and hand it a sign-in made while the trader is logged in. Messages are accepted only from
// this page itself (same window, same origin); the token goes straight to the extension's background.
"use strict";
(() => {
const version = chrome.runtime.getManifest().version;
const post = (data) => window.postMessage({ source: "funded-extension", ...data }, location.origin);
/**
* Ask the background page; `then` gets its answer, or null when it couldn't answer this time. Once this copy
* of the extension has been replaced (reloaded or updated while the page stayed open), Chrome refuses: the
* page is told once, to reload, and nothing more is asked.
*/
const ask = (msg, then) => {
try {
chrome.runtime.sendMessage(msg, (r) => then(chrome.runtime.lastError ? null : (r ?? {})));
} catch {
window.removeEventListener("message", onMessage);
post({ type: "stale" });
}
};
function onMessage(e) {
if (e.source !== window || e.origin !== location.origin) return;
const m = e.data;
if (!m || m.source !== "funded-site") return;
if (m.type === "ping") {
// (no answer this time: the page asks again in a moment)
ask({ type: "status" }, (s) => s && post({ type: "pong", version, signedIn: !!s.signedIn, email: s.email ?? null }));
} else if (m.type === "sounds") {
// the page reads or changes the trader's buy and sell sounds (checked in the background; they stay in this browser)
ask({ type: "sounds", set: m.set, clear: m.clear, volume: m.volume }, (r) => post({ type: "sounds", ...(r ?? { error: "Couldn't reach the extension. Try again." }) }));
} else if (m.type === "connect" && typeof m.token === "string") {
ask({ type: "connect", token: m.token, email: m.email }, (r) => post({ type: "connected", ok: !!r?.signedIn, email: r?.email ?? null, error: r ? (r.error ?? null) : "Couldn't reach the extension. Try again." }));
}
}
window.addEventListener("message", onMessage);
post({ type: "ready", version });
})();
// Funded extension: draws the trader's Funded paper trades on the trading site's own TradingView chart,
// like a trading site shows real trades: a B or S bubble over the candle of each buy and sell (the
// chart's own trade marks: the site's chart asks its data source for marks, and ours are added to the
// site's answer, which passes through untouched), stacked when a candle has several, and dashed lines at
// the average entry and exit. A chart that doesn't ask for marks gets B and S markers drawn on it
// instead. It runs in the page (that's where the chart and its drawing tools are) and only draws:
// panel.js sends it what to draw, and the one thing it reads is the chart's latest candle, to place the
// lines in whatever the chart plots (price or market cap, in SOL or USD). It sends nothing anywhere.
"use strict";
(() => {
if (window.top !== window || window.__fundedChart) return;
window.__fundedChart = true;
const COLORS = { buy: "#82d4a5", sell: "#f2909c" };
/** Trade bubbles: green B and red S with a light ring and a white letter, like the sites' own. */
const BUBBLE = { buy: "#22c55e", sell: "#ef4444", ring: "#5ec8ff", letter: "#ffffff", size: 22 };
/** What to draw (from panel.js), or null for nothing, and when it came. */
let want = null;
let wantAt = 0;
/** chart frame → what's drawn on it */
const drawn = new Map();
// panel.js posts { source: "funded-panel", type: "chart", payload } from this same page
window.addEventListener("message", (e) => {
if (e.source !== window || e.data?.source !== "funded-panel" || e.data.type !== "chart") return;
want = valid(e.data.payload) ? e.data.payload : null;
wantAt = Date.now();
sync();
});
const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
const optNum = (v) => v === undefined || v === null || num(v);
function valid(p) {
return (
!!p &&
typeof p.mint === "string" &&
(p.pools === undefined || (Array.isArray(p.pools) && p.pools.length <= 8 && p.pools.every((a) => typeof a === "string" && a.length >= 32 && a.length <= 44))) &&
// (no price: the bubbles still go on, the lines stay where they are)
optNum(p.spot) &&
Array.isArray(p.fills) &&
p.fills.length <= 200 &&
p.fills.every((f) => num(f.t) && num(f.price) && optNum(f.usd) && (f.side === "buy" || f.side === "sell")) &&
[p.avgEntry, p.avgExit, p.avgEntryUsd, p.avgExitUsd, p.supply, p.solUsd].every(optNum)
);
}
/** The site's TradingView charts: the library draws each one in a frame of the same site that holds its API. */
function charts() {
return [...document.querySelectorAll("iframe")].filter((f) => {
try {
return !!f.contentWindow?.tradingViewApi;
} catch {
return false; // another site's frame
}
});
}
/** A chart's symbol as text in upper case: some sites write it in upper case (Axiom, pump.fun), some as hex (DexScreener). */
function symbolText(symbol) {
let s = String(symbol ?? "");
if (/^[0-9A-F]+$/i.test(s) && s.length % 2 === 0 && s.length > 64) {
s = s.replace(/../g, (h) => String.fromCharCode(parseInt(h, 16)));
}
return s.toUpperCase();
}
/**
* What a chart's symbol (ticker, name…) names: this coin ("coin": the coin, the page's pair or one of the
* coin's pools, such as its curve, the PumpSwap pool it moved to, the pair it's priced on), another one
* ("other"), or no address at all ("none"). Compared in upper case, where an address's i, o and l read as
* I, O and L (not base58: any run of 32 or more letters and digits may be one).
*/
const ADDRESS_LIKE = /[1-9A-Z]{32,}/;
function named(names) {
const texts = names.map(symbolText);
const mine = [want.mint, want.address, ...(want.pools ?? [])].filter(Boolean).map((a) => a.toUpperCase());
if (texts.some((t) => mine.some((a) => t.includes(a)))) return "coin";
return texts.some((t) => ADDRESS_LIKE.test(t)) ? "other" : "none";
}
/** A chart of this coin, or one whose symbol names no coin at all. */
const ours = (names) => named(names) !== "other";
/** How far (as a factor) the chart's close may sit from the panel's price and still read as that unit. */
const UNIT_SLACK = Math.log(1.5);
/** A chart in none of our units: its ratio is the median of this many looks, redrawn only past this far. */
const RAW_LOOKS = 9;
const RAW_SLACK = Math.log(1.2);
/**
* What the chart plots: a price in SOL ("sol") or in dollars ("usd"), a market cap in SOL ("mcSol") or
* in dollars ("mcUsd"), or none of those ("raw": its close over the panel's price, followed loosely).
* Told apart by the chart's latest close against the panel's own price: those units are a hundred
* times or more apart, so a fast candle, or the chart and the panel updating a moment apart, can't mix
* them up. Once found, the unit stays, with the supply and SOL price it was found at, so the marks stay
* where they are while the price moves; it changes only when the chart reads as another unit twice in
* a row (the site switched what it plots).
*/
function lookAt(close, prev) {
const seen = close / want.spot;
const { solUsd, supply } = want;
const units = [
{ kind: "sol", per: 1 },
{ kind: "usd", per: solUsd, solUsd },
{ kind: "mcSol", per: supply, supply },
{ kind: "mcUsd", per: supply && solUsd ? supply * solUsd : null, supply, solUsd },
].filter((u) => num(u.per));
let best = null;
for (const u of units) {
const off = Math.abs(Math.log(seen / u.per));
if (off < UNIT_SLACK && (!best || off < best.off)) best = { ...u, off };
}
const found = best ? { kind: best.kind, solUsd: best.solUsd ?? null, supply: best.supply ?? null } : { kind: "raw", ratio: seen };
const was = prev?.unit;
if (!was) return { unit: found, pending: null, raws: [seen] };
if (found.kind === was.kind) {
if (was.kind !== "raw") return { unit: was, pending: null, raws: [] };
// none of our units: the median of the last few looks, and only when it has moved
const raws = [...prev.raws, seen].slice(-RAW_LOOKS);
const median = [...raws].sort((a, b) => a - b)[raws.length >> 1];
return { unit: Math.abs(Math.log(median / was.ratio)) > RAW_SLACK ? { kind: "raw", ratio: median } : was, pending: null, raws };
}
// reads as another unit: switch on the second look in a row
if (prev.pending === found.kind) return { unit: found, pending: null, raws: [seen] };
return { ...prev, pending: found.kind };
}
/** The chart's latest close, or null while it has none (still loading its coin, or no way to read it). */
async function latestClose(chart) {
try {
const d = await chart.exportData({ includeTime: false, includeSeries: true, includedStudies: [], from: Math.floor(Date.now() / 1000) - 7 * 86400 });
const row = d.data[d.data.length - 1];
const close = row?.[row.length - 1];
return num(close) ? close : null;
} catch {
return null;
}
}
/**
* Where a price lands on the chart: `sol` SOL per token, `usd` its dollar price when it happened (a fill
* or an average of fills at their own SOL prices; else the SOL price the unit was found at).
*/
function place(unit, sol, usd) {
const dollars = () => (num(usd) ? usd : sol * unit.solUsd);
if (unit.kind === "sol") return sol;
if (unit.kind === "usd") return dollars();
if (unit.kind === "mcSol") return sol * unit.supply;
if (unit.kind === "mcUsd") return dollars() * unit.supply;
return sol * unit.ratio;
}
// ───────────── trade bubbles: the chart's own marks ─────────────
/** How long the site's own marks may take before ours go without them (the chart takes one answer per request). */
const SITE_MARKS_WAIT_MS = 3000;
/** How long a chart has to ask for marks before it gets markers drawn instead. */
const PROBE_MS = 3000;
/** A data source whose chart didn't ask it for marks is asked again after this long (it may have been busy). */
const REPROBE_MS = 30_000;
/** The site's data source → how often its chart has asked it for marks since we joined in. */
const hooks = new WeakMap();
/** The site's data source → whether its chart shows our trades as marks, and when that was found. */
const probed = new WeakMap();
/** The site's last marks for each symbol: what goes with ours when its answer is slow (a slow connection). */
const siteMarks = new Map();
const symbolKey = (symbolInfo) => String(symbolInfo?.ticker ?? symbolInfo?.full_name ?? symbolInfo?.name ?? "");
/** The site's last marks for this symbol that fall between `from` and `to` (seconds). */
function lastSiteMarks(key, from, to) {
return (siteMarks.get(key) ?? []).filter((m) => !(typeof m?.time === "number") || (m.time >= from && m.time <= to));
}
/** The data source of the chart in this frame, where TradingView's widget keeps it (window[the frame's id]). */
function feedOf(frame) {
try {
const feed = (window[frame.id] ?? window[frame.name])?.datafeed;
return typeof feed?.getMarks === "function" ? feed : null;
} catch {
return null;
}
}
/**
* Join the data source's answer to the chart's requests for marks: the site's marks, then ours for this
* coin. The chart takes the first answer to each request, so ours wait for the site's; if it hasn't
* answered in a few seconds, they go with the site's last marks for the coin (the first time there are
* none, the chart is asked again once the late answer is in).
*/
function hookFeed(feed) {
let h = hooks.get(feed);
if (h) return h;
h = { calls: 0, chart: null };
hooks.set(feed, h);
const theirs = feed.getMarks;
try {
feed.getMarks = function (symbolInfo, from, to, onData, resolution) {
h.calls++;
// a chart that asks after its probe gave up on it (a busy computer) shows marks after all: bubbles,
// and the markers drawn meanwhile go
const seen = probed.get(feed);
if (seen && !seen.ok) {
probed.set(feed, { ok: true, at: Date.now() });
soon();
}
const mine = bubblesFor(symbolInfo);
if (!mine.length) return theirs.call(this, symbolInfo, from, to, onData, resolution);
const key = symbolKey(symbolInfo);
let sent = false;
const send = (list) => {
if (sent) return false;
sent = true;
onData([...list, ...mine]);
return true;
};
setTimeout(() => send(lastSiteMarks(key, from, to)), SITE_MARKS_WAIT_MS);
try {
theirs.call(
this,
symbolInfo,
from,
to,
(list) => {
const marks = Array.isArray(list) ? list : [];
const had = siteMarks.has(key);
siteMarks.delete(key);
siteMarks.set(key, marks);
if (siteMarks.size > 20) siteMarks.delete(siteMarks.keys().next().value);
if (!send(marks) && !had && marks.length) safe(() => h.chart?.refreshMarks());
},
resolution,
);
} catch {
send(lastSiteMarks(key, from, to));
}
};
} catch {
/* the site's data source can't be changed: markers instead */
}
return h;
}
/** Our trades as the chart's marks: a B or S bubble over the candle each one happened in, the oldest nearest it. */
function bubblesFor(symbolInfo) {
if (!want || !ours([symbolInfo?.ticker, symbolInfo?.name, symbolInfo?.full_name])) return [];
const label = want.mode === "practice" ? "Practice" : "Funded";
return want.fills.slice(-100).map((f, i) => {
const buy = f.side === "buy";
return {
id: `funded-${f.t}-${i}`,
time: Math.floor(f.t / 1000),
color: { border: BUBBLE.ring, background: buy ? BUBBLE.buy : BUBBLE.sell },
label: buy ? "B" : "S",
labelFontColor: BUBBLE.letter,
text: tipOf(f, label),
minSize: BUBBLE.size,
};
});
}
/**
* Does this chart show our trades as marks? It does if it asks its data source for marks when told to refresh
* them. Asked once per data source (a site that rebuilds its chart, for another coin, has a new one to join),
* and again a while after a no.
*/
async function bubblesOn(feed, chart) {
if (!feed) return false;
const seen = probed.get(feed);
if (seen && (seen.ok || Date.now() - seen.at < REPROBE_MS)) return seen.ok;
const h = hookFeed(feed);
h.chart = chart;
const before = h.calls;
safe(() => chart.refreshMarks());
for (let waited = 0; waited < PROBE_MS && h.calls === before; waited += 200) await new Promise((r) => setTimeout(r, 200));
const ok = h.calls > before;
probed.set(feed, { ok, at: Date.now() });
return ok;
}
let syncing = false;
let again = false;
async function sync() {
if (syncing) return void (again = true);
syncing = true;
try {
const frames = charts();
for (const [f, d] of drawn) {
if (!frames.includes(f)) {
clear(d);
drawn.delete(f);
}
}
for (const f of frames) await drawOn(f);
// the site may build the coin's chart a few seconds after the panel's first word (pump.fun does): look again
// sooner than every few seconds for a while
if (want && Date.now() - wantAt < FIND_CHART_MS && !frames.some((f) => drawn.has(f))) soon();
} finally {
syncing = false;
if (again) {
again = false;
sync();
}
}
}
// the site may rebuild its chart, or change coin, interval or units: look again every few seconds
setInterval(() => want && sync(), 4000);
// (sooner while a chart is still loading)
let soonTimer = null;
const soon = () => {
soonTimer ??= setTimeout(() => {
soonTimer = null;
if (want) sync();
}, 1000);
};
/** Looks at a chart whose candles can't be read (but whose name is this coin's) before marking it anyway. */
const LOAD_LOOKS = 3;
/** How long after the panel's word a chart of the coin is looked for every second, before every few seconds. */
const FIND_CHART_MS = 30_000;
async function drawOn(frame) {
let chart;
try {
chart = frame.contentWindow.tradingViewApi.activeChart();
} catch {
return;
}
const prev = drawn.get(frame);
const symbol = safe(() => chart.symbol());
const names = want ? named([symbol]) : "other";
if (names === "other") {
if (prev) {
clear(prev);
// ask the chart for its marks again: without ours this time
if (prev.marksKey) safe(() => chart.refreshMarks());
}
drawn.delete(frame);
return;
}
const entry = prev ?? { items: [], waits: 0 };
drawn.set(frame, entry);
// a chart still loading its coin (Axiom's is named " Loading " at first) can't say yet whether it shows marks:
// look again shortly. One whose candles can't be read goes ahead once its name has been this coin's a while.
const close = await latestClose(chart);
if (!want) return;
if (close !== null) entry.waits = 0;
else if (!(names === "coin" && ++entry.waits >= LOAD_LOOKS)) return void soon();
const feed = feedOf(frame);
const bubbles = await bubblesOn(feed, chart);
if (!want) return;
if (bubbles) {
// the trades are marks: the chart asks for them again when they change (or its data source is a new one)
const marksKey = JSON.stringify([symbol, want.fills, want.mode]);
if (marksKey !== entry.marksKey || chart !== entry.marksChart || feed !== entry.marksFeed) {
Object.assign(entry, { marksKey, marksChart: chart, marksFeed: feed });
safe(() => chart.refreshMarks());
}
}
// the lines (and markers) go where the chart plots the panel's price: without one, they stay as they are
if (close === null || !num(want.spot)) return;
// a new symbol may plot something else: find its unit afresh
const look = lookAt(close, entry.symbol === symbol ? entry.look : null);
const { unit } = look;
const key = JSON.stringify([symbol, safe(() => chart.resolution()), unit, bubbles ? null : want.fills, want.avgEntry, want.avgExit, want.avgEntryUsd, want.avgExitUsd, want.mode]);
if (entry.key === key && entry.chart === chart) {
entry.look = look;
return;
}
clear(entry);
Object.assign(entry, { key, look, symbol, chart });
const items = entry.items;
const label = want.mode === "practice" ? "Practice" : "Funded";
try {
if (!bubbles) for (const f of want.fills.slice(-100)) items.push(await marker(chart, f, place(unit, f.price, f.usd), label));
if (num(want.avgEntry)) items.push(await line(chart, place(unit, want.avgEntry, want.avgEntryUsd), `Avg entry · ${label}`, COLORS.buy));
if (num(want.avgExit)) items.push(await line(chart, place(unit, want.avgExit, want.avgExitUsd), `Avg exit · ${label}`, COLORS.sell));
} catch {
// the chart wasn't ready for them, or went away mid-draw: the next look starts over
clear(entry);
entry.key = null;
}
}
const safe = (fn) => {
try {
return fn();
} catch {
return null;
}
};
const fmtSol = (v) => `${v >= 1 ? v.toFixed(2) : v.toFixed(3)} SOL`;
const tipOf = (f, label) => `${label} paper ${f.side === "buy" ? "buy" : "sell"}${num(f.sol) ? `: ${fmtSol(f.sol)}` : ""}`;
/**
* Charts on TradingView's free edition have the trading markers and order lines as
* functions that throw "only available on Trading Platform": those get plain arrows and lines instead.
*/
const plain = new WeakSet();
const trading = (chart, fn) => !plain.has(chart) && typeof chart[fn] === "function";
/** A B or S marker at the fill's time, at `price` on the chart (charts that don't ask for marks). */
async function marker(chart, f, price, label) {
const buy = f.side === "buy";
const tip = tipOf(f, label);
const time = Math.floor(f.t / 1000);
if (trading(chart, "createExecutionShape")) {
try {
const ex = await chart.createExecutionShape({ disableUndo: true });
ex.setText(buy ? "B" : "S").setTooltip(tip).setTextColor(COLORS[f.side]).setArrowColor(COLORS[f.side]).setDirection(f.side).setTime(time).setPrice(price);
return { remove: () => ex.remove() };
} catch {
plain.add(chart);
}
}
const id = await chart.createShape({ time, price }, { shape: buy ? "arrow_up" : "arrow_down", text: buy ? "B" : "S", lock: true, disableSelection: true, disableSave: true, disableUndo: true, overrides: { color: COLORS[f.side] } });
return { remove: () => chart.removeEntity(id) };
}
/** A dashed level across the chart, labelled at the right like the site's own order lines. */
async function line(chart, price, text, color) {
if (trading(chart, "createOrderLine")) {
try {
const l = await chart.createOrderLine({ disableUndo: true });
l.setPrice(price).setText(text).setQuantity("").setEditable(false).setCancellable(false).setLineStyle(2).setLineColor(color).setBodyBorderColor(color).setBodyTextColor(color).setBodyBackgroundColor("rgba(15,19,17,0.92)").setQuantityBorderColor(color).setQuantityBackgroundColor(color);
return { remove: () => l.remove() };
} catch {
plain.add(chart);
}
}
const id = await chart.createShape({ price }, { shape: "horizontal_line", lock: true, disableSelection: true, disableSave: true, disableUndo: true, overrides: { linecolor: color, linestyle: 2, linewidth: 1, showLabel: true, text, textcolor: color, horzLabelsAlign: "right" } });
return { remove: () => chart.removeEntity(id) };
}
function clear(d) {
for (const it of d.items) safe(() => it?.remove());
d.items = [];
}
})();
// Funded extension: coins outside pump.fun. DexScreener's free API says which pair a coin trades on; a
// Raydium or Meteora pool is then priced from its own accounts on chain (pools.js, every quote), any other
// pair at GMGN's real-time price through the Funded server (when it has a GMGN key), else at DexScreener's
// listed price (which refreshes about every 25 seconds). The Funded server prices the fill itself, the same
// way, when the trader clicks (src/lib/dex.ts, which this mirrors), and checks it against the pair's real
// swaps later.
import { accounts } from "./solana.js";
import { poolPrice, POOL_PROGRAMS, readMint, readPool, readTokenAccount } from "./pools.js";
const WSOL_MINT = "So11111111111111111111111111111111111111112";
const USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const QUOTES = { [WSOL_MINT]: "SOL", [USDC_MINT]: "USDC" };
/** A SOL or USDC pair is picked over a deeper one in another token while it's at least this share of its depth. */
const PREFER_DIRECT = 0.5;
const NOT_COINS = new Set([WSOL_MINT, USDC_MINT, "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"]);
/** pump.fun's curve: SOL × tokens per token of supply (a launchpad curve listed without liquidity is priced like one). */
const CURVE_K_PER_TOKEN = 30 * 1.073;
/** Which pair a coin trades on changes rarely: DexScreener is asked again after this long (sooner while it lists none). */
const PAIR_TTL_MS = 30_000;
const NO_PAIR_TTL_MS = 5_000;
/** A chain price this many times off DexScreener's (either way) is taken for a misread pool. */
const CHAIN_SANITY = 20;
const listedLiq = (p) => (Number.isFinite(p?.liquidity?.usd) ? p.liquidity.usd : null);
const liq = (p) => listedLiq(p) ?? (p.marketCap || p.fdv || 0);
/** A pool at least this deep (USD) created after a curve is the one the curve moved into. */
const MIN_LIQUIDITY_USD = 1_000;
/** A curve listed without liquidity that the coin has left for a pool created after it (it keeps its last price). */
function finishedCurve(p, coinPairs) {
if (listedLiq(p) !== null || !p.pairCreatedAt) return false;
return coinPairs.some((q) => q !== p && (listedLiq(q) ?? 0) >= MIN_LIQUIDITY_USD && (q.pairCreatedAt ?? 0) > p.pairCreatedAt);
}
/**
* The coin's most liquid SOL or USDC pair, unless one in another token (a tokenized stock, ZEC…: StonkFun
* pairs coins with those) with a USD price is more than twice as deep. Never a pump.fun curve (those are
* priced from the chain) or a finished launchpad curve.
*/
export function pickPair(pairs, mint) {
if (!Array.isArray(pairs) || NOT_COINS.has(mint)) return null;
const coinPairs = pairs.filter((p) => p?.baseToken?.address === mint);
let best = null;
let bestDirect = null;
for (const p of coinPairs) {
if (!p.quoteToken?.address || p.dexId === "pumpfun" || finishedCurve(p, coinPairs)) continue;
if (!(Number(p.priceNative) > 0) || !p.pairAddress) continue;
const direct = !!QUOTES[p.quoteToken.address];
if (!direct && !(Number(p.priceUsd) > 0)) continue;
if (!best || liq(p) > liq(best)) best = p;
if (direct && (!bestDirect || liq(p) > liq(bestDirect))) bestDirect = p;
}
return bestDirect && (bestDirect === best || liq(bestDirect) >= liq(best) * PREFER_DIRECT) ? bestDirect : best;
}
const bestPairs = new Map(); // mint → { at, pair }
/** Launchpad curves the chain says are finished (pools.js) → their coin: DexScreener keeps listing them for a while. */
const finished = new Map();
/** The coin's best pair on DexScreener (cached), never a curve the chain says is finished, or null. */
async function bestPair(mint) {
const hit = bestPairs.get(mint);
if (hit && Date.now() - hit.at < (hit.pair ? PAIR_TTL_MS : NO_PAIR_TTL_MS)) return hit.pair;
const list = await fetch(`https://api.dexscreener.com/token-pairs/v1/solana/${mint}`, { signal: AbortSignal.timeout(6000) }).then((r) => (r.ok ? r.json() : null));
const pair = pickPair(Array.isArray(list) ? list.filter((p) => !finished.has(p?.pairAddress)) : list, mint);
bestPairs.set(mint, { at: Date.now(), pair });
if (bestPairs.size > 50) bestPairs.delete(bestPairs.keys().next().value);
return pair;
}
const layouts = new Map(); // pair → { vaults, decimals }, or null: not a pool read on chain
/**
* The coin's price on a Raydium or Meteora pool from the chain: { quoteMint, price, side } (pools.js),
* "finished" for a launchpad curve the coin has left, or null.
*/
async function chainPrice(pair, mint) {
let layout = layouts.get(pair);
if (layout === null) return null;
if (!layout) {
const [a] = await accounts([pair]);
const pool = a && POOL_PROGRAMS.has(a.owner) ? readPool(a.owner, a.data) : null;
if (!pool) {
layouts.set(pair, null);
return null;
}
if (pool.finished) return "finished";
const vaults = await accounts(pool.vaults);
const quoteMint = pool.mints[1] ?? readTokenAccount(vaults[1]?.data)?.mint;
if (!quoteMint) return null;
const decimals = pool.decimals ?? (await accounts([pool.mints[0], quoteMint])).map((m) => readMint(m?.data)?.decimals);
if (decimals.some((d) => d === undefined)) return null;
layout = { vaults: pool.vaults, decimals };
layouts.set(pair, layout);
}
const [a, v0, v1] = await accounts([pair, ...layout.vaults]);
const pool = a ? readPool(a.owner, a.data) : null;
if (pool?.finished) return "finished";
return pool ? poolPrice(pool, mint, [readTokenAccount(v0?.data), readTokenAccount(v1?.data)], layout.decimals) : null;
}
/**
* The coin's price on its best pair as { venue: "dex", pool: { base, quote, maxBuy: null }, supply, dex,
* chain | gmgn } in tokens and SOL, or null; `chain`: read from the pool on chain, `gmgn`: GMGN's price
* (`gmgn(mint)` asks the Funded server: { price: SOL per coin, supply } or null), else DexScreener's
* listing. `solUsd` converts USDC pairs and other tokens' (through their USD price); without it only SOL
* pairs work. { error } for a coin that just left its launchpad curve, until DexScreener lists its new pool.
*/
export async function dexQuote(mint, solUsd, gmgn) {
const p = await bestPair(mint);
if (!p) return [...finished.values()].includes(mint) ? { error: "This coin just moved to its new pool. Trading resumes in a moment." } : null;
const quote = QUOTES[p.quoteToken.address] ?? p.quoteToken.symbol ?? "?";
// a SOL pair prices SOL too (its USD price over its SOL price)
if (!solUsd && quote === "SOL") solUsd = Number(p.priceUsd) / Number(p.priceNative) || null;
const native = Number(p.priceNative);
const price = quote === "SOL" ? native : !solUsd ? NaN : quote === "USDC" ? native / solUsd : Number(p.priceUsd) / solUsd;
if (!(price > 0)) return null;
const usd = Number(p.priceUsd);
const cap = p.marketCap || p.fdv;
const supply = cap && usd > 0 ? cap / usd : null;
const listed = listedLiq(p);
const side = listed !== null ? (solUsd ? listed / 2 / solUsd : null) : Math.sqrt(CURVE_K_PER_TOKEN * (supply ?? 1e9) * price);
if (!(side > 0)) return null;
const dex = { pair: p.pairAddress, dexId: p.dexId, quote };
// the pool's own price, in SOL as the server converts it (USDC at the SOL price, other tokens at their USD price)
let c = null;
try {
c = await chainPrice(p.pairAddress, mint);
} catch {
/* no answer: DexScreener's price this time */
}
if (c === "finished") {
// the coin's next best pair, as the server fills it, never the curve's last price
finished.set(p.pairAddress, mint);
if (finished.size > 50) finished.delete(finished.keys().next().value);
bestPairs.delete(mint);
return dexQuote(mint, solUsd, gmgn);
}
const perQuote = quote === "SOL" ? 1 : !solUsd ? 0 : quote === "USDC" ? 1 / solUsd : Number(p.priceUsd) / native / solUsd;
const cp = c && c.quoteMint === p.quoteToken.address ? c.price * perQuote : 0;
if (cp > 0 && cp < price * CHAIN_SANITY && cp > price / CHAIN_SANITY) {
const cs = c.side !== null ? c.side * perQuote : Math.sqrt(CURVE_K_PER_TOKEN * (supply ?? 1e9) * cp);
if (cs > 0) return { venue: "dex", pool: { base: cs / cp, quote: cs, maxBuy: null }, supply, dex, chain: true };
}
// not a pool read on chain: GMGN's real-time price, at DexScreener's depth (as the server fills it)
let g = null;
try {
g = gmgn ? await gmgn(mint) : null;
} catch {
/* no answer: DexScreener's price this time */
}
const gp = g?.price;
if (gp > 0 && gp < price * CHAIN_SANITY && gp > price / CHAIN_SANITY) return { venue: "dex", pool: { base: side / gp, quote: side, maxBuy: null }, supply: g.supply ?? supply, dex, gmgn: true };
return { venue: "dex", pool: { base: side / price, quote: side, maxBuy: null }, supply, dex };
}
// Funded extension, and the Funded server (which imports this file so both price a coin the same way):
// a Raydium or Meteora pool's price, read from its accounts on chain instead of DexScreener's API (which
// refreshes about every 25 seconds). Pure: bytes in, numbers out; the callers fetch the accounts.
//
// One pool read is the pool account, then its two vaults (token accounts) and, where the pool doesn't
// store them, the two mints' decimals. Constant-product pools (Raydium's AMM v4 and CPMM) are priced on
// their reserves; concentrated ones (Raydium CLMM, Meteora DLMM and DAMM v2) on the price in their state,
// with the pair's value split evenly on each side as depth (as DexScreener-priced pairs always were);
// Meteora's launchpad curves (DBC) on the price in their state, the caller sizing them like a pump.fun curve.
export const RAYDIUM_AMM = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
export const RAYDIUM_CPMM = "CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C";
export const RAYDIUM_CLMM = "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK";
export const METEORA_DLMM = "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo";
export const METEORA_DAMM2 = "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG";
export const METEORA_DBC = "dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN";
/** The programs whose pools are read here (any other pair stays on DexScreener's price). */
export const POOL_PROGRAMS = new Set([RAYDIUM_AMM, RAYDIUM_CPMM, RAYDIUM_CLMM, METEORA_DLMM, METEORA_DAMM2, METEORA_DBC]);
const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
function base58(bytes) {
let n = 0n;
for (const b of bytes) n = n * 256n + BigInt(b);
let out = "";
while (n > 0n) {
out = B58[Number(n % 58n)] + out;
n /= 58n;
}
for (const b of bytes) {
if (b !== 0) break;
out = "1" + out;
}
return out;
}
const dv = (b) => new DataView(b.buffer, b.byteOffset, b.byteLength);
const key = (b, o) => base58(b.subarray(o, o + 32));
const u64 = (b, o) => dv(b).getBigUint64(o, true);
const u128 = (b, o) => dv(b).getBigUint64(o, true) + (dv(b).getBigUint64(o + 8, true) << 64n);
const Q64 = 2 ** 64;
/** Anchor account discriminators (sha256("account:<name>")[0..8]): the pool type, not another account of the program. */
const POOL_STATE = [247, 237, 227, 245, 215, 195, 222, 70]; // Raydium CPMM and CLMM
const LB_PAIR = [33, 11, 49, 98, 181, 101, 177, 13]; // Meteora DLMM
const CP_POOL = [241, 154, 109, 4, 17, 177, 109, 188]; // Meteora DAMM v2
const VIRTUAL_POOL = [213, 224, 5, 209, 98, 69, 119, 92]; // Meteora DBC
const is = (b, d) => b.length >= 8 && d.every((x, i) => b[i] === x);
/** (sqrt price as Q64.64)² as a float: raw token B per raw token A. */
const sqrtPriceRaw = (x) => (Number(x) / Q64) ** 2;
/**
* What a pool account says, for pricing: { kind, mints: [a, b], vaults: [a, b], decimals: [a, b] or null
* (read the mints), held: [a, b] (fees sitting in the vaults that aren't liquidity, raw), rawPrice: raw b
* per raw a from the pool's state (null: price on the reserves), empty: no liquidity left (its stored price
* is whatever it was when the last of it was withdrawn), finished: a launchpad curve that has filled (the
* coin moved to a pool; nothing trades on the curve again, and its price stays where it stopped) }. Null
* for any other account.
*/
export function readPool(owner, data) {
const b = data;
switch (owner) {
case RAYDIUM_AMM:
// LIQUIDITY_STATE_LAYOUT_V4 (752 bytes): the vaults also hold PnL owed to the pool's orders
if (b.length !== 752) return null;
return { kind: "raydium-amm", mints: [key(b, 400), key(b, 432)], vaults: [key(b, 336), key(b, 368)], decimals: [Number(u64(b, 32)), Number(u64(b, 40))], held: [u64(b, 192), u64(b, 200)], rawPrice: null };
case RAYDIUM_CPMM:
// PoolState: protocol, fund and creator fees wait in the vaults until collected
if (!is(b, POOL_STATE) || b.length < 413) return null;
return {
kind: "raydium-cpmm",
mints: [key(b, 168), key(b, 200)],
vaults: [key(b, 72), key(b, 104)],
decimals: [b[331], b[332]],
held: [u64(b, 341) + u64(b, 357) + u64(b, 397), u64(b, 349) + u64(b, 365) + u64(b, 405)],
rawPrice: null,
};
case RAYDIUM_CLMM:
// PoolState: the price is sqrt_price_x64
if (!is(b, POOL_STATE) || b.length < 325) return null;
return { kind: "raydium-clmm", mints: [key(b, 73), key(b, 105)], vaults: [key(b, 137), key(b, 169)], decimals: [b[233], b[234]], held: [u64(b, 309), u64(b, 317)], rawPrice: sqrtPriceRaw(u128(b, 253)), empty: u128(b, 237) === 0n };
case METEORA_DLMM: {
// LbPair: the active bin's price, (1 + bin step)^active id
if (!is(b, LB_PAIR) || b.length < 232) return null;
const activeId = dv(b).getInt32(76, true);
const binStep = dv(b).getUint16(80, true);
return { kind: "meteora-dlmm", mints: [key(b, 88), key(b, 120)], vaults: [key(b, 152), key(b, 184)], decimals: null, held: [u64(b, 216), u64(b, 224)], rawPrice: (1 + binStep / 10_000) ** activeId };
}
case METEORA_DAMM2:
// cp-amm Pool: sqrt_price; protocol and partner fees wait in the vaults
if (!is(b, CP_POOL) || b.length < 472) return null;
return {
kind: "meteora-damm2",
mints: [key(b, 168), key(b, 200)],
vaults: [key(b, 232), key(b, 264)],
decimals: null,
held: [u64(b, 392) + u64(b, 408), u64(b, 400) + u64(b, 416)],
rawPrice: sqrtPriceRaw(u128(b, 456)),
empty: u128(b, 360) === 0n,
};
case METEORA_DBC:
// VirtualPool: a launchpad curve, sqrt_price; its quote token is the quote vault's mint. migration_progress
// (@308) leaves 0 for good when the curve fills, before the move to a pool (is_migrated, @305, comes after)
if (!is(b, VIRTUAL_POOL) || b.length < 309) return null;
return { kind: "meteora-dbc", mints: [key(b, 136), null], vaults: [key(b, 168), key(b, 200)], decimals: null, held: [0n, 0n], rawPrice: sqrtPriceRaw(u128(b, 280)), curve: true, finished: b[308] !== 0 };
default:
return null;
}
}
/** A token account's mint and raw amount (vaults are token accounts), or null. */
export function readTokenAccount(data) {
if (!data || data.length < 72) return null;
return { mint: key(data, 0), amount: u64(data, 64) };
}
/** A mint's raw supply and decimals, or null. */
export function readMint(data) {
if (!data || data.length < 45) return null;
return { supply: u64(data, 36), decimals: data[44] };
}
/**
* The coin `mint`'s price on a pool read with readPool, from its vaults (readTokenAccount, [a, b]) and
* both tokens' decimals: { quoteMint, price: quote tokens per coin, side: quote tokens on each side of the
* pool as its depth (null for a launchpad curve: the caller sizes it) } in whole tokens, or null.
*/
export function poolPrice(pool, mint, vaults, decimals) {
const mints = [pool.mints[0], pool.mints[1] ?? vaults[1]?.mint];
const i = mints[0] === mint ? 0 : mints[1] === mint ? 1 : -1;
if (pool.empty || pool.finished || i < 0 || !vaults[0] || !vaults[1] || !decimals || decimals.some((d) => !(d >= 0 && d <= 18))) return null;
const j = 1 - i;
const unit = decimals.map((d) => 10 ** d);
const reserve = [0, 1].map((k) => Number(vaults[k].amount > pool.held[k] ? vaults[k].amount - pool.held[k] : 0n) / unit[k]);
// b per a, in whole tokens
const bPerA = pool.rawPrice !== null ? pool.rawPrice * (unit[0] / unit[1]) : reserve[0] > 0 ? reserve[1] / reserve[0] : 0;
const price = i === 0 ? bPerA : 1 / bPerA;
if (!(price > 0) || !Number.isFinite(price)) return null;
// constant product: the reserves; concentrated: the pair's value split evenly
const side = pool.curve ? null : pool.rawPrice === null ? reserve[j] : (reserve[j] + reserve[i] * price) / 2;
if (side !== null && !(side > 0)) return null;
return { quoteMint: mints[j], price, side };
}
// Funded extension: just enough Solana to price a pump.fun or Raydium LaunchLab coin from the chain, in
// the trader's own browser (free public RPC, nothing billed to anyone): base58, program-derived
// addresses, and the pump.fun bonding curve / PumpSwap pool / LaunchLab pool account layouts. No keys,
// no signing, no transactions.
export const PUMP_PROGRAM = "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P";
export const PUMP_AMM_PROGRAM = "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA";
/** Raydium LaunchLab: the bonding curves of StonkFun, bonk.fun and other launchpads. */
export const LAUNCHLAB_PROGRAM = "LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj";
export const WSOL_MINT = "So11111111111111111111111111111111111111112";
const DEFAULT_PUBKEY = "11111111111111111111111111111111";
const TOKEN_PROGRAMS = new Set(["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"]);
const TOKEN = 1e6; // pump.fun tokens: 6 decimals
const SOL = 1e9;
// ───────────── base58 ─────────────
const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
const MAP = new Map([...ALPHABET].map((c, i) => [c, i]));
export function decodeBase58(s) {
let n = 0n;
for (const c of s) {
const v = MAP.get(c);
if (v === undefined) throw new Error("not base58");
n = n * 58n + BigInt(v);
}
const bytes = [];
while (n > 0n) {
bytes.unshift(Number(n & 255n));
n >>= 8n;
}
for (const c of s) {
if (c !== "1") break;
bytes.unshift(0);
}
return Uint8Array.from(bytes);
}
export function encodeBase58(bytes) {
let n = 0n;
for (const b of bytes) n = (n << 8n) + BigInt(b);
let s = "";
while (n > 0n) {
s = ALPHABET[Number(n % 58n)] + s;
n /= 58n;
}
for (const b of bytes) {
if (b !== 0) break;
s = "1" + s;
}
return s;
}
export function isAddress(s) {
if (typeof s !== "string" || s.length < 32 || s.length > 44) return false;
try {
return decodeBase58(s).length === 32;
} catch {
return false;
}
}
// ───────────── program-derived addresses ─────────────
const P = 2n ** 255n - 19n;
const modp = (a) => ((a % P) + P) % P;
function pow(b, e) {
let r = 1n;
b = modp(b);
while (e > 0n) {
if (e & 1n) r = (r * b) % P;
b = (b * b) % P;
e >>= 1n;
}
return r;
}
const D = modp(-121665n * pow(121666n, P - 2n));
const SQRT_M1 = pow(2n, (P - 1n) / 4n);
/** Is this 32-byte string a point on the ed25519 curve? PDAs are the ones that aren't. */
function isOnCurve(bytes) {
let y = 0n;
for (let i = 31; i >= 0; i--) y = (y << 8n) + BigInt(i === 31 ? bytes[i] & 0x7f : bytes[i]);
const sign = bytes[31] >> 7;
if (y >= P) return false;
const y2 = (y * y) % P;
const u = modp(y2 - 1n);
const v = modp(D * y2 + 1n);
const v3 = (v * v * v) % P;
const v7 = (v3 * v3 * v) % P;
let x = (u * v3 * pow(u * v7, (P - 5n) / 8n)) % P;
const vx2 = (v * x * x) % P;
if (vx2 === u) {
/* x is a root */
} else if (vx2 === modp(-u)) x = (x * SQRT_M1) % P;
else return false;
return !(x === 0n && sign === 1);
}
const enc = new TextEncoder();
const PDA_MARKER = enc.encode("ProgramDerivedAddress");
async function findProgramAddress(seeds, programId) {
const program = decodeBase58(programId);
for (let bump = 255; bump >= 0; bump--) {
const parts = [...seeds, Uint8Array.of(bump), program, PDA_MARKER];
const buf = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
let o = 0;
for (const p of parts) {
buf.set(p, o);
o += p.length;
}
const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", buf));
if (!isOnCurve(hash)) return encodeBase58(hash);
}
throw new Error("no program address");
}
const pdaCache = new Map();
async function cached(key, fn) {
if (!pdaCache.has(key)) pdaCache.set(key, fn());
return pdaCache.get(key);
}
/** The coin's pump.fun bonding curve account. */
export const bondingCurvePda = (mint) => cached(`c:${mint}`, () => findProgramAddress([enc.encode("bonding-curve"), decodeBase58(mint)], PUMP_PROGRAM));
/** The PumpSwap pool a pump.fun coin migrates into (index 0), paired with what its curve was paired with (SOL by default). */
export const canonicalPoolPda = (mint, quoteMint = WSOL_MINT) =>
cached(`p:${mint}:${quoteMint}`, async () => {
const authority = await findProgramAddress([enc.encode("pool-authority"), decodeBase58(mint)], PUMP_PROGRAM);
return findProgramAddress([enc.encode("pool"), new Uint8Array(2), decodeBase58(authority), decodeBase58(mint), decodeBase58(quoteMint)], PUMP_AMM_PROGRAM);
});
/** A coin's LaunchLab pool (its bonding curve) paired with `quoteMint`. */
export const launchPoolPda = (mint, quoteMint) => cached(`l:${mint}:${quoteMint}`, () => findProgramAddress([enc.encode("pool"), decodeBase58(mint), decodeBase58(quoteMint)], LAUNCHLAB_PROGRAM));
/**
* Where a coin can trade before any DEX: its pump.fun curve and the PumpSwap pool it moves into, and its LaunchLab
* curve, paired with `quoteMint` (a site's chart may be named after any of them, not the coin).
*/
export const coinPools = (mint, quoteMint = WSOL_MINT) => Promise.all([bondingCurvePda(mint), canonicalPoolPda(mint, quoteMint), launchPoolPda(mint, quoteMint)]);
// ───────────── RPC ─────────────
const PUBLIC_RPCS = ["https://api.mainnet-beta.solana.com", "https://solana-rpc.publicnode.com"];
let preferred = 0;
async function rpcAt(url, method, params) {
const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), signal: AbortSignal.timeout(8000) });
if (res.status === 429 || res.status === 403 || res.status >= 500) throw new Error(`HTTP ${res.status}`);
const body = await res.json();
if (body.error) throw new Error(body.error.message || "RPC error");
return body.result;
}
/** JSON-RPC against the free public endpoints, rotating on refusal. */
export async function rpc(method, params) {
const urls = PUBLIC_RPCS.slice(preferred).concat(PUBLIC_RPCS.slice(0, preferred));
let last;
for (const url of urls) {
try {
const out = await rpcAt(url, method, params);
preferred = PUBLIC_RPCS.indexOf(url);
return out;
} catch (e) {
last = e;
}
}
throw last ?? new Error("RPC unreachable");
}
/**
* A look into the chain's history (signatures, old transactions). Not every free endpoint keeps it:
* publicnode answers an empty list or null for anything but recent ones, so an empty answer asks the
* next endpoint, Solana's own first.
*/
async function historyRpc(method, params) {
let out = null;
let last;
let answered = false;
for (const url of PUBLIC_RPCS) {
try {
out = await rpcAt(url, method, params);
answered = true;
if (Array.isArray(out) ? out.length : out) return out;
} catch (e) {
last = e;
}
}
if (!answered) throw last ?? new Error("RPC unreachable");
return out;
}
const b64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
let accountsFallback = null;
let fallbackUntil = 0;
/** Once the free endpoints have refused twice, account reads go to the fallback for this long. */
const FALLBACK_HOLD_MS = 30_000;
/**
* Where account reads go when both free endpoints refuse twice in a row: `fn(addresses)` answers like
* getMultipleAccounts. The extension sets Funded's server, which reads them with its own RPC.
*/
export function setAccountsFallback(fn) {
accountsFallback = fn;
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
/** Raw data (and owner) of up to 100 accounts; null for missing ones. */
export async function accounts(addresses) {
const params = [addresses, { encoding: "base64", commitment: "confirmed" }];
let r = null;
if (accountsFallback && Date.now() < fallbackUntil) r = await accountsFallback(addresses).catch(() => null);
if (!r) {
try {
r = await rpc("getMultipleAccounts", params);
} catch (e) {
// (refused, usually for asking too often from this connection) once more in a moment, then the fallback
await sleep(300);
try {
r = await rpc("getMultipleAccounts", params);
} catch {
if (!accountsFallback) throw e;
fallbackUntil = Date.now() + FALLBACK_HOLD_MS;
r = await accountsFallback(addresses);
}
}
}
return r.value.map((a) => (a ? { owner: a.owner, data: b64(a.data[0]) } : null));
}
// ───────────── account layouts ─────────────
const CURVE_DISC = [23, 183, 248, 55, 96, 216, 172, 96];
const POOL_DISC = [241, 154, 109, 4, 17, 177, 109, 188];
const hasDisc = (b, d) => b.length >= 8 && d.every((x, i) => b[i] === x);
const view = (b) => new DataView(b.buffer, b.byteOffset, b.byteLength);
const key = (b, o) => encodeBase58(b.subarray(o, o + 32));
export function parseCurve(b) {
if (!hasDisc(b, CURVE_DISC) || b.length < 49) return null;
const v = view(b);
const left = (o) => b.length - o;
return {
vTok: v.getBigUint64(8, true),
vSol: v.getBigUint64(16, true),
rTok: v.getBigUint64(24, true),
rSol: v.getBigUint64(32, true),
supply: v.getBigUint64(40, true),
complete: b[48] !== 0,
// creator (32) @49, is_mayhem_mode @81, is_cashback_coin @82, quote_mint @83
quoteMint: left(83) >= 32 ? key(b, 83) : WSOL_MINT,
};
}
export function parsePool(b) {
if (!hasDisc(b, POOL_DISC) || b.length < 203) return null;
const v = view(b);
// bump @8, index @9, creator @11, base_mint @43, quote_mint @75, lp_mint @107, base_vault @139, quote_vault @171,
// lp_supply @203, coin_creator @211, is_mayhem_mode + is_cashback_coin @243, virtual_quote_reserves (i128) @245
let virtualQuote = 0n;
if (b.length >= 261) virtualQuote = v.getBigUint64(245, true) + (v.getBigInt64(253, true) << 64n);
return { baseMint: key(b, 43), quoteMint: key(b, 75), baseVault: key(b, 139), quoteVault: key(b, 171), virtualQuote };
}
const LAUNCH_POOL_DISC = [247, 237, 227, 245, 215, 195, 222, 70];
const LAUNCH_CONFIG_DISC = [149, 8, 156, 202, 160, 252, 176, 217];
/**
* A LaunchLab pool (Raydium's IDL, PoolState): the coin (mint A) on a curve against `mintB`. Status 0 is
* still on the curve; 1 and 2 have left it for a Raydium pool.
*/
export function parseLaunchPool(b) {
if (!hasDisc(b, LAUNCH_POOL_DISC) || b.length < 333) return null;
const v = view(b);
const u = (o) => v.getBigUint64(o, true);
// epoch @8, bump @16, status @17, mint_decimals_a @18, mint_decimals_b @19, migrate_type @20, supply @21,
// total_sell_a @29, virtual_a @37, virtual_b @45, real_a @53, real_b @61, total_fund_raising_b @69, fees,
// vesting schedule, global_config @141, platform_config @173, mint_a @205, mint_b @237
return { status: b[17], decA: b[18], decB: b[19], supply: u(21), totalSellA: u(29), virtualA: u(37), virtualB: u(45), realA: u(53), realB: u(61), config: key(b, 141), mintA: key(b, 205), mintB: key(b, 237) };
}
/** A LaunchLab global config's curve type (0: constant product), or null. */
const parseLaunchCurveType = (b) => (hasDisc(b, LAUNCH_CONFIG_DISC) && b.length > 16 ? b[16] : null);
const tokenAmount = (b) => (b && b.length >= 72 ? view(b).getBigUint64(64, true) : null);
const isSolQuote = (m) => m === WSOL_MINT || m === DEFAULT_PUBKEY;
// ───────────── pricing a coin ─────────────
const poolCache = new Map(); // mint → { pool, baseVault, quoteVault, supply, unit (of the paired token), quoteMint (if not SOL) }
const decimalsCache = new Map(); // a token's mint → its decimals
/** A token's decimals (SPL and Token-2022 mints keep them at byte 44), or null. */
async function mintDecimals(mint) {
if (!decimalsCache.has(mint)) {
const [m] = await accounts([mint]);
if (!m || m.data.length <= 44) return null;
decimalsCache.set(mint, m.data[44]);
}
return decimalsCache.get(mint);
}
/**
* The coin's pool right now, as the server prices it: { venue, pool: { base, quote, maxBuy }, realSol, supply }
* in whole tokens and SOL, or { error }: its pump.fun curve or PumpSwap pool, or its LaunchLab curve
* (one paired with another token than SOL is found by findLaunchPool first). One RPC call per quote once
* the addresses are known. A curve paired with another token than SOL (USDC, PUMP, WBTC, a stock…) comes
* back in that token, with its `quoteMint`: the caller converts it to SOL (and the server, for the fill,
* at its own price). So does its PumpSwap pool once it has moved there (paired with the same token).
*/
export async function quoteCoin(mint) {
const known = poolCache.get(mint);
if (known) {
const [p, bv, qv] = await accounts([known.pool, known.baseVault, known.quoteVault]);
const parsed = p && parsePool(p.data);
const base = tokenAmount(bv?.data);
const quote = tokenAmount(qv?.data);
if (parsed && base !== null && quote !== null && base > 0n) {
const out = { venue: "pumpswap", pool: { base: Number(base) / TOKEN, quote: Number(quote + parsed.virtualQuote) / known.unit, maxBuy: null }, realSol: Number(quote) / known.unit, supply: known.supply };
return known.quoteMint ? { ...out, quoteMint: known.quoteMint } : out;
}
}
const launchKnown = launchPools.get(mint);
if (launchKnown) return launchQuote(mint, launchKnown);
// pump.fun's curve and a SOL-paired LaunchLab curve in one call
const curveAddr = await bondingCurvePda(mint);
const launchAddr = await launchPoolPda(mint, WSOL_MINT);
const [c, l] = await accounts([curveAddr, launchAddr]);
const curve = c && c.owner === PUMP_PROGRAM ? parseCurve(c.data) : null;
if (!curve) {
if (l?.owner !== LAUNCHLAB_PROGRAM || !parseLaunchPool(l.data)) return { error: "not-pump" };
launchPools.set(mint, launchAddr);
return launchQuote(mint, launchAddr, l);
}
const supply = Number(curve.supply) / TOKEN;
const paired = !isSolQuote(curve.quoteMint);
let unit = SOL;
if (paired) {
const decimals = await mintDecimals(curve.quoteMint);
if (decimals === null) return { error: "not-sol" };
unit = 10 ** decimals;
}
if (!curve.complete) {
// (a curve paired with another token holds that token's reserves in its "SOL" fields)
const out = { venue: "curve", pool: { base: Number(curve.vTok) / TOKEN, quote: Number(curve.vSol) / unit, maxBuy: Number(curve.rTok) / TOKEN }, realSol: Number(curve.rSol) / unit, supply };
return paired ? { ...out, quoteMint: curve.quoteMint } : out;
}
// it has moved to its PumpSwap pool, paired with the same token as its curve
const quoteMint = paired ? curve.quoteMint : WSOL_MINT;
const poolAddr = await canonicalPoolPda(mint, quoteMint);
const [p] = await accounts([poolAddr]);
const parsed = p && p.owner === PUMP_AMM_PROGRAM ? parsePool(p.data) : null;
if (!parsed || parsed.baseMint !== mint) return { error: "migrating" };
poolCache.set(mint, { pool: poolAddr, baseVault: parsed.baseVault, quoteVault: parsed.quoteVault, supply, unit, ...(paired ? { quoteMint } : {}) });
return quoteCoin(mint);
}
const launchPools = new Map(); // mint → its LaunchLab pool, once found
const curveTypes = new Map(); // LaunchLab global config → its curve type
/**
* A LaunchLab coin on its curve, priced like a pump.fun curve: x·y = k on the virtual reserves, the
* tokens left for sale as the most a buy gets. Paired with another token than SOL, it comes back in that
* token with its `quoteMint`, like a pump.fun curve. A coin that left its curve for a Raydium pool:
* { error: "graduated" } (DexScreener prices it there).
*/
async function launchQuote(mint, address, read) {
const a = read ?? (await accounts([address]))[0];
const p = a?.owner === LAUNCHLAB_PROGRAM ? parseLaunchPool(a.data) : null;
if (!p || p.mintA !== mint) return { error: "not-pump" };
if (p.status !== 0) return { error: "graduated" };
if (!curveTypes.has(p.config)) {
const [cfg] = await accounts([p.config]);
curveTypes.set(p.config, cfg?.owner === LAUNCHLAB_PROGRAM ? parseLaunchCurveType(cfg.data) : null);
}
// LaunchLab also has fixed-price and linear curves, which no launchpad we support uses
if (curveTypes.get(p.config) !== 0) return { error: "curve-type" };
const unitA = 10 ** p.decA;
const unitB = 10 ** p.decB;
const pool = { base: Number(p.virtualA - p.realA) / unitA, quote: Number(p.virtualB + p.realB) / unitB, maxBuy: Math.max(0, Number(p.totalSellA - p.realA) / unitA) };
const out = { venue: "launchlab", pool, realSol: Number(p.realB) / unitB, supply: Number(p.supply) / unitA };
return isSolQuote(p.mintB) ? out : { ...out, quoteMint: p.mintB };
}
/**
* Use `pool` for the coin's LaunchLab curve (the Funded server found it): quoteCoin reads it and checks
* it's this coin's before pricing anything on it.
*/
export function rememberLaunchPool(mint, pool) {
if (!isAddress(pool)) return null;
launchPools.set(mint, pool);
return pool;
}
/**
* The LaunchLab pool of a coin paired with another token than SOL (StonkFun pairs coins with stocks and
* hundreds of other tokens), from one of the coin's recent trades: the pool's address follows from the
* coin and the token it's paired with. Null if its recent transactions don't trade on LaunchLab.
*/
export async function findLaunchPool(mint) {
if (launchPools.has(mint)) return launchPools.get(mint);
const sigs = await historyRpc("getSignaturesForAddress", [mint, { limit: 5 }]);
for (const s of sigs) {
if (s.err) continue;
const tx = await historyRpc("getTransaction", [s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }]);
// (jsonParsed lists the accounts loaded from lookup tables too)
const keys = new Set((tx?.transaction?.message?.accountKeys ?? []).map((k) => (typeof k === "string" ? k : k.pubkey)));
if (!keys.has(LAUNCHLAB_PROGRAM)) continue;
const paired = new Set([...(tx?.meta?.postTokenBalances ?? []), ...(tx?.meta?.preTokenBalances ?? [])].map((b) => b.mint).filter((m) => m && m !== mint));
for (const q of paired) {
const pool = await launchPoolPda(mint, q);
if (keys.has(pool)) {
launchPools.set(mint, pool);
return pool;
}
}
}
return null;
}
/**
* What an address on a trading site is: a coin (mint), a pump.fun curve, a PumpSwap or LaunchLab pool, or
* something else. Returns { mint } when it can tell, else { other: owner }.
*/
export async function classify(address) {
const [a] = await accounts([address]);
if (!a) return { missing: true };
if (TOKEN_PROGRAMS.has(a.owner)) return { mint: address };
if (a.owner === PUMP_AMM_PROGRAM) {
// the coin is the base, whatever it's paired with (SOL, or PUMP/USDC for coins that left such a curve)
const p = parsePool(a.data);
if (p && !isSolQuote(p.baseMint)) return { mint: p.baseMint };
}
if (a.owner === PUMP_PROGRAM && parseCurve(a.data)) return { curve: true };
if (a.owner === LAUNCHLAB_PROGRAM) {
const p = parseLaunchPool(a.data);
if (p) {
launchPools.set(p.mintA, address);
return { mint: p.mintA };
}
}
return { other: a.owner };
}
/** The mint behind a bonding curve address, from the curve's most recent transaction. */
export async function mintOfCurve(curveAddr) {
const sigs = await historyRpc("getSignaturesForAddress", [curveAddr, { limit: 3 }]);
for (const s of sigs) {
const tx = await historyRpc("getTransaction", [s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }]);
const mints = new Set([...(tx?.meta?.postTokenBalances ?? []), ...(tx?.meta?.preTokenBalances ?? [])].map((b) => b.mint).filter((m) => m && m !== WSOL_MINT));
for (const m of mints) if ((await bondingCurvePda(m)) === curveAddr) return m;
}
return null;
}
/** Name and symbol from the mint (Token-2022 metadata, as pump.fun's newer coins carry it). */
export async function mintMetadata(mint) {
const r = await rpc("getAccountInfo", [mint, { encoding: "jsonParsed" }]);
const ext = r?.value?.data?.parsed?.info?.extensions?.find?.((e) => e.extension === "tokenMetadata");
return ext ? { symbol: String(ext.state.symbol ?? "").trim(), name: String(ext.state.name ?? "").trim(), uri: ext.state.uri } : null;
}
{
"manifest_version": 3,
"name": "Funded: paper trading",
"short_name": "Funded",
"version": "0.2.23",
"description": "Paper trade Solana memecoins right on Axiom, GMGN, pump.fun and more. Challenge trades count toward a Funded SOL award.",
"icons": {
"16": "icons/icon16.png",
"32": "icons/icon32.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"action": {
"default_popup": "popup.html",
"default_title": "Funded",
"default_icon": {
"16": "icons/icon16.png",
"32": "icons/icon32.png"
}
},
"background": {
"service_worker": "background.js",
"type": "module"
},
"permissions": [
"storage"
],
"host_permissions": [
"https://fundedsol.trade/*",
"https://api.mainnet-beta.solana.com/*",
"https://solana-rpc.publicnode.com/*",
"https://api.dexscreener.com/*",
"https://frontend-api-v3.pump.fun/*",
"https://api.coinbase.com/*"
],
"content_scripts": [
{
"matches": [
"https://axiom.trade/*",
"https://*.axiom.trade/*",
"https://gmgn.ai/*",
"https://*.gmgn.ai/*",
"https://pump.fun/*",
"https://*.pump.fun/*",
"https://trade.padre.gg/*",
"https://dexscreener.com/*",
"https://stonkfun.xyz/*",
"https://*.stonkfun.xyz/*"
],
"js": [
"sites.js",
"panel.js"
],
"run_at": "document_idle"
},
{
"matches": [
"https://axiom.trade/*",
"https://*.axiom.trade/*",
"https://gmgn.ai/*",
"https://*.gmgn.ai/*",
"https://pump.fun/*",
"https://*.pump.fun/*",
"https://trade.padre.gg/*",
"https://dexscreener.com/*"
],
"js": [
"chart.js"
],
"world": "MAIN",
"run_at": "document_idle"
},
{
"matches": [
"https://fundedsol.trade/*",
"https://www.fundedsol.trade/*"
],
"js": [
"bridge.js"
],
"run_at": "document_start"
}
]
}
// Funded extension: the paper-trade panel on a coin's page (Axiom, GMGN, pump.fun, Padre, DexScreener,
// StonkFun). One-click buys in SOL and sells by %, eight editable presets each, a PnL bar for the coin,
// and a panel the trader can drag and resize; the price comes from the chain for pump.fun coins and from
// DexScreener for others (in the background, from the trader's own browser), the account from Funded.
// The header shows the trader's mode: Challenge (green, counts toward the award) or Practice (amber,
// counts toward nothing); clicking it twice switches. The coin's fills and average prices also go to
// chart.js, which marks them on the site's own chart (unless switched off in the preset editor).
// Paper trades only: nothing here touches a wallet, and the site's own buttons are left alone.
"use strict";
(() => {
if (window.top !== window || document.getElementById("funded-panel-host")) return;
// ───────────── helpers ─────────────
/** What a page says once this copy of the extension was replaced (reloaded or updated while the page stayed open). */
const STALE = "Funded was updated. Reload this page.";
const send = (msg) =>
new Promise((resolve) => {
try {
chrome.runtime.sendMessage(msg, (r) => resolve(chrome.runtime.lastError ? { error: STALE, stale: true } : r ?? {}));
} catch {
resolve({ error: STALE, stale: true });
}
});
function el(tag, attrs = {}, ...kids) {
const n = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (v === undefined || v === null || v === false) continue;
if (k === "class") n.className = v;
else if (k.startsWith("on")) n.addEventListener(k.slice(2), v);
else n.setAttribute(k, v === true ? "" : String(v));
}
for (const c of kids.flat()) if (c !== null && c !== undefined && c !== false) n.append(...(c instanceof Node ? [c] : solNodes(String(c))));
return n;
}
const svg = (tag, attrs) => {
const n = document.createElementNS("http://www.w3.org/2000/svg", tag);
for (const [k, v] of Object.entries(attrs)) n.setAttribute(k, v);
return n;
};
// SOL amounts are written with "◎" and shown with Solana's mark in its place: an inline SVG, which no
// site's image policy can block. Each mark gets its own gradient id (ids are shared across the panel).
const SOL_PATHS = ["M4 0H24L20 5H0Z", "M0 7.5H20L24 12.5H4Z", "M4 15H24L20 20H0Z"];
let solIds = 0;
const solIcon = () => {
const id = `funded-sol-${++solIds}`;
const mark = svg("svg", { class: "sol", viewBox: "0 0 24 20", role: "img", "aria-label": "SOL" });
const grad = svg("linearGradient", { id, gradientUnits: "userSpaceOnUse", x1: "24", y1: "0", x2: "0", y2: "20" });
grad.append(svg("stop", { offset: "0", "stop-color": "#00FFA3" }), svg("stop", { offset: "1", "stop-color": "#DC1FFF" }));
const defs = svg("defs", {});
defs.append(grad);
mark.append(defs, ...SOL_PATHS.map((d) => svg("path", { d, fill: `url(#${id})` })));
return mark;
};
const solNodes = (s) => s.split("◎").flatMap((part, i) => (i ? [solIcon(), part] : [part])).filter((x) => x !== "").map((x) => (typeof x === "string" ? document.createTextNode(x) : x));
/** Sets a node's text (SOL marks included), leaving it alone when it hasn't changed. */
const setText = (n, s) => {
if (n.dataset.text === s) return;
n.dataset.text = s;
n.replaceChildren(...solNodes(s));
};
const fmtSol = (v, sign = false) => {
const a = Math.abs(v);
const d = a >= 100 ? 1 : a >= 1 ? 3 : a >= 0.01 ? 3 : 4;
return `${sign && v > 0 ? "+" : v < 0 ? "−" : ""}◎${a.toFixed(d)}`;
};
const fmtNum = (v) => {
const a = Math.abs(v);
if (a >= 1e9) return `${(v / 1e9).toFixed(2)}B`;
if (a >= 1e6) return `${(v / 1e6).toFixed(2)}M`;
if (a >= 1e3) return `${(v / 1e3).toFixed(1)}K`;
return v.toFixed(a >= 10 ? 0 : 2);
};
const fmtPct = (v) => `${v > 0 ? "+" : v < 0 ? "−" : ""}${Math.abs(v).toFixed(1)}%`;
const trim = (s) => s.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, "");
/** Short forms for the PnL bar: "◎0.098", "◎1.25", "◎0"; "−2%", "+1.5%", "+38%". */
const fmtBar = (v, sign = false) => {
const a = Math.abs(v);
if (a < 5e-5) return "◎0";
return `${sign && v > 0 ? "+" : v < 0 ? "−" : ""}◎${trim(a.toFixed(a >= 100 ? 0 : a >= 10 ? 1 : a >= 1 ? 2 : a >= 0.1 ? 3 : 4))}`;
};
const fmtBarPct = (v) => (Math.abs(v) < 0.05 ? "0%" : `${v > 0 ? "+" : "−"}${trim(Math.abs(v).toFixed(Math.abs(v) >= 10 ? 0 : 1))}%`);
const short = (a) => `${a.slice(0, 4)}…${a.slice(-4)}`;
const newer = (a, b) => {
const x = a.split(".").map(Number);
const y = b.split(".").map(Number);
for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) > (y[i] || 0);
return false;
};
const MODE_LABEL = { challenge: "Challenge", practice: "Practice" };
/**
* How old the panel's price may be and still go to the chart: chart.js tells the chart's units from it,
* and a price left behind by a fast move (Solana's RPC not answering) would put the lines in the wrong place.
*/
const CHART_PRICE_MAX_AGE_MS = 10_000;
/** How long a click that may have gone through (its answer was lost) keeps its order ID for the same click again. */
const UNCONFIRMED_MS = 60_000;
/** After a lost answer: when to ask for the account again, to tell whether the order went through. */
const CHECK_ORDER_MS = [2000, 5000, 10_000, 20_000];
const DEFAULT_PRESETS = { buy: [0.05, 0.1, 0.25, 0.5, 0.75, 1, 1.5, 2], sell: [25, 50, 75, 100, 5, 10, 15, 33] };
/** Saved presets, filled out to eight each (sets saved as four keep theirs as the first row). */
function normPresets(p) {
const fill = (a, d) => (Array.isArray(a) && a.length && a.length <= 8 && a.every((v) => Number.isFinite(v) && v > 0) ? [...a, ...d.slice(a.length)] : d);
return { buy: fill(p?.buy, DEFAULT_PRESETS.buy), sell: fill(p?.sell, DEFAULT_PRESETS.sell) };
}
/** The trading panel's size (resizable from its edges and bottom corners). */
const SIZE = { w: 300, h: 352, minW: 244, minH: 316, maxW: 640, maxH: 900 };
const clamp = (v, lo, hi) => Math.min(Math.max(v, lo), Math.max(lo, hi));
/** The Funded mark: four diamonds on a rounded square. */
const LOGO_PATHS = [
["M32 6.5 41.6 19.8 32 29.4 22.4 19.8Z", "#6fbc92"],
["M6.5 32 19.8 22.4 29.4 32 19.8 41.6Z", "#F3EFE6"],
["M57.5 32 44.2 22.4 34.6 32 44.2 41.6Z", "#B8B9BC"],
["M32 57.5 22.4 44.2 32 34.6 41.6 44.2Z", "#E4DCCF"],
];
const logo = () => {
const mark = svg("svg", { width: "18", height: "18", viewBox: "0 0 64 64", fill: "none", "aria-hidden": "true" });
mark.append(svg("rect", { width: "64", height: "64", rx: "14", fill: "#303234" }), ...LOGO_PATHS.map(([d, fill]) => svg("path", { d, fill })));
return el("span", { class: "logo" }, mark);
};
// ───────────── state ─────────────
const S = {
page: null, // { address, kind, site } from the URL
mint: null,
coinError: null,
meta: null,
quote: null, // { venue, pool, realSol, supply, solUsd, pools, at } | { error }
quoteAt: 0, // when the last good quote came
unconfirmed: null, // { what, idem, until }: a click whose answer was lost, which may have gone through
pools: null, // the coin's pools (from its last good quote), which a site's chart may be named after
signedIn: null,
view: null, // the account, as /api/ext/account returns it
presets: DEFAULT_PRESETS,
editing: false,
busy: null, // "buy" | "sell" | "refill" | "mode"
status: null, // { text, tone, until }
armed: null, // { key: "mode" | "reset", until }: a click that needs a second one to go through
marks: true, // show this coin's trades on the site's chart (chart.js)
minimized: false,
pos: null,
size: null, // { w, h } once resized
coin: null, // { mint, bought, sold, avgEntry, avgExit, avgEntryUsd, avgExitUsd, fills }: this coin's totals this run, for the PnL bar
};
// ───────────── the panel ─────────────
const host = el("div", { id: "funded-panel-host" });
host.style.cssText = "all: initial; position: fixed; z-index: 2147483000; top: 96px; right: 16px; display: none;";
const root = host.attachShadow({ mode: "open" });
root.append(el("style", {}, CSS()));
const box = el("div", { class: "panel", role: "region", "aria-label": "Funded paper trading" });
root.append(box);
// keep the site's keyboard shortcuts out of our inputs
for (const t of ["keydown", "keyup", "keypress"]) host.addEventListener(t, (e) => e.stopPropagation());
(document.body ?? document.documentElement).append(host);
const position = () => {
if (!S.pos) return;
const w = host.offsetWidth || 270;
const x = Math.min(Math.max(0, S.pos.x), window.innerWidth - Math.min(w, 120));
const y = Math.min(Math.max(0, S.pos.y), window.innerHeight - 40);
Object.assign(host.style, { left: `${x}px`, top: `${y}px`, right: "auto" });
};
/** The trading and preset views take the trader's size; the others only its width. */
function sizePanel() {
const sized = mode === "trade" || mode === "edit";
const w = clamp(S.size?.w ?? SIZE.w, SIZE.minW, Math.min(SIZE.maxW, window.innerWidth - 16));
const h = clamp(S.size?.h ?? SIZE.h, SIZE.minH, Math.min(SIZE.maxH, window.innerHeight - 16));
box.classList.toggle("sized", sized);
box.style.width = mode === "min" ? "" : `${w}px`;
box.style.height = sized ? `${h}px` : "";
}
window.addEventListener("resize", () => (sizePanel(), position()));
/** A chrome.storage call; false (and the page is told to reload) once this copy of the extension was replaced. */
async function stored(fn) {
try {
await fn();
return true;
} catch {
setStatus(STALE, "down");
return false;
}
}
/** Where the panel sits on this site, its size and whether it's minimized. */
function savePlace() {
stored(async () => {
const { panelPos } = await chrome.storage.local.get("panelPos");
await chrome.storage.local.set({ panelPos: { ...(panelPos ?? {}), [location.hostname]: { ...(S.pos ?? {}), ...(S.size ?? {}), min: S.minimized } } });
});
}
/** Drag an edge or a bottom corner to resize (`dir`: e, w, s, se or sw). */
function resize(e, dir) {
if (e.button !== 0 || !e.isTrusted) return;
e.preventDefault();
e.stopPropagation();
const r = host.getBoundingClientRect();
const from = { x: e.clientX, y: e.clientY, w: r.width, h: r.height, left: r.left, top: r.top };
// pin the top-left corner, so the panel grows the way it's dragged
S.pos = { x: r.left, y: r.top };
const handle = e.currentTarget;
handle.setPointerCapture(e.pointerId);
const move = (m) => {
const dx = m.clientX - from.x;
const dy = m.clientY - from.y;
const w = clamp(dir.includes("e") ? from.w + dx : dir.includes("w") ? from.w - dx : from.w, SIZE.minW, Math.min(SIZE.maxW, dir.includes("w") ? from.left + from.w : window.innerWidth - from.left));
const h = clamp(dir.includes("s") ? from.h + dy : from.h, SIZE.minH, Math.min(SIZE.maxH, window.innerHeight - from.top));
S.size = { w: Math.round(w), h: Math.round(h) };
S.pos = { x: dir.includes("w") ? from.left + from.w - w : from.left, y: from.top };
sizePanel();
position();
};
const up = () => {
handle.removeEventListener("pointermove", move);
handle.removeEventListener("pointerup", up);
handle.removeEventListener("pointercancel", up);
savePlace();
};
handle.addEventListener("pointermove", move);
handle.addEventListener("pointerup", up);
handle.addEventListener("pointercancel", up);
}
const handles = () => ["e", "w", "s", "se", "sw"].map((d) => el("div", { class: `rz rz-${d}`, "aria-hidden": "true", onpointerdown: (e) => resize(e, d) }));
function drag(e) {
if (e.button !== 0 || e.target.closest("button, input")) return;
const r = host.getBoundingClientRect();
const dx = e.clientX - r.left;
const dy = e.clientY - r.top;
const move = (m) => {
S.pos = { x: m.clientX - dx, y: m.clientY - dy };
position();
};
const up = () => {
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", up);
if (S.pos) savePlace();
};
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
e.preventDefault();
}
const position_ = () => S.view?.run?.positions.find((p) => p.mint === S.mint) ?? null;
/** The account the panel trades: what the server last said (versions of the view from before modes are the Challenge). */
const modeOf = () => (S.view?.mode === "practice" ? "practice" : "challenge");
const other = (m) => (m === "practice" ? "challenge" : "practice");
const armed = (key) => S.armed?.key === key && S.armed.until > Date.now();
/** First click arms (the status line says so), a second within 4 s goes through. */
function arm(key, text) {
if (armed(key)) {
S.armed = null;
return true;
}
S.armed = { key, until: Date.now() + 4000 };
setStatus(text, "warn", 4000);
return false;
}
// what a sale pays: the coin's own fee plus the terminal's (as its last fill did), and the network fee
const feeRate = () => (position_()?.feeBps ?? S.view?.feeBps ?? 100) / 10_000;
const spot = () => (S.quote?.pool ? S.quote.pool.quote / S.quote.pool.base : null);
/** What the position would fetch if sold now, on the current pool (fees included). */
function exitValue(qty) {
const p = S.quote?.pool;
if (!p) return null;
const gross = (p.quote * qty) / (p.base + qty);
return gross * (1 - feeRate()) - (S.view?.networkFeeSol ?? 0);
}
function setStatus(text, tone = "dim", ms = 5000) {
S.status = { text, tone, until: Date.now() + ms };
render();
}
// ───────────── sounds ─────────────
// a filled order's sound. The default: two quick, quiet notes, rising for a buy and falling for a sell (made here,
// no audio files). A trader's own MP3s and volume come from Funded's /extension page, kept in this browser.
const BLIP_HZ = { buy: [660, 880], sell: [880, 660] };
const BLIP_NOTE_S = 0.05;
const SOUND_PEAK_MAX = 0.24; // the loudest any sound plays, at 100% volume
const SOUND_VOLUME = 25; // the volume until the trader sets one (%): a peak of 0.06
const SOUND_MAX_S = 3;
const sounds = { buy: null, sell: null, volume: SOUND_VOLUME }; // buy, sell: the trader's own, as { buffer, peak }
let audio = null;
let playing = null;
/** A stored sound ready to play (decoded ahead, so a fill's sound isn't late), or null: the default plays. */
async function decodeSound(stored) {
if (!stored?.data) return null;
try {
const bytes = Uint8Array.from(atob(stored.data), (c) => c.charCodeAt(0));
const buffer = await new OfflineAudioContext(1, 1, 44100).decodeAudioData(bytes.buffer);
let peak = 0;
for (let ch = 0; ch < buffer.numberOfChannels; ch++) for (const v of buffer.getChannelData(ch)) peak = Math.max(peak, Math.abs(v));
return peak > 0 ? { buffer, peak } : null;
} catch {
return null;
}
}
const takeVolume = (v) => {
sounds.volume = Number.isFinite(v) ? v : SOUND_VOLUME;
};
(async () => {
try {
const { soundBuy, soundSell, soundVolume } = await chrome.storage.local.get(["soundBuy", "soundSell", "soundVolume"]);
takeVolume(soundVolume);
sounds.buy = await decodeSound(soundBuy);
sounds.sell = await decodeSound(soundSell);
} catch {
/* the default sounds */
}
})();
function blip(side) {
try {
const peak = (sounds.volume / 100) * SOUND_PEAK_MAX;
if (!(peak > 0)) return;
audio ??= new AudioContext();
audio.resume?.();
playing?.stop();
playing = null;
const own = sounds[side];
if (own) {
const source = audio.createBufferSource();
const gain = audio.createGain();
source.buffer = own.buffer;
// as loud as the volume says, however loud the file was made
gain.gain.value = peak / own.peak;
source.connect(gain).connect(audio.destination);
source.start();
source.stop(audio.currentTime + SOUND_MAX_S);
playing = source;
return;
}
BLIP_HZ[side].forEach((hz, i) => {
const at = audio.currentTime + i * BLIP_NOTE_S;
const note = audio.createOscillator();
const gain = audio.createGain();
note.frequency.value = hz;
// a few milliseconds' fade in, so it doesn't click
gain.gain.setValueAtTime(0.0001, at);
gain.gain.linearRampToValueAtTime(peak, at + 0.004);
gain.gain.exponentialRampToValueAtTime(0.0001, at + BLIP_NOTE_S);
note.connect(gain).connect(audio.destination);
note.start(at);
note.stop(at + BLIP_NOTE_S);
});
} catch {
/* no sound on this page: the status line still says it */
}
}
// ───────────── actions ─────────────
async function trade(side, amount, e) {
if (e && !e.isTrusted) return; // only real clicks
if (S.busy || !S.mint) return;
if (side === "buy" && !(amount >= 0.001)) return setStatus("Enter at least ◎0.001", "down");
S.busy = side;
render();
const mint = S.mint;
const what = `${mint} ${side} ${amount} ${modeOf()}`;
// the same click again after one whose answer was lost: the same order ID, so it can't fill twice
const again = S.unconfirmed?.what === what && S.unconfirmed.until > Date.now() ? S.unconfirmed.idem : undefined;
const before = lastFill();
const r = await send({ type: "order", mint, side, ...(side === "buy" ? { sol: amount } : { pct: amount }), mode: modeOf(), idem: again });
S.busy = null;
if (r.unconfirmed) {
S.unconfirmed = { what, idem: r.idem, until: Date.now() + UNCONFIRMED_MS };
return checkOrder(mint, before, side);
}
if (r.error) {
setStatus(r.error, "down", 6000);
// signed out, or the mode was switched somewhere else: show what the server has now
if (!r.stale) refreshAccount(true);
return;
}
if (S.unconfirmed?.what === what) S.unconfirmed = null;
takeView(r.view);
const t = r.trade;
blip(t.side);
const sym = S.meta?.symbol ? `$${S.meta.symbol}` : short(S.mint);
if (t.side === "buy") setStatus(`Bought ${fmtNum(t.qty)} ${sym} for ${fmtSol(t.notional + t.fee)}`, "up");
else setStatus(`Sold ${amount}% of ${sym}: ${fmtSol(t.realizedPnl, true)}`, t.realizedPnl >= 0 ? "up" : "down");
}
/** When this coin's newest fill happened (server time), or 0. */
function lastFill() {
const fills = S.coin?.mint === S.mint ? S.coin.fills : null;
return fills?.length ? fills[fills.length - 1].t : 0;
}
/**
* An order whose answer was lost on the way (it may have gone through even so): ask for the account
* until it answers, which shows the fill (and its bubble) if there is one, and say which it was. Until a
* fill turns up, the same click again keeps the order's ID, so a late arrival can't fill twice.
*/
async function checkOrder(mint, before, side) {
setStatus("Couldn't confirm that order. Checking whether it went through…", "warn", 60_000);
for (const wait of CHECK_ORDER_MS) {
await new Promise((r) => setTimeout(r, wait));
if (S.mint !== mint) return;
const r = await send({ type: "account", force: true, mint });
if (r.stale) return;
if (r.error || !r.view) continue;
S.signedIn = !!r.signedIn;
takeView(r.view);
const went = lastFill() > before;
if (went) {
S.unconfirmed = null;
blip(side);
}
return setStatus(went ? "That order went through" : "That order didn't go through. You can try again.", went ? "up" : "down", 6000);
}
setStatus("Still can't reach Funded. Check your connection before trying again.", "down", 8000);
}
async function refill(e) {
if (e && !e.isTrusted) return;
const mode = modeOf();
// Practice starts over (positions and history go), so it asks twice
if (mode === "practice" && !arm("reset", `Click again to start Practice over at ◎${S.view?.run?.startSol ?? 2}`)) return;
S.busy = "refill";
render();
const r = await send({ type: "refill", mode, mint: S.mint ?? undefined });
S.busy = null;
if (r.error) return setStatus(r.error, "down");
takeView(r.view);
if (mode === "practice") setStatus(`Practice reset to ◎${S.view?.run?.startSol ?? 2}. A fresh start.`, "dim", 6000);
else setStatus(`Balance reset. Your balance target is now ◎${S.view?.run?.targetSol ?? "?"}.`, "dim", 7000);
}
async function switchMode(e) {
if (e && !e.isTrusted) return;
if (S.busy || !S.view?.run) return;
const to = other(modeOf());
if (!arm("mode", `Click the tag again to switch to ${MODE_LABEL[to]} mode`)) return render();
S.busy = "mode";
render();
const r = await send({ type: "mode", mode: to, mint: S.mint ?? undefined });
S.busy = null;
if (r.error) return setStatus(r.error, "down");
takeView(r.view);
setStatus(to === "practice" ? "Practice mode: these trades count toward nothing" : "Challenge mode: these trades count toward your award", to === "practice" ? "practice" : "up", 6000);
}
async function setMarks(on) {
S.marks = on;
if (!(await stored(() => chrome.storage.sync.set({ chartMarks: on })))) return;
setStatus(on ? "Your trades show on the chart" : "Chart marks off", "dim", 2500);
}
async function savePresets(buy, sell) {
const b = buy.map(Number);
const s = sell.map(Number);
if (!b.every((v) => v >= 0.001 && v <= 1000)) return setStatus("Buy amounts: ◎0.001 to ◎1,000", "down");
if (!s.every((v) => v >= 1 && v <= 100)) return setStatus("Sell amounts: 1% to 100%", "down");
S.presets = { buy: b, sell: s };
S.editing = false;
if (!(await stored(() => chrome.storage.sync.set({ presets: S.presets })))) return;
setStatus("Presets saved", "up", 2500);
}
// ───────────── rendering ─────────────
let mode = null;
const refs = {};
/** The trading and preset views show the mode where the brand would be (see paintMode). */
function header(canEdit = false) {
const sym = S.meta?.symbol ? `$${S.meta.symbol}` : S.mint ? short(S.mint) : "";
refs.mode = canEdit ? el("button", { class: "mode", onclick: (e) => switchMode(e) }) : null;
const h = el(
"div",
{ class: "head", onpointerdown: drag },
logo(),
refs.mode ?? el("span", { class: "brand" }, "FUNDED"),
el("span", { class: "sym", title: S.meta?.name ?? S.mint ?? "" }, sym),
el("span", { class: "grow" }),
canEdit
? el("button", { class: "icon", title: S.editing ? "Done" : "Edit presets", "aria-label": "Edit presets", onclick: () => ((S.editing = !S.editing), render(true)) }, S.editing ? "✓" : "✎")
: null,
el("button", { class: "icon", title: "Open your Funded portfolio", "aria-label": "Open portfolio", onclick: () => send({ type: "openSite", path: "/dashboard" }) }, "↗"),
el("button", { class: "icon", title: S.minimized ? "Expand" : "Minimize", "aria-label": S.minimized ? "Expand" : "Minimize", onclick: toggleMin }, S.minimized ? "▢" : "–"),
);
return h;
}
function toggleMin() {
S.minimized = !S.minimized;
savePlace();
render(true);
pump();
}
function currentMode() {
if (!S.page) return "hidden";
if (S.signedIn === false) return "signedOut";
if (S.signedIn === null || !S.view) return "loading";
if (!S.view.run) return "loading"; // the server sets the account up on first load
if (S.coinError) return "unsupported";
if (!S.mint || !S.quote) return "loading";
if (S.quote.error && !S.quote.pool) return "unsupported";
if (S.minimized) return "min";
return S.editing ? "edit" : "trade";
}
function render(force = false) {
const m = currentMode();
host.style.display = m === "hidden" ? "none" : "block";
if (m === "hidden") return;
if (force || m !== mode) {
mode = m;
box.replaceChildren();
box.className = `panel ${m === "min" ? "min" : ""}`;
build[m]();
sizePanel();
position();
}
update[m]?.();
paintMode();
sendChart();
}
/**
* What chart.js (in the page) should mark on the site's chart: this coin's fills and average prices in
* the account the panel shows, with the panel's price so it can tell the chart's units (without one, the
* bubbles still go on), and the coin's pools, which a chart may be named after. Sent again when any of it
* changes, or the price moves a few percent.
*/
let chartSent = "null";
function sendChart() {
const c = S.coin?.mint === S.mint ? S.coin : null;
// (a price that has gone stale goes as none: the lines stay where they are)
const px = Date.now() - S.quoteAt < CHART_PRICE_MAX_AGE_MS ? spot() : null;
const on = S.marks && !!S.view?.run && mode !== "signedOut" && !!c?.fills?.length;
const payload = on ? { mint: S.mint, address: S.page?.address ?? null, pools: S.pools ?? [], fills: c.fills, avgEntry: c.avgEntry, avgExit: c.avgExit, avgEntryUsd: c.avgEntryUsd ?? null, avgExitUsd: c.avgExitUsd ?? null, spot: px, supply: S.quote?.supply ?? null, solUsd: S.quote?.solUsd ?? null, mode: modeOf() } : null;
const key = JSON.stringify(payload && { ...payload, spot: px ? Math.round(Math.log(px) * 40) : null });
if (key === chartSent) return;
chartSent = key;
window.postMessage({ source: "funded-panel", type: "chart", payload }, location.origin);
}
/** Practice tints the panel amber; the tag says which mode, or which one a second click switches to. */
function paintMode() {
const m = modeOf();
const signedIn = !!S.view?.run && mode !== "signedOut";
box.classList.toggle("practice", signedIn && m === "practice");
for (const n of [refs.mode, mode === "min" ? refs.minMode : null]) {
if (!n || !n.isConnected) continue;
const next = n === refs.mode && armed("mode");
n.className = `mode ${next ? other(m) : m}${next ? " armed" : ""}`;
n.textContent = next ? `→ ${MODE_LABEL[other(m)]}` : MODE_LABEL[m];
if (n === refs.mode) {
n.title = m === "practice" ? "Practice mode: trades count toward nothing. Click to switch to Challenge." : "Challenge mode: trades count toward your award. Click to switch to Practice.";
n.setAttribute("aria-label", `${MODE_LABEL[m]} mode. Switch to ${MODE_LABEL[other(m)]}`);
n.disabled = !!S.busy;
}
}
}
const build = {
loading() {
box.append(header(), el("div", { class: "body" }, el("div", { class: "muted" }, S.coinError ?? "Loading…")));
},
signedOut() {
box.append(
header(),
el(
"div",
{ class: "body" },
el("p", { class: "lead" }, "Paper trade this coin with Funded. In Challenge mode, every trade counts toward a 1–5 SOL award."),
el("button", { class: "primary", onclick: () => send({ type: "openConnect" }) }, "Connect your Funded account"),
),
);
},
unsupported() {
box.append(header(), el("div", { class: "body" }, el("p", { class: "muted" }, S.coinError ?? S.quote?.error ?? "This coin can't be paper traded.")));
},
min() {
const pill = el("div", { class: "pill", onpointerdown: drag, onclick: (e) => !e.target.closest("button") && toggleMin() }, logo(), (refs.minMode = el("span", { class: "mode" })), (refs.minBal = el("span", { class: "num" })), (refs.minPnl = el("span", { class: "num" })));
box.append(pill);
},
trade() {
const buyBtns = S.presets.buy.map((v) => el("button", { class: "preset buy", onclick: (e) => trade("buy", v, e) }, String(v)));
const sellBtns = S.presets.sell.map((v) => el("button", { class: "preset sell", onclick: (e) => trade("sell", v, e) }, `${v}%`));
const amount = el("input", { class: "amount", type: "number", min: "0.001", step: "0.01", placeholder: "Amount (SOL)", "aria-label": "Custom buy amount in SOL" });
amount.addEventListener("keydown", (e) => e.key === "Enter" && e.isTrusted && trade("buy", Number(amount.value), e));
refs.buttons = [...buyBtns, ...sellBtns];
const cell = (key, title) => (refs[key] = el("span", { class: "num", title, "aria-label": title }));
box.append(
header(true),
el(
"div",
{ class: "body" },
el("div", { class: "row" }, el("span", { class: "muted" }, "Balance ", (refs.bal = el("b", { class: "num" }))), (refs.mc = el("span", { class: "num muted" }))),
el("div", { class: "label" }, "Buy · SOL"),
el("div", { class: "grid fill" }, ...buyBtns),
el("div", { class: "custom" }, amount, (refs.customBuy = el("button", { class: "preset buy", onclick: (e) => trade("buy", Number(amount.value), e) }, "Buy"))),
el("div", { class: "row label" }, el("span", {}, "Sell · %"), (refs.held = el("span", { class: "num held" }))),
el("div", { class: "grid fill" }, ...sellBtns),
el("div", { class: "row" }, (refs.status = el("div", { class: "status" })), (refs.foot = el("div", { class: "foot" }))),
),
// where this run bought and sold the coin, as market caps, to find on the site's own chart
(refs.avg = el("div", { class: "avg" }, (refs.avgIn = el("span", { class: "in" })), (refs.avgOut = el("span", { class: "out" })))),
// this coin this run, like a trading site's PnL bar: SOL spent buying, received selling, what's held is worth now, and the result
el("div", { class: "pnl" }, cell("pBought", "Bought"), cell("pSold", "Sold"), cell("pHeld", "Holding"), cell("pPnl", "PnL")),
...handles(),
);
refs.buttons.push(refs.customBuy);
},
edit() {
const buy = S.presets.buy.map((v, i) => el("input", { class: "amount", type: "number", value: v, min: "0.001", step: "0.01", "aria-label": `Buy preset ${i + 1} (SOL)` }));
const sell = S.presets.sell.map((v, i) => el("input", { class: "amount", type: "number", value: v, min: "1", max: "100", step: "1", "aria-label": `Sell preset ${i + 1} (%)` }));
box.append(
header(true),
el(
"div",
{ class: "body" },
el("div", { class: "label" }, "Buy presets · SOL"),
el("div", { class: "grid fill" }, ...buy),
el("div", { class: "label" }, "Sell presets · %"),
el("div", { class: "grid fill" }, ...sell),
el(
"label",
{ class: "check" },
el("input", { type: "checkbox", checked: S.marks, onchange: (e) => setMarks(e.target.checked) }),
"Show my trades on the site's chart",
),
el(
"div",
{ class: "row gap" },
el("button", { class: "ghost", onclick: () => savePresets(DEFAULT_PRESETS.buy, DEFAULT_PRESETS.sell) }, "Defaults"),
el("button", { class: "primary", onclick: () => savePresets(buy.map((i) => i.value), sell.map((i) => i.value)) }, "Save"),
),
(refs.status = el("div", { class: "status" })),
),
...handles(),
);
},
};
/** A newer version on the site, for zip installs (Chrome Web Store installs have an update_url and update themselves). */
function updateAvailable() {
const latest = S.view?.extension?.latest;
let me;
try {
me = chrome.runtime.getManifest();
} catch {
return null; // this copy was replaced: the page says to reload instead
}
return latest && !me.update_url && newer(latest, me.version) ? latest : null;
}
function paintStatus() {
if (!refs.status) return;
const st = S.status && S.status.until > Date.now() ? S.status : null;
const upd = updateAvailable();
refs.status.onclick = null;
if (st) {
setText(refs.status, st.text);
refs.status.className = `status ${st.tone}`;
} else if (mode === "trade" && !S.busy && upd) {
setText(refs.status, `Update available: v${upd} ↗`);
refs.status.className = "status warn link";
refs.status.onclick = () => send({ type: "openSite", path: "/extension" });
} else if (mode === "trade") {
const practice = modeOf() === "practice";
setText(refs.status, S.busy ? ({ buy: "Buying…", sell: "Selling…", mode: "Switching…", refill: "Resetting…" }[S.busy] ?? "…") : practice ? "Practice · counts toward nothing" : "✓ Counts toward your award · checked on chain");
refs.status.className = `status ${S.busy ? "dim" : practice ? "practice" : "ok"}`;
} else setText(refs.status, "");
}
const update = {
edit: paintStatus,
trade() {
const run = S.view.run;
setText(refs.bal, fmtSol(run.cash));
const px = spot();
if (px && S.quote.supply) {
const mcSol = px * S.quote.supply;
setText(refs.mc, S.quote.solUsd ? `MC $${fmtNum(mcSol * S.quote.solUsd)}` : `MC ${fmtSol(mcSol)}`);
}
for (const b of refs.buttons) b.disabled = !!S.busy || !!S.quote?.error;
const pos = position_();
const value = pos ? exitValue(pos.qty) : 0;
const sym = S.meta?.symbol ? `$${S.meta.symbol}` : "";
setText(refs.held, pos ? `${fmtNum(pos.qty)} ${sym} · ${value === null ? "…" : fmtSol(value)}` : "");
// the bar: what this run spent on and got back from the coin, plus what's held is worth if sold now
const c = S.coin?.mint === S.mint ? S.coin : null;
const pnl = c && value !== null ? c.sold + value - c.bought : null;
setText(refs.pBought, c ? fmtBar(c.bought) : "…");
setText(refs.pSold, c ? fmtBar(c.sold) : "…");
setText(refs.pHeld, value === null ? "…" : fmtBar(value));
setText(refs.pPnl, pnl === null ? "…" : `${fmtBar(pnl, true)} (${fmtBarPct(c.bought > 0 ? (pnl / c.bought) * 100 : 0)})`);
refs.pPnl.className = `num strong ${pnl === null || Math.abs(pnl) < 5e-5 ? "" : pnl > 0 ? "up" : "down"}`;
// avg entry and exit, as market caps (dollars when the SOL price is known: each fill at the SOL price
// when it happened, so they don't move with SOL), like the site's chart
const mc = (px, usd) => (px && S.quote?.supply ? (S.quote.solUsd ? `$${fmtNum((usd ?? px * S.quote.solUsd) * S.quote.supply)}` : fmtSol(px * S.quote.supply)) : null);
const avgIn = mc(c?.avgEntry, c?.avgEntryUsd);
const avgOut = mc(c?.avgExit, c?.avgExitUsd);
refs.avg.hidden = !avgIn && !avgOut;
refs.avgIn.replaceChildren(el("span", { class: "dim" }, "Avg entry "), el("b", {}, avgIn ?? "—"));
refs.avgOut.replaceChildren(el("span", { class: "dim" }, "Avg exit "), el("b", {}, avgOut ?? "—"));
refs.avg.title = "Average market cap of your buys and of your sells of this coin, before fees: find them on the site's chart";
// Challenge: 80% down from the peak since the last reset, nothing open, and it raises the target.
// Practice: any time.
refs.foot.replaceChildren();
if (run.canReset) {
const practice = modeOf() === "practice";
const title = practice ? "Start Practice over. It never affects your Challenge." : `Your balance target rises to ${run.nextTargetSol} SOL`;
refs.foot.append(el("button", { class: "link", disabled: !!S.busy, title, onclick: (e) => refill(e) }, armed("reset") ? "Confirm reset" : `Reset to ◎${run.startSol}`));
}
if (S.quote?.error) S.status = { text: S.quote.error, tone: "down", until: Date.now() + 2000 };
paintStatus();
},
min() {
setText(refs.minBal, S.view?.run ? fmtSol(S.view.run.cash) : "");
const pos = position_();
const value = pos ? exitValue(pos.qty) : null;
if (pos && value !== null) {
const pct = ((value - pos.costSol) / pos.costSol) * 100;
setText(refs.minPnl, fmtPct(pct));
refs.minPnl.className = `num ${pct >= 0 ? "up" : "down"}`;
} else setText(refs.minPnl, "");
},
};
// ───────────── data ─────────────
/** A new account view; its coin totals count only if they're for this page's coin. */
function takeView(v) {
S.view = v;
if (v?.coin && v.coin.mint === S.mint) S.coin = v.coin;
}
async function refreshAccount(force) {
const r = await send({ type: "account", force, mint: S.mint ?? undefined });
if (r.stale) return;
S.signedIn = !!r.signedIn;
if (r.view !== undefined) takeView(r.view);
if (!r.signedIn) S.view = null;
render();
}
let quoteTimer = null;
let quoting = false;
async function pump() {
clearTimeout(quoteTimer);
if (!S.mint || document.visibilityState !== "visible") return;
if (!quoting) {
quoting = true;
const mint = S.mint;
const q = await send({ type: "quote", mint });
quoting = false;
if (mint !== S.mint || q.stale) return;
// keep the last good price through a brief RPC hiccup
if (!(q.error && q.retry && S.quote?.pool)) S.quote = q;
if (!q.error) S.quoteAt = Date.now();
// the coin's pools don't change with its price: kept through any error
if (q.pools) S.pools = q.pools;
render();
}
quoteTimer = setTimeout(pump, S.minimized ? 4000 : 1000);
}
async function onPage() {
const page = globalThis.FundedSites.detect(location);
const same = page && S.page && page.address === S.page.address;
S.page = page;
if (same) return;
S.mint = null;
S.quote = null;
S.pools = null;
S.meta = null;
S.coin = null;
S.coinError = null;
S.editing = false;
clearTimeout(quoteTimer);
render(true);
if (!page) return;
const r = await send({ type: "resolve", address: page.address, kind: page.kind });
if (S.page?.address !== page.address) return;
if (r.error) {
S.coinError = r.error;
render(true);
if (r.retry) setTimeout(() => S.page?.address === page.address && ((S.page = null), onPage()), typeof r.retry === "number" ? r.retry : 4000);
return;
}
S.mint = r.mint;
refreshAccount(false); // this coin's totals
send({ type: "meta", mint: r.mint }).then((m) => {
if (S.mint === r.mint && m && !m.error) {
S.meta = m;
render(true);
}
});
pump();
}
// ───────────── boot ─────────────
chrome.storage.onChanged.addListener((changes, area) => {
if (area === "local" && changes.soundBuy) void decodeSound(changes.soundBuy.newValue).then((s) => (sounds.buy = s));
if (area === "local" && changes.soundSell) void decodeSound(changes.soundSell.newValue).then((s) => (sounds.sell = s));
if (area === "local" && changes.soundVolume) takeVolume(changes.soundVolume.newValue);
if (area === "sync" && changes.presets) {
S.presets = normPresets(changes.presets.newValue);
if (mode === "trade") render(true);
}
if (area === "sync" && changes.chartMarks) {
S.marks = changes.chartMarks.newValue !== false;
render();
}
if (area === "local" && (changes.auth || changes.account)) {
if (changes.auth && !changes.auth.newValue) {
S.signedIn = false;
S.view = null;
}
if (changes.account?.newValue) {
S.signedIn = true;
takeView(changes.account.newValue.view);
} else if (changes.auth?.newValue) refreshAccount(true);
render();
}
});
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
pump();
refreshAccount(false);
}
});
(async () => {
const [{ presets, chartMarks }, { panelPos }] = await Promise.all([chrome.storage.sync.get(["presets", "chartMarks"]), chrome.storage.local.get("panelPos")]);
S.presets = normPresets(presets);
S.marks = chartMarks !== false;
const saved = panelPos?.[location.hostname];
if (saved && Number.isFinite(saved.x)) S.pos = { x: saved.x, y: saved.y };
if (saved && Number.isFinite(saved.w) && Number.isFinite(saved.h)) S.size = { w: saved.w, h: saved.h };
S.minimized = !!saved?.min;
await refreshAccount(false);
await onPage();
// single-page sites change the address without reloading
let href = location.href;
setInterval(() => {
if (location.href !== href) {
href = location.href;
onPage();
}
// let expired status messages and unconfirmed clicks fade
if (S.armed && S.armed.until < Date.now()) S.armed = null;
if (S.status && S.status.until < Date.now() && mode !== "hidden") {
S.status = null;
render();
}
// a price that went stale with no quote since (Solana's RPC not answering, a hidden tab) stops going to the chart
sendChart();
}, 500);
})();
function CSS() {
// sizes are in em, so a resized panel scales as a whole: its text follows the panel's width and height
return `
:host { all: initial; }
* { box-sizing: border-box; }
.panel {
position: relative; display: flex; flex-direction: column;
width: 268px; font: 12.5px/1.35 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color: #eef0ea;
background: rgba(15, 19, 17, 0.97); border: 1px solid #36423b; border-radius: 12px;
box-shadow: 0 16px 48px rgba(0,0,0,.45); overflow: hidden; -webkit-font-smoothing: antialiased;
}
.panel.min { width: auto; border-radius: 999px; }
.panel.sized { container-type: size; }
.panel.sized > .head, .panel.sized > .body, .panel.sized > .pnl { font-size: clamp(11px, min(4.25cqw, 3.55cqh), 20px); }
.head { display: flex; align-items: center; gap: .5em; padding: .62em .62em .62em .8em; background: #161b18; border-bottom: 1px solid #27302b; cursor: grab; user-select: none; flex: none; }
.head:active { cursor: grabbing; }
.logo { display: inline-flex; }
.logo svg { width: 1.45em; height: 1.45em; }
.brand { font: 700 .84em/1 ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace; letter-spacing: .18em; }
/* the mode tag: Challenge green, Practice amber (the site uses the same colors) */
.mode { all: unset; box-sizing: border-box; flex: none; padding: .36em .55em; border-radius: .45em; border: 1px solid; cursor: pointer; white-space: nowrap;
font: 700 .72em/1 ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace; letter-spacing: .12em; text-transform: uppercase; }
.mode.challenge { color: #82d4a5; border-color: rgba(130,212,165,.45); background: rgba(130,212,165,.12); }
.mode.practice { color: #f0c36a; border-color: rgba(240,195,106,.5); background: rgba(240,195,106,.13); }
.mode.armed { border-style: dashed; }
button.mode:hover:not([disabled]) { filter: brightness(1.18); }
button.mode[disabled] { opacity: .6; cursor: default; }
.pill .mode { font-size: 9.5px; padding: 3px 5px; cursor: inherit; }
.panel.practice { border-color: rgba(240,195,106,.62); }
.panel.practice > .head, .panel.practice > .pnl { background: linear-gradient(rgba(240,195,106,.07), rgba(240,195,106,.07)), #161b18; }
.sym { font-weight: 600; color: #a5b2a9; max-width: 8em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.grow { flex: 1; }
.icon { all: unset; display: inline-grid; place-items: center; width: 1.76em; height: 1.76em; border-radius: .5em; color: #7f8d84; cursor: pointer; font-size: 1.04em; }
.icon:hover { background: rgba(238,240,234,.07); color: #eef0ea; }
.icon:focus-visible, button:focus-visible, input:focus-visible { outline: 2px solid #78d09f; outline-offset: 1px; }
.body { padding: .8em; display: grid; gap: .56em; }
.sized .body { flex: 1; min-height: 0; display: flex; flex-direction: column; gap: .5em; }
.sized .body > :not(.fill) { flex: none; }
.row { display: flex; align-items: center; justify-content: space-between; gap: .64em; min-width: 0; }
.row.gap { justify-content: flex-end; }
.check { display: flex; align-items: center; gap: .5em; color: #a5b2a9; cursor: pointer; font-size: .92em; flex: none; }
.check input { accent-color: #78d09f; width: 1.05em; height: 1.05em; margin: 0; }
.label { font: 600 .76em/1 ui-monospace, Menlo, Consolas, monospace; letter-spacing: .12em; text-transform: uppercase; color: #7f8d84; margin-top: .2em; }
.held { font-size: 1.18em; letter-spacing: 0; text-transform: none; color: #a5b2a9; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: .45em; }
.sized .grid.fill { flex: 1; min-height: 3.4em; grid-template-rows: repeat(2, 1fr); }
.num { font-family: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace; font-variant-numeric: tabular-nums; }
/* Solana's mark in front of SOL amounts */
.sol { display: inline-block; width: .9em; height: .75em; vertical-align: -.04em; margin-right: .16em; }
.muted { color: #a5b2a9; }
.dim { color: #7f8d84; }
.up { color: #82d4a5; }
.down { color: #f2909c; }
.strong { font-weight: 700; }
b { color: #eef0ea; }
.lead { margin: 0; color: #a5b2a9; }
button { font: inherit; }
.preset {
all: unset; box-sizing: border-box; height: 2.4em; display: grid; place-items: center; border-radius: .8em; cursor: pointer; min-width: 0;
font: 600 .96em/1 ui-monospace, Menlo, Consolas, monospace; border: 1px solid #27302b; background: rgba(238,240,234,.03); color: #eef0ea;
}
.sized .grid.fill > .preset, .sized .grid.fill > .amount { height: auto; min-height: 0; }
.preset:hover:not([disabled]) { border-color: #36423b; background: rgba(238,240,234,.07); }
.preset.buy { color: #82d4a5; border-color: rgba(130,212,165,.42); background: rgba(130,212,165,.13); }
.preset.buy:hover:not([disabled]) { background: rgba(130,212,165,.22); }
.preset.sell { color: #f2909c; border-color: rgba(242,144,156,.42); background: rgba(242,144,156,.13); }
.preset.sell:hover:not([disabled]) { background: rgba(242,144,156,.22); }
.preset[disabled] { opacity: .45; cursor: default; }
.custom { display: grid; grid-template-columns: 1fr 5.2em; gap: .45em; flex: none; }
.amount {
all: unset; box-sizing: border-box; height: 2.4em; padding: 0 .72em; border-radius: .8em; border: 1px solid #27302b; background: #161b18;
font: .96em/1 ui-monospace, Menlo, Consolas, monospace; color: #eef0ea; width: 100%; min-width: 0;
}
.grid .amount { text-align: center; padding: 0 .3em; }
/* no up/down arrows in the number boxes: amounts are typed */
input[type=number] { -moz-appearance: textfield; appearance: textfield; }
input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; appearance: none; margin: 0; }
.amount::placeholder { color: #7f8d84; }
.status { flex: 1; min-width: 0; min-height: 1.3em; font-size: .92em; color: #7f8d84; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
.status.ok { color: #82d4a5; }
.status.up { color: #82d4a5; }
.status.down { color: #f2909c; }
.status.warn { color: #f0c36a; }
.status.practice { color: #f0c36a; }
.status.link { cursor: pointer; text-decoration: underline; text-underline-offset: 2px; }
.foot { flex: none; }
.foot:empty { display: none; }
.primary { all: unset; box-sizing: border-box; text-align: center; padding: .72em .96em; border-radius: .64em; background: #78d09f; color: #0c1d14; font-weight: 700; cursor: pointer; }
.primary:hover { filter: brightness(1.08); }
.ghost { all: unset; padding: .64em .8em; border-radius: .64em; color: #a5b2a9; cursor: pointer; }
.ghost:hover { color: #eef0ea; background: rgba(238,240,234,.06); }
.link { all: unset; color: #a5b2a9; text-decoration: underline; cursor: pointer; font-size: .92em; white-space: nowrap; }
.pill { display: flex; align-items: center; gap: 8px; padding: 7px 12px 7px 8px; cursor: pointer; user-select: none; }
/* avg entry and exit market caps, just above the PnL bar */
.avg { flex: none; display: grid; grid-template-columns: 1fr 1fr; border-top: 1px solid #27302b; background: #131815; }
.avg[hidden] { display: none; }
.avg > span { padding: .45em .6em; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
font: 500 .92em/1.2 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-variant-numeric: tabular-nums; }
.avg > span + span { border-left: 1px solid #27302b; }
.avg .in b { color: #82d4a5; }
.avg .out b { color: #f2909c; }
.panel.practice > .avg { background: linear-gradient(rgba(240,195,106,.05), rgba(240,195,106,.05)), #131815; }
/* this coin's PnL bar: bought · sold · holding · result */
.pnl { flex: none; display: grid; grid-template-columns: 1fr 1fr 1fr 2.3fr; background: #161b18; border-top: 1px solid #27302b; }
.pnl > span { padding: .6em .35em; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #eef0ea;
/* the sans-serif face at full size reads better than the code face at this size */
font: 600 1em/1.2 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-variant-numeric: tabular-nums; letter-spacing: .01em; }
.pnl > span + span { border-left: 1px solid #27302b; }
.pnl > span.strong { font-weight: 700; }
.pnl > span:nth-child(1) { color: #82d4a5; }
.pnl > span:nth-child(2) { color: #f2909c; }
/* resize handles: the side edges, the bottom edge and the bottom corners */
.rz { position: absolute; z-index: 2; touch-action: none; }
.rz-e, .rz-w { top: 0; bottom: 14px; width: 6px; cursor: ew-resize; }
.rz-e { right: 0; }
.rz-w { left: 0; }
.rz-s { left: 14px; right: 14px; bottom: 0; height: 6px; cursor: ns-resize; }
.rz-se, .rz-sw { bottom: 0; width: 14px; height: 14px; }
.rz-se { right: 0; cursor: nwse-resize; }
.rz-sw { left: 0; cursor: nesw-resize; }
.rz-se::after { content: ""; position: absolute; right: 3px; bottom: 3px; width: 7px; height: 7px; opacity: .7;
background: linear-gradient(135deg, transparent 0 45%, #56635b 45% 55%, transparent 55% 70%, #56635b 70% 80%, transparent 80%); }
`;
}
})();
* { box-sizing: border-box; }
body {
margin: 0; width: 300px; padding: 14px; background: #0f1311; color: #eef0ea;
font: 13px/1.4 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
header { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; }
.brand { font: 700 12px/1 ui-monospace, Menlo, Consolas, monospace; letter-spacing: .2em; }
.tag { margin-left: auto; font: 700 9px/1 ui-monospace, Menlo, Consolas, monospace; letter-spacing: .12em; color: #e2c27c; border: 1px solid rgba(226,194,124,.3); background: rgba(226,194,124,.1); padding: 3px 5px; border-radius: 4px; }
.muted { color: #a5b2a9; }
.hint { color: #7f8d84; font-size: 11.5px; margin: 6px 0 0; }
.card { border: 1px solid #27302b; background: #161b18; border-radius: 10px; padding: 10px 12px; margin-bottom: 10px; }
.row { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
.row + .row { margin-top: 6px; }
.num { font-family: ui-monospace, Menlo, Consolas, monospace; font-variant-numeric: tabular-nums; }
.sol { display: inline-block; width: .9em; height: .75em; vertical-align: -.04em; margin-right: .16em; }
.big { font-size: 20px; font-weight: 700; }
.up { color: #82d4a5; }
.down { color: #f2909c; }
.warn { color: #e2c27c; }
.label { font: 600 9.5px/1 ui-monospace, Menlo, Consolas, monospace; letter-spacing: .12em; text-transform: uppercase; color: #7f8d84; }
button { font: inherit; cursor: pointer; }
.primary { width: 100%; border: 0; border-radius: 8px; padding: 10px 12px; background: #78d09f; color: #0c1d14; font-weight: 700; }
.primary:hover { filter: brightness(1.08); }
.ghost { border: 1px solid #27302b; background: transparent; color: #eef0ea; border-radius: 8px; padding: 7px 10px; }
.ghost:hover { border-color: #36423b; }
.linkbtn { border: 0; background: none; color: #a5b2a9; text-decoration: underline; padding: 0; }
.wide { width: 100%; margin-top: 8px; }
/* the mode: Challenge green, Practice amber, like the panel */
.mode { font: 700 10px/1 ui-monospace, Menlo, Consolas, monospace; letter-spacing: .12em; text-transform: uppercase; padding: 4px 6px; border-radius: 5px; border: 1px solid; }
.mode.challenge { color: #82d4a5; border-color: rgba(130,212,165,.45); background: rgba(130,212,165,.12); }
.mode.practice { color: #f0c36a; border-color: rgba(240,195,106,.5); background: rgba(240,195,106,.13); }
.mode-card.challenge { border-color: rgba(130,212,165,.35); }
.mode-card.practice { border-color: rgba(240,195,106,.5); background: #1c1c15; }
:focus-visible { outline: 2px solid #78d09f; outline-offset: 1px; }
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Funded</title>
<link rel="stylesheet" href="popup.css" />
</head>
<body>
<header>
<svg width="22" height="22" viewBox="0 0 64 64" fill="none" aria-hidden="true"><rect width="64" height="64" rx="14" fill="#303234"/><path d="M32 6.5 41.6 19.8 32 29.4 22.4 19.8Z" fill="#6fbc92"/><path d="M6.5 32 19.8 22.4 29.4 32 19.8 41.6Z" fill="#F3EFE6"/><path d="M57.5 32 44.2 22.4 34.6 32 44.2 41.6Z" fill="#B8B9BC"/><path d="M32 57.5 22.4 44.2 32 34.6 41.6 44.2Z" fill="#E4DCCF"/></svg>
<span class="brand">FUNDED</span>
<span class="tag">PAPER</span>
</header>
<main id="main">
<p class="muted">Loading…</p>
</main>
<script src="popup.js" type="module"></script>
</body>
</html>
// Funded extension popup: who's signed in, the mode (Challenge or Practice) and a switch, the paper
// balance and progress, and links to the site. Trading itself happens in the panel on a coin's page.
const main = document.getElementById("main");
const send = (msg) => new Promise((resolve) => chrome.runtime.sendMessage(msg, (r) => resolve(r ?? {})));
function el(tag, attrs = {}, ...kids) {
const n = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (v === undefined || v === null || v === false) continue;
if (k === "class") n.className = v;
else if (k.startsWith("on")) n.addEventListener(k.slice(2), v);
else n.setAttribute(k, String(v));
}
for (const c of kids.flat()) if (c !== null && c !== undefined && c !== false) n.append(...(c instanceof Node ? [c] : solNodes(String(c))));
return n;
}
const svg = (tag, attrs) => {
const n = document.createElementNS("http://www.w3.org/2000/svg", tag);
for (const [k, v] of Object.entries(attrs)) n.setAttribute(k, v);
return n;
};
// SOL amounts are written with "◎" and shown with Solana's mark in its place (as in the panel)
const SOL_PATHS = ["M4 0H24L20 5H0Z", "M0 7.5H20L24 12.5H4Z", "M4 15H24L20 20H0Z"];
let solIds = 0;
const solIcon = () => {
const id = `funded-sol-${++solIds}`;
const mark = svg("svg", { class: "sol", viewBox: "0 0 24 20", role: "img", "aria-label": "SOL" });
const grad = svg("linearGradient", { id, gradientUnits: "userSpaceOnUse", x1: "24", y1: "0", x2: "0", y2: "20" });
grad.append(svg("stop", { offset: "0", "stop-color": "#00FFA3" }), svg("stop", { offset: "1", "stop-color": "#DC1FFF" }));
const defs = svg("defs", {});
defs.append(grad);
mark.append(defs, ...SOL_PATHS.map((d) => svg("path", { d, fill: `url(#${id})` })));
return mark;
};
const solNodes = (s) => s.split("◎").flatMap((part, i) => (i ? [solIcon(), part] : [part])).filter((x) => x !== "").map((x) => (typeof x === "string" ? document.createTextNode(x) : x));
const sol = (v) => `◎${Math.abs(v) >= 100 ? v.toFixed(1) : v.toFixed(3)}`;
const pct = (v) => (Math.abs(v) < 0.05 ? "0.0%" : `${v > 0 ? "+" : ""}${v.toFixed(1)}%`);
const MODE_LABEL = { challenge: "Challenge", practice: "Practice" };
const CHECK = { unchecked: "Not checked yet", checking: "Checking", verified: "Verified on chain", mismatch: "Prices don't match", incomplete: "Partly checked" };
const newer = (a, b) => {
const x = a.split(".").map(Number);
const y = b.split(".").map(Number);
for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) > (y[i] || 0);
return false;
};
/** A newer version on the site, for zip installs (Chrome Web Store installs update themselves). */
function updateCard(view) {
const latest = view?.extension?.latest;
const me = chrome.runtime.getManifest();
if (!latest || me.update_url || !newer(latest, me.version)) return null;
return el(
"div",
{ class: "card" },
el("p", { class: "warn", style: "margin:0 0 6px" }, `Update available: v${latest} (you have v${me.version}).`),
el("button", { class: "ghost", onclick: () => send({ type: "openSite", path: "/extension" }) }, "Get the new version"),
);
}
async function render() {
const a = await send({ type: "account", force: true });
main.replaceChildren();
if (!a.signedIn) {
main.append(
el("p", { class: "muted" }, "Paper trade Solana memecoins on Axiom, GMGN, pump.fun and more. In Challenge mode, every trade counts toward a 1–5 SOL award."),
el("button", { class: "primary", onclick: () => send({ type: "openConnect" }).then(() => window.close()) }, "Connect your Funded account"),
el("p", { class: "hint" }, "You'll log in on fundedsol.trade (just your email), then click Connect."),
);
return;
}
const run = a.view?.run;
main.append(el("div", { class: "row" }, el("span", { class: "muted" }, a.email || "Signed in"), el("button", { class: "linkbtn", onclick: signOut }, "Sign out")), updateCard(a.view) ?? "");
if (!run) {
main.append(
el("div", { class: "card" }, el("p", { class: "muted", style: "margin:0" }, "Setting up your paper account (◎2)…")),
el("button", { class: "primary", onclick: () => send({ type: "openSite", path: "/dashboard" }) }, "Open Funded"),
);
return;
}
const cost = run.positions.reduce((s, p) => s + p.costSol, 0);
const mode = a.view.mode === "practice" ? "practice" : "challenge";
const to = mode === "practice" ? "challenge" : "practice";
const roi = run.roiPct ?? run.points.roiPct;
main.append(
el(
"div",
{ class: `card mode-card ${mode}` },
el("div", { class: "row" }, el("span", { class: "label" }, "Mode"), el("span", { class: `mode ${mode}` }, MODE_LABEL[mode])),
el("p", { class: "hint" }, mode === "practice" ? "Practice counts toward nothing. Reset it any time from the panel; your Challenge isn't affected." : "Challenge trades count toward your award and are checked on chain."),
el("button", { class: "ghost wide", onclick: (e) => switchTo(to, e.currentTarget) }, `Switch to ${MODE_LABEL[to]}`),
),
el(
"div",
{ class: "card" },
el("div", { class: "label" }, `${MODE_LABEL[mode]} balance`),
el("div", { class: "row" }, el("span", { class: "num big" }, sol(run.cash)), el("span", { class: "num muted" }, run.positions.length ? `+ ${sol(cost)} in ${run.positions.length} coin${run.positions.length === 1 ? "" : "s"}` : "")),
el("div", { class: "row" }, el("span", { class: "muted" }, `Started with ${sol(run.startSol)}`), el("span", { class: `num ${Math.abs(roi) < 0.05 ? "muted" : roi > 0 ? "up" : "down"}` }, pct(roi))),
),
mode === "practice"
? el("div", { class: "card" }, el("div", { class: "row" }, el("span", { class: "muted" }, "Trades"), el("span", { class: "num" }, String(run.trades))))
: el(
"div",
{ class: "card" },
el("div", { class: "row" }, el("span", { class: "muted" }, "Points"), el("span", { class: "num" }, run.points.eligible ? run.points.total.toLocaleString("en-US", { maximumFractionDigits: 1 }) : "—")),
el("div", { class: "row" }, el("span", { class: "muted" }, "Trades"), el("span", { class: "num" }, String(run.trades))),
el("div", { class: "row" }, el("span", { class: "muted" }, "Checks"), el("span", { class: run.check.status === "verified" ? "up" : run.check.status === "mismatch" ? "down" : "warn" }, `${CHECK[run.check.status] ?? run.check.status}${run.check.total ? ` · ${run.check.checked}/${run.check.total}` : ""}`)),
!run.points.eligible && run.points.waitingFor ? el("p", { class: "hint" }, `Points start after ${run.points.waitingFor}.`) : null,
),
el("button", { class: "primary", onclick: () => send({ type: "openSite", path: "/dashboard" }) }, "Open your portfolio"),
el("p", { class: "hint" }, "Open a coin on a supported site: the Funded panel appears on the right."),
);
}
async function switchTo(mode, button) {
button.disabled = true;
button.textContent = "Switching…";
const r = await send({ type: "mode", mode });
if (r.error) {
button.disabled = false;
button.textContent = r.error;
return;
}
render();
}
async function signOut() {
await send({ type: "signout" });
render();
}
render();
// Funded extension: which coin is this page about? Read from the address bar only (never the page's
// own scripts or data), so it keeps working when a site redesigns. Loaded before panel.js. (Marking trades
// on the site's chart is chart.js's job, the one part that runs in the page.)
"use strict";
(() => {
const B58 = "[1-9A-HJ-NP-Za-km-z]{32,44}";
// DexScreener lowercases pair addresses in its URLs, which can leave an "l" (not base58) in them
const PAIR = "[1-9A-Za-z]{32,44}";
/** host → how to find the address in the URL, and whether it's the coin itself or a pair/pool. */
const SITES = [
{ host: /(^|\.)pump\.fun$/, path: new RegExp(`^/coin/(${B58})`), kind: "mint", name: "pump.fun" },
{ host: /(^|\.)gmgn\.ai$/, path: new RegExp(`^/sol/token/(?:[A-Za-z0-9]+_)?(${B58})`), kind: "mint", name: "GMGN" },
// Axiom moved coin pages to /token/<mint> (Nov 2026) and redirects its old /meme/ links there
{ host: /(^|\.)axiom\.trade$/, path: new RegExp(`^/(?:token|meme|t)/(${B58})`), kind: "any", name: "Axiom" },
{ host: /(^|\.)padre\.gg$/, path: new RegExp(`^/trade/solana/(${B58})`), kind: "any", name: "Padre" },
{ host: /(^|\.)dexscreener\.com$/, path: new RegExp(`^/solana/(${PAIR})`), kind: "any", name: "DexScreener" },
{ host: /(^|\.)stonkfun\.xyz$/, path: new RegExp(`^/token/(${B58})`), kind: "mint", name: "StonkFun" },
];
/** { address, kind, site } for the coin page this URL shows, or null. */
function detect(loc) {
const site = SITES.find((s) => s.host.test(loc.hostname));
if (!site) return null;
const address = site.path.exec(loc.pathname)?.[1] ?? null;
return address ? { address, kind: site.kind, site: site.name } : null;
}
globalThis.FundedSites = { detect };
})();