Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(papertrade): add four read-only agent tools and /api/papertrade to quote synthetic BTC and ETH perps on HyperEVM and value any wallet's positions
nirholasab7d7e7eab9c
diff --git a/api/_lib/papertrade/index.js b/api/_lib/papertrade/index.jsnew file mode 100644index 000000000..a2f540a80--- /dev/null+++ b/api/_lib/papertrade/index.js@@ -0,0 +1,437 @@+// Papertrade: read-only integration with the synthetic-perps exchange on+// HyperEVM (https://papertrade.xyz). Markets, protocol health, exact open+// quotes and any wallet's live positions, all from the real sources:+//+// instruments, OI, caps exchange API GET /state/trading+// protocol + payout queue exchange API GET /query/protocol/*+// wallet + positions exchange API GET /state/user/live (SSE, first frame)+// win fee HyperEVM winFeeRate() on the exchange contract+// entry / mark price Hyperliquid l2Book BBO, the same mid the contract reads+//+// Nothing here signs, deposits or trades. Every money figure is computed by+// ./math.js at the contract's own fixed-point scales. Guide: docs/papertrade.md.++import { toFunctionSelector } from 'viem';+import { fetchUpstream, fetchUpstreamJson, lastGood } from '../upstream-fetch.js';+import {+ decodeInstrument, decodePosition, midRaw, bustPriceRaw, valuePosition, payoutPnlRaw, isBust, riskPercent,+ openCapacity, usdToRaw, rawToUsd, priceToRaw, rawToPrice, wadToNumber,+} from './math.js';++export const EXCHANGE_API = 'https://exchange.papertrade.xyz';+export const HYPER_EVM_RPC = 'https://rpc.hyperliquid.xyz/evm';+export const HL_INFO_URL = 'https://api.hyperliquid.xyz/info';+export const CHAIN_ID = 999;+export const CONTRACTS = Object.freeze({+ exchange: '0x6cd5661646289fb6e65ea5c032310fded797d0a2',+ collateral: '0x6b9e773128f453f5c2c60935ee2de2cbc5390a24',+});+export const APP_URL = 'https://exchange.papertrade.xyz';+export const DOCS_URL = 'https://docs.papertrade.xyz';++// Price moves in the position's favour that every quote is valued at, in percent.+export const SCENARIO_MOVES_PCT = Object.freeze([0.01, 0.05, 0.1, 0.25, 0.5, 1, 2, 5]);++const HEADERS = { accept: 'application/json', 'user-agent': 'three.ws/1.0 (+https://three.ws)' };+const WIN_FEE_SELECTOR = toFunctionSelector('winFeeRate()');++export class PapertradeError extends Error {+ constructor(status, code, message, detail = null) {+ super(message);+ this.name = 'PapertradeError';+ this.status = status;+ this.code = code;+ this.detail = detail;+ }+}++const fail = (status, code, message, detail = null) => new PapertradeError(status, code, message, detail);++const round = (n, dp = 6) => (n == null || !Number.isFinite(n) ? null : Math.round(n * 10 ** dp) / 10 ** dp);++// ── short-lived read cache ───────────────────────────────────────────────────++const _memo = new Map();+function memo(key, ttlMs, load) {+ const hit = _memo.get(key);+ if (hit && Date.now() - hit.at < ttlMs) return hit.promise;+ const promise = load();+ _memo.set(key, { at: Date.now(), promise });+ promise.catch(() => _memo.get(key)?.promise === promise && _memo.delete(key));+ return promise;+}++async function upstream(what, fn) {+ try {+ return await fn();+ } catch (err) {+ if (err instanceof PapertradeError) throw err;+ throw fail(502, 'upstream_unavailable', `Papertrade data is unavailable right now (${what}). Retry in a moment.`, {+ cause: String(err?.message || err).slice(0, 200),+ });+ }+}++const exchangeGet = (path, name) =>+ fetchUpstreamJson(`${EXCHANGE_API}${path}`, { headers: HEADERS }, { name: `papertrade:${name}`, timeoutMs: 8000, attempts: 2 });++// ── raw reads ────────────────────────────────────────────────────────────────++/**+ * Instruments and global trading parameters. Instrument parameters change only+ * by owner action, so a last good copy (flagged stale) may stand in for one+ * failed read; open interest in a stale copy is reported as such.+ */+export function tradingState() {+ return memo('trading', 5_000, async () => {+ const { value, stale, ageMs } = await upstream('trading state', () =>+ lastGood('papertrade:trading', () => exchangeGet('/state/trading', 'trading'), { maxAgeMs: 10 * 60_000 }));+ if (value?.schemaVersion !== 1 || !Array.isArray(value.instruments)) {+ throw fail(502, 'upstream_schema_changed', 'Papertrade changed its trading-state format; quotes are paused until the integration is updated.', {+ schema_version: value?.schemaVersion ?? null,+ });+ }+ const intake = Array.isArray(value.intake) ? value.intake : null;+ return {+ tradingPaused: value.tradingPaused === true,+ indexedThroughBlock: Number(value.indexedThroughBlock) || null,+ minimumMarginRaw: BigInt(value.minimumTradeSizeRaw),+ minimumOpenNotionalRaw: BigInt(value.minimumOpenNotionalRaw),+ maximumNetOpenInterestRaw: intake && intake[2] != null ? BigInt(intake[2]) : 0n,+ instruments: value.instruments.map(decodeInstrument),+ stale,+ ageMs,+ };+ });+}++/** The win fee, read from the exchange contract (1e18 fraction). */+export function winFeeRate() {+ return memo('winfee', 60_000, () =>+ upstream('win fee', async () => {+ const { value } = await lastGood('papertrade:winfee', async () => {+ const out = await fetchUpstreamJson(HYPER_EVM_RPC, {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_call', params: [{ to: CONTRACTS.exchange, data: WIN_FEE_SELECTOR }, 'latest'] }),+ }, { name: 'papertrade:hyperevm', timeoutMs: 8000, attempts: 2 });+ if (out?.error || typeof out?.result !== 'string' || !/^0x[0-9a-f]+$/i.test(out.result)) {+ throw new Error(`winFeeRate() eth_call failed: ${out?.error?.message || 'no result'}`);+ }+ return BigInt(out.result);+ }, { maxAgeMs: 60 * 60_000 });+ return value;+ }));+}++/**+ * Hyperliquid best bid and ask for one coin, in the instrument's raw price+ * scale. Never served stale: an entry price must be the price now.+ */+export function bbo(instrument) {+ return memo(`bbo:${instrument.symbol}`, 1_500, () =>+ upstream(`${instrument.symbol} price`, async () => {+ const book = await fetchUpstreamJson(HL_INFO_URL, {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify({ type: 'l2Book', coin: instrument.symbol }),+ }, { name: 'hyperliquid:l2book', timeoutMs: 6000, attempts: 2 });+ const bid = book?.levels?.[0]?.[0]?.px;+ const ask = book?.levels?.[1]?.[0]?.px;+ if (bid == null || ask == null) throw new Error(`no ${instrument.symbol} BBO`);+ const bidRaw = priceToRaw(bid, instrument.priceScaleRaw);+ const askRaw = priceToRaw(ask, instrument.priceScaleRaw);+ return { bidRaw, askRaw, midRaw: midRaw(bidRaw, askRaw), at: Number(book.time) || Date.now() };+ }));+}++/** The price a position marks at: the frozen mid for a terminal market, else the live BBO mid. */+async function markFor(instrument) {+ if (instrument.terminal && instrument.frozenBidRaw != null && instrument.frozenAskRaw != null) {+ return { midRaw: midRaw(instrument.frozenBidRaw, instrument.frozenAskRaw), bidRaw: instrument.frozenBidRaw, askRaw: instrument.frozenAskRaw, at: instrument.pausedAtMs, frozen: true };+ }+ return { ...(await bbo(instrument)), frozen: false };+}++function findInstrument(state, symbol) {+ const want = String(symbol || '').trim().toUpperCase().replace(/[-/]?(USD|USDC|PERP)$/, '');+ const inst = state.instruments.find((i) => i.symbol.toUpperCase() === want);+ if (!inst) {+ throw fail(404, 'unknown_market', `Papertrade has no ${want || 'such'} market. Listed: ${state.instruments.map((i) => i.symbol).join(', ')}.`, {+ available: state.instruments.map((i) => i.symbol),+ });+ }+ return inst;+}++function marketStatus(inst, paused) {+ if (inst.retired) return 'retired';+ if (inst.terminal) return 'terminal';+ if (paused || inst.paused) return 'paused';+ if (inst.closeOnly) return 'close_only';+ return inst.active ? 'active' : 'inactive';+}++// ── public service ───────────────────────────────────────────────────────────++/** Every listed market with its live price, limits and open interest. */+export async function markets() {+ const [state, fee, stats] = await Promise.all([+ tradingState(),+ winFeeRate(),+ exchangeGet('/query/protocol/market-stats', 'market-stats').catch(() => null),+ ]);+ const rows = await Promise.all(state.instruments.filter((i) => !i.retired).map(async (inst) => {+ const px = await markFor(inst).catch(() => null);+ const mid = px ? rawToPrice(px.midRaw, inst.priceScaleRaw) : null;+ const oiUsd = (raw) => (mid == null ? null : round((Number(raw / 10n ** 12n) / 1e6) * mid, 2));+ const vol = stats?.markets?.[String(inst.id)]?.volume_24h;+ return {+ symbol: inst.symbol,+ instrument_id: inst.id,+ status: marketStatus(inst, state.tradingPaused),+ openable: inst.openable && !state.tradingPaused,+ mid_price: mid,+ bid: px ? rawToPrice(px.bidRaw, inst.priceScaleRaw) : null,+ ask: px ? rawToPrice(px.askRaw, inst.priceScaleRaw) : null,+ price_at: px?.at ?? null,+ price_source: px?.frozen ? 'frozen_at_pause' : px ? 'hyperliquid_bbo_mid' : null,+ max_leverage: inst.maxLeverage,+ max_position_notional_usd: rawToUsd(inst.maxPositionNotionalRaw),+ bust_buffer_bps: round(wadToNumber(inst.bustBufferRaw) * 10_000, 3),+ open_interest_long_usd: oiUsd(inst.longOiRaw),+ open_interest_short_usd: oiUsd(inst.shortOiRaw),+ volume_24h_usd: vol != null ? rawToUsd(BigInt(vol)) : null,+ };+ }));+ return {+ venue: 'papertrade',+ chain_id: CHAIN_ID,+ collateral: 'USDC',+ trading_paused: state.tradingPaused,+ min_margin_usd: rawToUsd(state.minimumMarginRaw),+ min_notional_usd: rawToUsd(state.minimumOpenNotionalRaw),+ win_fee_pct: round(wadToNumber(fee) * 100, 4),+ funding: 'none',+ stale: state.stale,+ markets: rows,+ links: { app: APP_URL, docs: DOCS_URL },+ };+}++/** Protocol health: TVL, LP, payout queue, fees, relayer readiness. */+export async function protocol() {+ const [summary, queue, relayer, fee] = await Promise.all([+ upstream('protocol summary', () => exchangeGet('/query/protocol/summary', 'summary')),+ exchangeGet('/query/protocol/queue-summary', 'queue').catch(() => null),+ exchangeGet('/relayer/health', 'relayer').catch(() => null),+ winFeeRate(),+ ]);+ const b = summary?.balances || {};+ const usd = (v) => (v == null ? null : rawToUsd(BigInt(v)));+ const queueTotal = queue?.total != null ? usd(queue.total) : null;+ return {+ venue: 'papertrade',+ as_of: summary?.source?.at ?? null,+ block: summary?.source?.block ?? null,+ live_since: summary?.source?.genesis ?? null,+ tvl_usd: usd(b.tvl),+ margin_locked_usd: usd(b.margin),+ lp_usd: usd(b.lp),+ reserve_usd: usd(b.reserve),+ open_positions: summary?.activity?.open ?? null,+ lifetime_volume_usd: usd(summary?.activity?.volume),+ lifetime_fees_usd: usd(summary?.fees?.lifetime),+ win_fee_pct: round(wadToNumber(fee) * 100, 4),+ payout_queue: queue+ ? { total_usd: queueTotal, entries: queue.count ?? 0, active: (queue.count ?? 0) > 0 }+ : null,+ relayer_ready: relayer ? relayer.ok === true && relayer.ready === true : null,+ risk_notes: [+ 'Winning closes are paid from one LP; when it is short, the unpaid profit waits in a first-in, first-out payout queue.',+ 'The contracts are upgradeable by the protocol owner through a timelock.',+ ],+ };+}++function validateOpen({ symbol, side, marginUsd, leverage }) {+ if (side !== 'long' && side !== 'short') throw fail(400, 'invalid_side', 'side must be "long" or "short".');+ const margin = Number(marginUsd);+ if (!Number.isFinite(margin) || margin <= 0 || margin > 10_000_000) throw fail(400, 'invalid_margin', 'margin_usd must be a positive number of USDC, at most 10,000,000.');+ const lev = Number(leverage);+ if (!Number.isInteger(lev) || lev < 1) throw fail(400, 'invalid_leverage', 'leverage must be a whole number of at least 1.');+ if (!symbol) throw fail(400, 'symbol_required', 'symbol is required, e.g. BTC or ETH.');+ return { margin, lev };+}++function scenario(position, inst, fee, movePct, direction) {+ const entry = position.entryPriceRaw;+ const delta = (entry * BigInt(Math.round(movePct * 10_000))) / 1_000_000n;+ const up = direction === 'favour' ? position.isLong : !position.isLong;+ const exit = up ? entry + delta : entry - delta;+ const v = valuePosition(position, exit, inst);+ const payout = payoutPnlRaw(v.adjustedPnlRaw, fee);+ const raw = rawToUsd(v.rawPnlRaw);+ const paid = rawToUsd(payout);+ return {+ move_pct: direction === 'favour' ? movePct : -movePct,+ exit_price: rawToPrice(exit, inst.priceScaleRaw),+ raw_pnl_usd: raw,+ payout_pnl_usd: paid,+ kept_pct: v.rawPnlRaw > 0n ? round((paid / raw) * 100, 2) : null,+ busted: isBust(position, exit),+ };+}++/**+ * Price an open exactly as the exchange would fill it right now: entry at the+ * BBO mid, the hard-bust trigger, the capacity limits, and what the position+ * would actually pay out across a ladder of favourable moves.+ */+export async function quote({ symbol, side, marginUsd, leverage }) {+ const { margin, lev } = validateOpen({ symbol, side, marginUsd, leverage });+ const [state, fee] = await Promise.all([tradingState(), winFeeRate()]);+ const inst = findInstrument(state, symbol);+ const px = await markFor(inst);+ const isLong = side === 'long';+ const marginRaw = usdToRaw(margin);+ const notionalRaw = marginRaw * BigInt(lev);+ const entryRaw = px.midRaw;+ const position = { isLong, entryPriceRaw: entryRaw, marginRaw, leverage: lev, bustPriceRaw: bustPriceRaw(entryRaw, lev, isLong, inst.bustBufferRaw) };+ const cap = openCapacity({ instrument: inst, isLong, leverage: lev, markRaw: entryRaw, maximumNetOpenInterestRaw: state.maximumNetOpenInterestRaw });++ const checks = [+ { id: 'market_open', ok: inst.openable && !state.tradingPaused, label: `${inst.symbol} is ${marketStatus(inst, state.tradingPaused)}` },+ { id: 'leverage', ok: lev <= inst.maxLeverage, label: `Leverage ${lev}x within the ${inst.maxLeverage}x market maximum` },+ { id: 'min_margin', ok: marginRaw >= state.minimumMarginRaw, label: `Margin at least $${rawToUsd(state.minimumMarginRaw)}` },+ { id: 'min_notional', ok: notionalRaw >= state.minimumOpenNotionalRaw, label: `Notional at least $${rawToUsd(state.minimumOpenNotionalRaw).toLocaleString('en-US')}` },+ { id: 'capacity', ok: cap.maxMarginRaw == null || marginRaw <= cap.maxMarginRaw, label: cap.maxMarginRaw == null ? 'No capacity limit applies' : `Margin within the $${rawToUsd(cap.maxMarginRaw).toLocaleString('en-US')} the market can take at ${lev}x (${cap.limitedBy})` },+ ];++ const bust = rawToPrice(position.bustPriceRaw, inst.priceScaleRaw);+ const entry = rawToPrice(entryRaw, inst.priceScaleRaw);+ return {+ venue: 'papertrade',+ symbol: inst.symbol,+ side,+ margin_usd: rawToUsd(marginRaw),+ leverage: lev,+ notional_usd: rawToUsd(notionalRaw),+ entry_price: entry,+ price_source: px.frozen ? 'frozen_at_pause' : 'hyperliquid_bbo_mid',+ price_at: px.at,+ bust_price: bust,+ bust_distance_pct: round((Math.abs(entry - bust) / entry) * 100, 4),+ loss_at_bust_usd: -rawToUsd(marginRaw),+ max_margin_usd: cap.maxMarginRaw == null ? null : rawToUsd(cap.maxMarginRaw),+ win_fee_pct: round(wadToNumber(fee) * 100, 4),+ fees_at_open_usd: 0,+ funding: 'none',+ scenarios: SCENARIO_MOVES_PCT.map((m) => scenario(position, inst, fee, m, 'favour')),+ checks,+ openable: checks.every((c) => c.ok),+ blocked_by: checks.filter((c) => !c.ok).map((c) => c.id),+ stale_market_params: state.stale,+ notes: [+ 'Entry is the Hyperliquid best-bid/ask mid at the moment the relayer lands the intent, so a live fill can differ from this quote by however far the mid moves in between.',+ 'Crossing the bust price forfeits the full margin, even when a voluntary close just before would have returned some of it.',+ 'Profit on a winning close passes a 0.2 bps deadband, the impact haircut and the win fee; scenarios show what is actually paid.',+ ],+ trade_url: APP_URL,+ };+}++const ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;++/** Read the first `wallet` frame of the exchange's live wallet stream. */+async function walletFrame(address) {+ const res = await fetchUpstream(`${EXCHANGE_API}/state/user/live?wallet=${address}`, {+ headers: { ...HEADERS, accept: 'text/event-stream' },+ }, { name: 'papertrade:wallet', timeoutMs: 8000, attempts: 1 });+ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buf = '';+ try {+ while (buf.length < 4_000_000) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += decoder.decode(value, { stream: true });+ let cut;+ while ((cut = buf.indexOf('\n\n')) !== -1) {+ const block = buf.slice(0, cut);+ buf = buf.slice(cut + 2);+ const event = /^event: (.+)$/m.exec(block)?.[1]?.trim();+ if (event !== 'wallet') continue;+ const data = block.split('\n').filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trimStart()).join('\n');+ return JSON.parse(data);+ }+ }+ } finally {+ reader.cancel().catch(() => {});+ }+ throw new Error('wallet stream closed before its first wallet frame');+}++/**+ * Any wallet's Papertrade account, read from public chain-indexed state:+ * balances, lifetime totals, and every open position valued at the live mid+ * (raw PnL, what a close would pay, bust distance).+ */+export async function account(address) {+ if (!ADDRESS_RE.test(String(address || ''))) throw fail(400, 'invalid_address', 'address must be a 0x-prefixed 40-hex-character EVM wallet address.');+ const wallet = String(address).toLowerCase();+ const [state, fee, frame] = await Promise.all([tradingState(), winFeeRate(), upstream('wallet state', () => walletFrame(wallet))]);+ const byId = new Map(state.instruments.map((i) => [i.id, i]));+ const marks = new Map();+ const positions = [];+ for (const tuple of frame.openPositions || []) {+ const p = decodePosition(tuple);+ const inst = byId.get(p.instrumentId);+ if (!inst) continue;+ if (!marks.has(inst.id)) marks.set(inst.id, await markFor(inst).catch(() => null));+ const px = marks.get(inst.id);+ const valued = px ? valuePosition(p, px.midRaw, inst) : null;+ positions.push({+ id: p.id,+ symbol: inst.symbol,+ side: p.isLong ? 'long' : 'short',+ margin_usd: rawToUsd(p.marginRaw),+ leverage: p.leverage,+ notional_usd: rawToUsd(p.marginRaw * BigInt(p.leverage)),+ entry_price: rawToPrice(p.entryPriceRaw, inst.priceScaleRaw),+ bust_price: rawToPrice(p.bustPriceRaw, inst.priceScaleRaw),+ mark_price: px ? rawToPrice(px.midRaw, inst.priceScaleRaw) : null,+ raw_pnl_usd: valued ? rawToUsd(valued.rawPnlRaw) : null,+ close_payout_pnl_usd: valued ? rawToUsd(payoutPnlRaw(valued.adjustedPnlRaw, fee)) : null,+ risk_pct: px ? riskPercent(p, px.midRaw) : null,+ bust_crossed: px ? isBust(p, px.midRaw) : null,+ margin_from_queue: p.useDebt,+ opened_at: new Date(p.openedAtMs).toISOString(),+ });+ }+ positions.sort((a, b) => b.notional_usd - a.notional_usd);+ const funds = frame.funds || {};+ const life = frame.lifetime || {};+ const usd = (v) => (v == null ? null : rawToUsd(BigInt(v)));+ const unrealized = positions.reduce((s, p) => (p.close_payout_pnl_usd == null ? s : s + p.close_payout_pnl_usd), 0);+ return {+ venue: 'papertrade',+ address: wallet,+ indexed_through_block: frame.indexedThroughBlock ?? null,+ balance_usd: usd(frame.balance),+ available_usd: usd(funds.availableBalance),+ locked_margin_usd: usd(frame.locked),+ queued_payout_usd: usd(frame.queued),+ session_key_active: Array.isArray(frame.sessionKeys) && frame.sessionKeys.some(([, exp]) => Number(exp) * 1000 > Date.now()),+ open_positions: positions.length,+ close_all_payout_pnl_usd: round(unrealized, 6),+ lifetime: {+ deposited_usd: usd(life.depositedRaw),+ withdrawn_usd: usd(life.withdrawnRaw),+ realized_pnl_usd: usd(life.realizedPnlRaw),+ fees_paid_usd: usd(life.feesPaidRaw),+ traded_notional_usd: usd(life.tradedNotionalRaw),+ },+ positions,+ };+}diff --git a/api/_lib/papertrade/math.js b/api/_lib/papertrade/math.jsnew file mode 100644index 000000000..06c48835c--- /dev/null+++ b/api/_lib/papertrade/math.js@@ -0,0 +1,233 @@+// Papertrade position math: pure, BigInt, at the contract's own scales.+//+// Papertrade (HyperEVM, chain 999) is not an order book. Every position is a+// synthetic swap against one LP, entered and exited at Hyperliquid's BBO mid,+// with isolated margin fixed at open. Its economics differ from a normal perp+// in three ways, and getting them wrong misprices every quote:+//+// 1. A 0.2 bps jitter deadband: a win is measured as if the exit were+// entry/50000 less favourable, so a move inside that pays nothing.+// 2. An asymmetric impact haircut on the gain only. The kept share is+// (1 - baseRate) / (1 + 1/(move*rateMultiplier)+// + referenceNotional/(1e6*move*positionMultiplier))+// so small moves keep little and large moves approach (1 - baseRate).+// 3. A win fee (read live from the contract's winFeeRate()) on what remains.+// Losses pay nothing on top of the loss, and a loss is floored at the+// full isolated margin.+//+// Liquidation is a hard bust: the trigger sits a fixed buffer (instrument+// bustBufferRaw, about 5 bps) closer to entry than the zero-equity price, and+// crossing it forfeits the whole margin.+//+// Scales: collateral and every fraction are 1e18 fixed point; prices are+// integers in the instrument's price scale (BTC 10, ETH 100), the same raw+// units Hyperliquid's BBO precompile reports. Integer division here rounds the+// same way the contract does, which is why this file never touches floats+// until the final USD conversion. Behaviour documented at+// https://docs.papertrade.xyz and verified against live positions (see+// tests/papertrade-math.test.js).++export const WAD = 10n ** 18n;+const U64_MAX = (1n << 64n) - 1n;+// A side cap at or above this is the contract's "no cap" sentinel.+const UNCAPPED = 1n << 127n;++const big = (v) => (v == null ? null : BigInt(v));++/** USD number -> 1e18 collateral raw (cent-and-below precision kept to 1e-6). */+export function usdToRaw(usd) {+ return BigInt(Math.round(Number(usd) * 1e6)) * 10n ** 12n;+}++/** 1e18 collateral raw -> USD number, rounded to 1e-6. */+export function rawToUsd(raw) {+ if (raw == null) return null;+ const r = BigInt(raw);+ const neg = r < 0n;+ const micros = (neg ? -r : r) / 10n ** 12n;+ return (neg ? -1 : 1) * (Number(micros) / 1e6);+}++/** Price number -> raw integer at the instrument's price scale. */+export function priceToRaw(price, scaleRaw) {+ return BigInt(Math.round(Number(price) * Number(scaleRaw)));+}++/** Raw price -> number. */+export function rawToPrice(raw, scaleRaw) {+ return raw == null ? null : Number(raw) / Number(scaleRaw);+}++/** 1e18 fraction -> plain number. */+export function wadToNumber(raw) {+ return raw == null ? null : Number(BigInt(raw) * 1_000_000n / WAD) / 1e6;+}++/**+ * Decode one `/state/trading` instrument tuple. Field order is the exchange's+ * wire schema (schemaVersion 1).+ */+export function decodeInstrument(t) {+ if (!Array.isArray(t) || t.length < 23) throw new TypeError('papertrade: malformed instrument tuple');+ const [id, symbol, assetIndex, priceScale, active, paused, terminal, retired, closeOnly, frozenBid, frozenAsk, pausedAt,+ rateMultiplier, positionMultiplier, maxLeverage, maxPositionNotional, bustBuffer, baseRate, referenceNotional,+ longOi, shortOi, longCap, shortCap] = t;+ return {+ id: Number(id),+ symbol: String(symbol),+ assetIndex: Number(assetIndex),+ priceScaleRaw: big(priceScale),+ active: active === true,+ paused: paused === true,+ terminal: terminal === true,+ retired: retired === true,+ closeOnly: closeOnly === true,+ openable: active === true && paused !== true && closeOnly !== true && retired !== true,+ frozenBidRaw: big(frozenBid),+ frozenAskRaw: big(frozenAsk),+ pausedAtMs: pausedAt == null ? null : Number(pausedAt),+ rateMultiplierRaw: big(rateMultiplier),+ positionMultiplierRaw: big(positionMultiplier),+ maxLeverage: Number(maxLeverage),+ maxPositionNotionalRaw: big(maxPositionNotional),+ bustBufferRaw: big(bustBuffer),+ baseRateRaw: big(baseRate),+ referenceNotionalRaw: big(referenceNotional),+ longOiRaw: big(longOi),+ shortOiRaw: big(shortOi),+ longCapRaw: big(longCap),+ shortCapRaw: big(shortCap),+ };+}++/** Decode one open-position tuple from the wallet stream. */+export function decodePosition(t) {+ if (!Array.isArray(t) || t.length < 9) throw new TypeError('papertrade: malformed position tuple');+ const [id, instrumentId, isLong, useDebt, entry, margin, leverage, bust, openedAt, intentId] = t;+ return {+ id: String(id),+ instrumentId: Number(instrumentId),+ isLong: isLong === true,+ useDebt: useDebt === true,+ entryPriceRaw: BigInt(entry),+ marginRaw: BigInt(margin),+ leverage: Number(leverage),+ bustPriceRaw: BigInt(bust),+ openedAtMs: Number(openedAt),+ intentId: intentId == null ? null : String(intentId),+ };+}++/** Mid of a BBO at raw scale, truncated the way the contract truncates. */+export function midRaw(bidRaw, askRaw) {+ return (BigInt(bidRaw) + BigInt(askRaw)) / 2n;+}++/**+ * The hard-bust trigger for a new position: the zero-equity price (entry moved+ * by entry/leverage against the position), pulled `bustBufferRaw` closer to+ * entry.+ */+export function bustPriceRaw(entryRaw, leverage, isLong, bustBufferRaw) {+ const entry = BigInt(entryRaw);+ const step = entry / BigInt(leverage);+ const zero = isLong ? entry - step : entry + step;+ const buffer = BigInt(bustBufferRaw);+ return isLong ? zero + (zero * buffer) / WAD : zero - (zero * buffer) / WAD;+}++/**+ * Value a position at an exit price. Returns the raw PnL (move times notional)+ * and the adjusted PnL the contract credits: deadband and impact haircut on a+ * gain, the loss floored at the margin otherwise. Both 1e18 collateral raw.+ */+export function valuePosition(position, exitRaw, instrument) {+ const entry = BigInt(position.entryPriceRaw);+ const exit = BigInt(exitRaw);+ const margin = BigInt(position.marginRaw);+ const lev = position.leverage;+ if (entry <= 0n || exit < 0n || margin < 0n || !Number.isSafeInteger(lev) || lev < 1) {+ throw new RangeError('papertrade: invalid position valuation inputs');+ }+ const deadband = entry / 50_000n;+ if (entry > U64_MAX || exit > U64_MAX || (position.isLong ? entry + deadband : exit + deadband) > U64_MAX) {+ throw new RangeError('papertrade: price outside the contract range');+ }+ let effective = exit;+ if (position.isLong) {+ if (exit > entry + deadband) effective = exit - deadband;+ else if (exit > entry) effective = entry;+ } else if (exit + deadband < entry) effective = exit + deadband;+ else if (exit < entry) effective = entry;++ const move = position.isLong ? effective - entry : entry - effective;+ const rawPnlRaw = (margin * BigInt(lev) * move) / entry;+ if (rawPnlRaw <= 0n) return { rawPnlRaw, adjustedPnlRaw: rawPnlRaw < -margin ? -margin : rawPnlRaw };++ const moveWad = ((move < 0n ? -move : move) * WAD) / entry;+ const rateTerm = (moveWad * instrument.rateMultiplierRaw) / WAD;+ const positionTerm = (1_000_000n * moveWad * instrument.positionMultiplierRaw) / WAD;+ if (rateTerm === 0n || positionTerm === 0n) return { rawPnlRaw, adjustedPnlRaw: 0n };+ const m = (WAD * WAD) / rateTerm;+ const h = (instrument.referenceNotionalRaw * WAD) / positionTerm;+ if (m > WAD * WAD || h > WAD * WAD) return { rawPnlRaw, adjustedPnlRaw: 0n };+ const keep = ((WAD - instrument.baseRateRaw) * WAD) / (WAD + m + h);+ return { rawPnlRaw, adjustedPnlRaw: (rawPnlRaw * keep) / WAD };+}++/** What a close at `exitRaw` pays: adjusted PnL less the win fee on a gain. */+export function payoutPnlRaw(adjustedPnlRaw, winFeeRateRaw) {+ const adj = BigInt(adjustedPnlRaw);+ if (adj <= 0n) return adj;+ return adj - (adj * BigInt(winFeeRateRaw)) / WAD;+}++/** Has the mark crossed the bust trigger? */+export function isBust(position, markRaw) {+ return position.isLong ? BigInt(markRaw) <= position.bustPriceRaw : BigInt(markRaw) >= position.bustPriceRaw;+}++/** How far toward bust a position has moved, 0 to 100. */+export function riskPercent(position, markRaw) {+ const mark = BigInt(markRaw);+ const span = position.isLong ? position.entryPriceRaw - position.bustPriceRaw : position.bustPriceRaw - position.entryPriceRaw;+ const against = position.isLong ? position.entryPriceRaw - mark : mark - position.entryPriceRaw;+ if (span <= 0n) return isBust(position, mark) ? 100 : 0;+ if (against <= 0n) return 0;+ if (against >= span) return 100;+ return Number((against * 10_000n) / span) / 100;+}++/**+ * The largest margin an open of this side and leverage can take right now:+ * the per-position notional cap and the side's open-interest headroom, both+ * divided by leverage. Mirrors the exchange's own pre-trade sizing.+ *+ * @returns {{ maxMarginRaw: bigint|null, limitedBy: string|null, headroomRaw: bigint|null }}+ */+export function openCapacity({ instrument, isLong, leverage, markRaw, maximumNetOpenInterestRaw = 0n }) {+ let maxMarginRaw = null;+ let limitedBy = null;+ const take = (value, reason) => {+ if (maxMarginRaw === null || value < maxMarginRaw) {+ maxMarginRaw = value;+ limitedBy = reason;+ }+ };+ if (leverage > instrument.maxLeverage) take(0n, 'leverage_above_market_max');+ if (instrument.maxPositionNotionalRaw > 0n) take(instrument.maxPositionNotionalRaw / BigInt(leverage), 'max_position_notional');+ let headroomRaw = null;+ const mark = markRaw == null ? null : BigInt(markRaw);+ if (mark !== null && mark > 0n) {+ const same = isLong ? instrument.longOiRaw : instrument.shortOiRaw;+ const other = isLong ? instrument.shortOiRaw : instrument.longOiRaw;+ const sideCap = isLong ? instrument.longCapRaw : instrument.shortCapRaw;+ const netCap = maximumNetOpenInterestRaw > 0n ? other + (maximumNetOpenInterestRaw * instrument.priceScaleRaw) / mark : null;+ const cap = sideCap > 0n && sideCap < UNCAPPED && (netCap === null || sideCap < netCap) ? sideCap : netCap;+ if (cap !== null) {+ headroomRaw = ((cap > same ? cap - same : 0n) * mark) / instrument.priceScaleRaw;+ take(headroomRaw / BigInt(leverage), isLong ? 'long_open_interest_cap' : 'short_open_interest_cap');+ }+ }+ return { maxMarginRaw, limitedBy, headroomRaw };+}diff --git a/api/_mcpagent/catalog.js b/api/_mcpagent/catalog.jsindex 0f28a8456..e86830d84 100644--- a/api/_mcpagent/catalog.js+++ b/api/_mcpagent/catalog.js@@ -7,13 +7,14 @@ import { marketplaceToolDefs } from './marketplace-tools.js';import { predictionToolDefs } from './predictions-tools.js';import { orderToolDefs } from './orders-tools.js';import { perpsToolDefs } from './perps-tools.js';+import { papertradeToolDefs } from './papertrade-tools.js';import { tradingToolDefs } from './trading-tools.js';import { portfolioToolDefs } from './portfolio-tools.js';import { sniperAlertToolDefs } from './sniper-alert-tools.js';import { duelToolDefs } from './duels-tools.js';import { commerceToolDefs } from './commerce-tools.js';-const toolDefs = [...walletToolDefs, ...marketplaceToolDefs, ...predictionToolDefs, ...perpsToolDefs, ...tradingToolDefs,+const toolDefs = [...walletToolDefs, ...marketplaceToolDefs, ...predictionToolDefs, ...perpsToolDefs, ...papertradeToolDefs, ...tradingToolDefs,...portfolioToolDefs, ...sniperAlertToolDefs, ...duelToolDefs, ...commerceToolDefs, ...orderToolDefs];// Free, public entry point, listed first so discovery clients see it up top.diff --git a/api/_mcpagent/papertrade-tools.js b/api/_mcpagent/papertrade-tools.jsnew file mode 100644index 000000000..ce19e687f--- /dev/null+++ b/api/_mcpagent/papertrade-tools.js@@ -0,0 +1,144 @@+// threews-agent MCP: Papertrade, the synthetic-perps exchange on HyperEVM.+//+// Thin adapters over api/_lib/papertrade/index.js, the same service behind+// GET /api/papertrade. All four tools are reads (policy group `perps`, tier+// read): they price and report, and need no sign-in. Nothing here signs an+// intent, deposits or trades; a trade happens on Papertrade itself, from the+// user's own wallet. Guide: docs/papertrade.md.++import { limits as rateLimits } from '../_lib/rate-limit.js';+import * as papertrade from '../_lib/papertrade/index.js';++const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };++const usd = (n) => (n == null || !Number.isFinite(Number(n)) ? 'n/a' : `${Number(n) < 0 ? '-' : ''}$${Math.abs(Number(n)).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);+const price = (n) => (n == null ? 'n/a' : `$${Number(n).toLocaleString('en-US', { maximumFractionDigits: 2 })}`);+const compact = (n) => (n == null ? 'n/a' : `$${Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 2 }).format(n)}`);++function refusal(text, reason, extra = {}) {+ return { content: [{ type: 'text', text }], structuredContent: { ok: false, reason, ...extra }, isError: true };+}++const reply = (text, structuredContent) => ({ content: [{ type: 'text', text }], structuredContent });++async function run(auth, fn) {+ const rl = await rateLimits.mcpAgent(auth.userId || auth.rateKey || 'anon');+ if (!rl.success) {+ throw Object.assign(new Error('rate_limited'), { code: -32000, data: { retry_after: Math.ceil((rl.reset - Date.now()) / 1000) } });+ }+ try {+ return await fn();+ } catch (err) {+ if (err instanceof papertrade.PapertradeError) return refusal(err.message, err.code, err.detail ? { detail: err.detail } : {});+ throw err;+ }+}++function marketLine(m) {+ return `${m.symbol}: ${price(m.mid_price)} (${m.status}), up to ${m.max_leverage}x, max ${compact(m.max_position_notional_usd)} per position, OI long ${compact(m.open_interest_long_usd)} / short ${compact(m.open_interest_short_usd)}, 24h volume ${compact(m.volume_24h_usd)}`;+}++function quoteText(q) {+ const ladder = q.scenarios+ .map((s) => ` +${s.move_pct}% to ${price(s.exit_price)}: raw ${usd(s.raw_pnl_usd)}, paid ${usd(s.payout_pnl_usd)}${s.kept_pct == null ? '' : ` (${s.kept_pct}% kept)`}`)+ .join('\n');+ const checks = q.checks.map((c) => ` ${c.ok ? '[ok]' : '[blocked]'} ${c.label}`).join('\n');+ return [+ `Papertrade ${q.symbol} ${q.side.toUpperCase()} ${q.leverage}x, ${usd(q.margin_usd)} margin = ${usd(q.notional_usd)} notional`,+ `Entry ${price(q.entry_price)} (Hyperliquid mid now). Bust at ${price(q.bust_price)}, ${q.bust_distance_pct}% away: crossing it loses the full ${usd(q.margin_usd)}.`,+ `No open fee, no funding. Win fee ${q.win_fee_pct}% after the impact haircut. What a close would pay:`,+ ladder,+ 'Checks:',+ checks,+ q.openable ? `Openable now at ${q.trade_url} from the user's own wallet.` : `Not openable as sized. Blocked by: ${q.blocked_by.join(', ')}.`,+ ].join('\n');+}++function accountText(a) {+ const head = `Papertrade ${a.address}: balance ${usd(a.balance_usd)}, ${usd(a.locked_margin_usd)} locked in margin, ${usd(a.queued_payout_usd)} waiting in the payout queue. Lifetime realized PnL ${usd(a.lifetime.realized_pnl_usd)} on ${compact(a.lifetime.traded_notional_usd)} traded.`;+ if (!a.positions.length) return `${head}\nNo open positions.`;+ const rows = a.positions.slice(0, 25).map((p) =>+ ` #${p.id} ${p.symbol} ${p.side} ${p.leverage}x ${usd(p.margin_usd)}: entry ${price(p.entry_price)}, mark ${price(p.mark_price)}, bust ${price(p.bust_price)} (${p.risk_pct ?? 'n/a'}% of the way), close pays ${usd(p.close_payout_pnl_usd)}${p.bust_crossed ? ' [BUST CROSSED]' : ''}`);+ const more = a.positions.length > 25 ? `\n plus ${a.positions.length - 25} more in structuredContent` : '';+ return `${head}\n${a.open_positions} open, closing all now would pay ${usd(a.close_all_payout_pnl_usd)}:\n${rows.join('\n')}${more}`;+}++const symbolProp = { type: 'string', minLength: 2, maxLength: 16, description: 'Market symbol, e.g. BTC or ETH (papertrade_markets lists them).' };++export const papertradeToolDefs = [+ {+ name: 'papertrade_markets',+ title: 'List Papertrade markets',+ group: 'perps',+ tier: 'read',+ annotations: READ,+ description: 'Papertrade (synthetic perps on HyperEVM, USDC collateral, up to 1000x, no funding) markets: live Hyperliquid mid, status, max leverage, per-position notional cap, open interest per side, 24h volume, the minimum margin and notional, and the live win fee. Call this first to see what can be traded.',+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },+ handler: (_args, auth) => run(auth, async () => {+ const out = await papertrade.markets();+ const head = `Papertrade perps, USDC on HyperEVM${out.trading_paused ? ' (TRADING PAUSED)' : ''}. Min ${usd(out.min_margin_usd)} margin and ${usd(out.min_notional_usd)} notional, ${out.win_fee_pct}% win fee, no funding.`;+ return reply(`${head}\n${out.markets.map(marketLine).join('\n')}`, out);+ }),+ },+ {+ name: 'papertrade_quote',+ title: 'Quote a Papertrade position',+ group: 'perps',+ tier: 'read',+ annotations: READ,+ description: 'Price a Papertrade open exactly as the exchange would fill it now: entry at the Hyperliquid mid, the hard-bust price where the whole margin is lost, capacity and minimum-size checks, and what a winning close actually pays across a ladder of moves (after the 0.2 bps deadband, impact haircut and win fee). Small moves keep a small share of the raw profit; show the user the ladder. Read only: it never opens anything.',+ inputSchema: {+ type: 'object',+ properties: {+ symbol: symbolProp,+ side: { type: 'string', enum: ['long', 'short'] },+ margin_usd: { type: 'number', exclusiveMinimum: 0, maximum: 10_000_000, description: 'Isolated margin in USDC. Papertrade requires at least $10.' },+ leverage: { type: 'integer', minimum: 1, maximum: 100_000, description: 'Leverage multiple. Margin times leverage must be at least the $10,000 minimum notional.' },+ },+ required: ['symbol', 'side', 'margin_usd', 'leverage'],+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, async () => {+ const out = await papertrade.quote({ symbol: args.symbol, side: args.side, marginUsd: args.margin_usd, leverage: args.leverage });+ return reply(quoteText(out), out);+ }),+ },+ {+ name: 'papertrade_account',+ title: 'Read a Papertrade wallet',+ group: 'perps',+ tier: 'read',+ annotations: READ,+ description: 'Any EVM wallet\'s Papertrade account from public chain-indexed state: balance, locked margin, queued payouts, lifetime deposits, realized PnL and fees, and every open position valued at the live mid (raw PnL, what a close would pay, bust price and how close the mark is to it).',+ inputSchema: {+ type: 'object',+ properties: { address: { type: 'string', pattern: '^0x[0-9a-fA-F]{40}$', description: 'The 0x wallet address that trades on Papertrade.' } },+ required: ['address'],+ additionalProperties: false,+ },+ handler: (args, auth) => run(auth, async () => {+ const out = await papertrade.account(args.address);+ return reply(accountText(out), out);+ }),+ },+ {+ name: 'papertrade_protocol',+ title: 'Check Papertrade protocol health',+ group: 'perps',+ tier: 'read',+ annotations: READ,+ description: 'Papertrade protocol health before sizing a trade: TVL, margin locked, the LP that pays winners, the payout queue (winners wait in it when the LP is short), lifetime volume and fees, the live win fee and whether the order relayer is ready.',+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },+ handler: (_args, auth) => run(auth, async () => {+ const p = await papertrade.protocol();+ const queue = p.payout_queue == null+ ? 'Payout queue status unavailable.'+ : p.payout_queue.active+ ? `PAYOUT QUEUE ACTIVE: ${usd(p.payout_queue.total_usd)} across ${p.payout_queue.entries} winners is waiting for LP liquidity.`+ : 'Payout queue empty: winners are paid immediately.';+ const relayer = p.relayer_ready == null ? 'unknown' : p.relayer_ready ? 'ready' : 'NOT READY';+ const text = `Papertrade: TVL ${compact(p.tvl_usd)}, ${compact(p.margin_locked_usd)} in margin, LP ${compact(p.lp_usd)}, ${p.open_positions} open positions, ${compact(p.lifetime_volume_usd)} lifetime volume, ${compact(p.lifetime_fees_usd)} fees. Win fee ${p.win_fee_pct}%. Relayer ${relayer}.\n${queue}`;+ return reply(text, p);+ }),+ },+];diff --git a/api/papertrade.js b/api/papertrade.jsnew file mode 100644index 000000000..25c6d3c1a--- /dev/null+++ b/api/papertrade.js@@ -0,0 +1,48 @@+// GET /api/papertrade?view=markets|protocol|quote|account+// ---------------------------------------------------------------------------+// Read-only window onto Papertrade, the synthetic-perps exchange on HyperEVM.+//+// view=markets (default) BTC/ETH markets: live mid, limits, open interest+// view=protocol TVL, LP, payout queue, fees, relayer readiness+// view=quote exact open quote: &symbol=BTC&side=long&margin_usd=100&leverage=100+// view=account any wallet's balances and valued positions: &address=0x...+//+// Every figure comes from Papertrade's public API, the exchange contract and+// Hyperliquid's live BBO, priced by api/_lib/papertrade/math.js at contract+// scale. Nothing here signs or trades. Guide: docs/papertrade.md.++import { cors, json, method, wrap, error, rateLimited } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { markets, protocol, quote, account, PapertradeError } from './_lib/papertrade/index.js';++const VIEWS = {+ markets: { run: () => markets(), cache: 'public, max-age=5, s-maxage=5, stale-while-revalidate=30' },+ protocol: { run: () => protocol(), cache: 'public, max-age=15, s-maxage=30, stale-while-revalidate=120' },+ quote: {+ run: (q) => quote({ symbol: q.get('symbol'), side: q.get('side'), marginUsd: q.get('margin_usd'), leverage: q.get('leverage') }),+ cache: 'no-store',+ },+ account: { run: (q) => account(q.get('address')), cache: 'private, max-age=5' },+};++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.marketDataIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const q = new URL(req.url, 'http://x').searchParams;+ const name = q.get('view') || 'markets';+ const view = VIEWS[name];+ if (!view) return error(res, 400, 'invalid_view', `view must be one of: ${Object.keys(VIEWS).join(', ')}.`);++ try {+ return json(res, 200, await view.run(q), { 'cache-control': view.cache });+ } catch (err) {+ if (err instanceof PapertradeError) {+ return error(res, err.status, err.code, err.message, err.detail ? { detail: err.detail } : {});+ }+ throw err;+ }+});diff --git a/docs/mcp.md b/docs/mcp.mdindex c55c6318a..c8a1ae0c4 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -1274,6 +1274,25 @@ starts. No funds move. `duel_details` reads one duel or one challenge, and `duelduels by phase, your challenges, or the leaderboard: agents ranked by challenge-duel wins, withlosses, win rate and realized P&L, next to this season's top predictors.+### Papertrade: synthetic perps on HyperEVM++Four read-only tools on the agent wallet server (`https://three.ws/api/mcp-agent`) read+[Papertrade](https://papertrade.xyz), a synthetic BTC and ETH perps exchange on HyperEVM with USDC+collateral, up to 1000x and no funding. They need no sign-in, and none of them signs or trades.++| Tool | Hints | Policy |+|------|-------|--------|+| `papertrade_markets` | readOnly, idempotent, openWorld | read, `perps` group |+| `papertrade_quote` | readOnly, idempotent, openWorld | read, `perps` group |+| `papertrade_account` | readOnly, idempotent, openWorld | read, `perps` group |+| `papertrade_protocol` | readOnly, idempotent, openWorld | read, `perps` group |++`papertrade_quote` prices an open the way the exchange fills it: entry at the Hyperliquid mid, the+hard-bust price where the whole margin is lost, the minimum-size and capacity checks, and what a+winning close actually pays across eight price moves after Papertrade's deadband, impact haircut and+win fee. `papertrade_account` values any wallet's open positions at the live mid. The same data is on+`GET /api/papertrade`. Full guide: [Papertrade](./papertrade.md).+---## Resourcesdiff --git a/docs/papertrade.md b/docs/papertrade.mdnew file mode 100644index 000000000..217ddc860--- /dev/null+++ b/docs/papertrade.md@@ -0,0 +1,233 @@+# Papertrade++[Papertrade](https://papertrade.xyz) is a synthetic perpetual-futures exchange on HyperEVM (chain 999): BTC and ETH, USDC collateral, up to 1000x leverage, no funding. three.ws reads it for you. You get its live markets, an exact quote for any position before you open it, any wallet's open positions valued at the live price, and the protocol's health, over plain HTTP and as MCP tools an agent can call.++This integration is **read only**. Nothing here signs an order, deposits or withdraws. You trade on Papertrade itself, from your own wallet. three.ws shows you exactly what a trade will do before you place it.++| Surface | Where | Who uses it |+| --- | --- | --- |+| REST | `GET /api/papertrade?view=...` | Your own code, a dashboard, a script. No key needed |+| MCP | `papertrade_*` tools on `/api/mcp-agent` | Claude, or any MCP client you connect. No sign-in needed |++Related reading: [Agent Perps](./perps.md) is the Solana perps desk, where an agent trades with its own wallet. The [MCP guide](./mcp.md#papertrade-synthetic-perps-on-hyperevm) covers connecting a client.++---++## How Papertrade differs from a normal perp++A quote is only useful if it prices the venue's real rules. Papertrade's rules are unusual, and every number this integration returns accounts for them:++- **No order book.** Every trade is a swap against one liquidity provider at Hyperliquid's best-bid/best-ask midpoint. There is no slippage and no spread, and size does not move the price.+- **No funding.** A position costs nothing to hold.+- **Isolated margin, fixed at open.** You cannot add margin later, and a close is always the full position.+- **Hard bust instead of liquidation.** Each position has a bust price set at open: the price where its equity would reach zero, moved about 5 basis points (the market's `bust_buffer_bps`) closer to entry. If the mark crosses it, the whole margin is lost. A $100 long at 100x on a $100,000 market busts at about $99,047.+- **Winners keep less than the raw move.** A winning close passes three steps. First a 0.2 basis-point deadband: a move smaller than that pays nothing. Then an impact haircut that takes a large share of a small move and a small share of a large one. Then the win fee, read live from the exchange contract (2% when this was written). Losses pay nothing extra and never exceed the margin.+- **Payout queue.** Winners are paid from the liquidity provider. When it runs short, the unpaid profit waits in a first-in, first-out queue until there is liquidity. `view=protocol` tells you whether the queue is active.+- **Minimums.** Margin at least $10 and notional (margin times leverage) at least $10,000, so a $10 position needs 1000x.++The haircut is the one that surprises people. On a $10,000 BTC position, a 0.01% move is worth about $0.81 raw but pays about $0.21. A 1% move is worth about $99.80 and pays about $86.39. Every quote shows this ladder, so nobody opens a 1000x scalp expecting the raw number.++---++## REST++One endpoint, four views. All are `GET`, need no authentication, and are rate limited per IP like the other market-data routes.++### `view=markets` (the default)++```bash+curl -s 'https://three.ws/api/papertrade'+```++```json+{+ "venue": "papertrade",+ "chain_id": 999,+ "collateral": "USDC",+ "trading_paused": false,+ "min_margin_usd": 10,+ "min_notional_usd": 10000,+ "win_fee_pct": 2,+ "funding": "none",+ "stale": false,+ "markets": [+ {+ "symbol": "BTC",+ "instrument_id": 0,+ "status": "active",+ "openable": true,+ "mid_price": 83065.5,+ "bid": 83065,+ "ask": 83066,+ "price_source": "hyperliquid_bbo_mid",+ "max_leverage": 1000,+ "max_position_notional_usd": 10000000,+ "bust_buffer_bps": 4.76,+ "open_interest_long_usd": 2073237482.39,+ "open_interest_short_usd": 1622524832.88,+ "volume_24h_usd": 217785554681.2+ }+ ],+ "links": { "app": "https://exchange.papertrade.xyz", "docs": "https://docs.papertrade.xyz" }+}+```++`status` is one of `active`, `close_only`, `paused`, `terminal` or `inactive`. A terminal market prices at the bid and ask frozen when it was paused (`price_source: "frozen_at_pause"`). `stale: true` means Papertrade's API missed one read and the market parameters are from the last good copy, at most 10 minutes old. Prices are never served stale.++### `view=quote`++Prices an open exactly as the exchange would fill it now.++| Parameter | Required | Meaning |+| --- | --- | --- |+| `symbol` | yes | `BTC` or `ETH` (`BTC-USD` and `ETH-PERP` also work) |+| `side` | yes | `long` or `short` |+| `margin_usd` | yes | Isolated margin in USDC |+| `leverage` | yes | Whole number, up to the market's `max_leverage` |++```bash+curl -s 'https://three.ws/api/papertrade?view=quote&symbol=BTC&side=long&margin_usd=100&leverage=100'+```++```json+{+ "symbol": "BTC",+ "side": "long",+ "margin_usd": 100,+ "leverage": 100,+ "notional_usd": 10000,+ "entry_price": 83065.5,+ "bust_price": 82274,+ "bust_distance_pct": 0.9529,+ "loss_at_bust_usd": -100,+ "max_margin_usd": 100000,+ "win_fee_pct": 2,+ "fees_at_open_usd": 0,+ "funding": "none",+ "scenarios": [+ { "move_pct": 0.01, "exit_price": 83073.8, "raw_pnl_usd": 0.806592, "payout_pnl_usd": 0.212458, "kept_pct": 26.34, "busted": false },+ { "move_pct": 1, "exit_price": 83896.1, "raw_pnl_usd": 99.800759, "payout_pnl_usd": 86.384648, "kept_pct": 86.56, "busted": false }+ ],+ "checks": [+ { "id": "market_open", "ok": true, "label": "BTC is active" },+ { "id": "leverage", "ok": true, "label": "Leverage 100x within the 1000x market maximum" },+ { "id": "min_margin", "ok": true, "label": "Margin at least $10" },+ { "id": "min_notional", "ok": true, "label": "Notional at least $10,000" },+ { "id": "capacity", "ok": true, "label": "Margin within the $100,000 the market can take at 100x (max_position_notional)" }+ ],+ "openable": true,+ "blocked_by": [],+ "trade_url": "https://exchange.papertrade.xyz"+}+```++(`scenarios` is shortened here; the response has eight rungs: 0.01, 0.05, 0.1, 0.25, 0.5, 1, 2 and 5 percent.)++- `payout_pnl_usd` is what a close at that price would actually credit: after the deadband, the impact haircut and the win fee. `raw_pnl_usd` is the plain move times notional, for comparison.+- `max_margin_usd` is the most this side and leverage can take right now. The lowest of three limits wins: the per-position notional cap, the side's open-interest cap, and the protocol's net open-interest cap.+- A quote that breaks a rule still returns `200`, with `openable: false` and the failing check ids in `blocked_by` (`market_open`, `leverage`, `min_margin`, `min_notional`, `capacity`), so you can show the user what to change.+- The entry price is the mid at the moment of the quote. A real order fills at the mid when Papertrade's relayer lands it, so it can differ by however far the price moved in between.++### `view=account`++Any wallet's Papertrade account. It is public chain-indexed state, so no signature is needed.++```bash+curl -s 'https://three.ws/api/papertrade?view=account&address=0x44623c92310d1b9b430b3228487a1b88fcc1c517'+```++The response carries `balance_usd`, `available_usd`, `locked_margin_usd`, `queued_payout_usd` (profit waiting in the payout queue), `session_key_active`, and `lifetime` totals (deposited, withdrawn, realized PnL, fees paid, traded notional). `positions` lists every open position, largest first:++```json+{+ "id": "53573",+ "symbol": "ETH",+ "side": "long",+ "margin_usd": 250,+ "leverage": 50,+ "notional_usd": 12500,+ "entry_price": 2512.15,+ "bust_price": 2463.09,+ "mark_price": 2512.15,+ "raw_pnl_usd": 0,+ "close_payout_pnl_usd": 0,+ "risk_pct": 0,+ "bust_crossed": false,+ "margin_from_queue": false,+ "opened_at": "2026-10-10T20:03:36.000Z"+}+```++`risk_pct` runs from 0 (mark at or better than entry) to 100 (mark at the bust price). `close_all_payout_pnl_usd` is what closing everything now would credit in total.++### `view=protocol`++```bash+curl -s 'https://three.ws/api/papertrade?view=protocol'+```++Returns `tvl_usd`, `margin_locked_usd`, `lp_usd` (the liquidity that pays winners), `open_positions`, `lifetime_volume_usd`, `lifetime_fees_usd`, `win_fee_pct`, `payout_queue` (`total_usd`, `entries`, `active`), and `relayer_ready` (whether Papertrade's order relayer is accepting intents). Check it before sizing a large position. A small `lp_usd` next to a big winning position, or an active queue, means a profit may not be paid right away.++### Errors++Errors use the platform's standard shape, `{ "error": "<code>", "error_description": "<what to do>" }`:++| Status | `error` | Meaning |+| --- | --- | --- |+| 400 | `invalid_view` | `view` is not one of the four above |+| 400 | `invalid_side`, `invalid_margin`, `invalid_leverage`, `symbol_required` | A quote parameter is missing or out of range |+| 400 | `invalid_address` | `address` is not a 0x wallet address |+| 404 | `unknown_market` | No such market. `detail.available` lists the real ones |+| 502 | `upstream_unavailable` | Papertrade, HyperEVM or Hyperliquid did not answer. Retry shortly |+| 502 | `upstream_schema_changed` | Papertrade changed its data format. Quotes stay off until the integration is updated, rather than guess |++---++## MCP tools++Four read-only tools on the agent wallet server (`https://three.ws/api/mcp-agent`). They need no sign-in and are in the `perps` policy group at the read tier. Each returns a plain-language summary for the model plus the full REST response as `structuredContent`.++| Tool | Arguments | Same as |+| --- | --- | --- |+| `papertrade_markets` | none | `view=markets` |+| `papertrade_quote` | `symbol`, `side`, `margin_usd`, `leverage` | `view=quote` |+| `papertrade_account` | `address` | `view=account` |+| `papertrade_protocol` | none | `view=protocol` |++```json+{ "name": "papertrade_quote",+ "arguments": { "symbol": "BTC", "side": "long", "margin_usd": 10, "leverage": 1000 } }+```++The model sees the bust price, how far away it is, and the full payout ladder, so it can tell a user plainly that a $10 BTC long at 1000x is gone if BTC drops about 0.05%.++---++## Where the numbers come from++| Figure | Source |+| --- | --- |+| Markets, limits, open interest, minimums | Papertrade API `GET https://exchange.papertrade.xyz/state/trading` |+| Protocol balances, payout queue, 24h volume | Papertrade API `/query/protocol/summary`, `/queue-summary`, `/market-stats` |+| Relayer readiness | Papertrade API `/relayer/health` |+| A wallet's balances and positions | The first frame of Papertrade's live wallet stream, `/state/user/live` |+| Win fee | `winFeeRate()` on the exchange contract `0x6cd5661646289fb6e65ea5c032310fded797d0a2`, read over HyperEVM RPC |+| Entry and mark price | Hyperliquid `l2Book` best bid and ask, the same midpoint the contract prices against |++The position math (`api/_lib/papertrade/math.js`) runs in integer arithmetic at the contract's own scales, so its rounding matches the contract's. Its tests (`tests/papertrade-math.test.js`) include bust prices read from real Papertrade positions, reproduced exactly.++## Risks to tell users about++- Papertrade launched in October 2026. Its contracts are upgradeable by the protocol owner through a timelock.+- Profits depend on one liquidity provider and can wait in the payout queue.+- At high leverage the bust price sits a tiny move from entry, and the haircut means small favourable moves pay little. The quote ladder exists to make both visible before anyone trades.++## Code++| Piece | File |+| --- | --- |+| Position math | `api/_lib/papertrade/math.js` |+| Live client and service | `api/_lib/papertrade/index.js` |+| REST handler | `api/papertrade.js` |+| MCP tools | `api/_mcpagent/papertrade-tools.js` |+| Tests | `tests/papertrade-math.test.js` |diff --git a/packages/mcp-policy/src/table.js b/packages/mcp-policy/src/table.jsindex 752a1f4f6..9cba0c365 100644--- a/packages/mcp-policy/src/table.js+++ b/packages/mcp-policy/src/table.js@@ -293,6 +293,12 @@ export const POLICY = {perps_order_cancel: own('perps', 'confirm_trade', 'perps_action_preview'),perps_flatten: own('perps', 'confirm_trade', 'perps_action_preview'),perps_limits: w('perps'),+ // Papertrade synthetic perps on HyperEVM (api/_mcpagent/papertrade-tools.js).+ // Reads only: they price and report, nothing signs or trades.+ papertrade_markets: r('perps'),+ papertrade_quote: r('perps'),+ papertrade_account: r('perps'),+ papertrade_protocol: r('perps'),// Resting orders and DCA on any SPL token (api/_mcpagent/orders-tools.js).// The create tools verify their own signed, single-use preview id, bound to// the agent and to the create tool it was issued for.diff --git a/tests/api/mcp-agent-catalog.test.js b/tests/api/mcp-agent-catalog.test.jsindex 1ee25cf09..75e7ee172 100644--- a/tests/api/mcp-agent-catalog.test.js+++ b/tests/api/mcp-agent-catalog.test.js@@ -10,7 +10,7 @@ import { describe, it, expect } from 'vitest';import { TOOL_CATALOG, TOOLS } from '../../api/_mcpagent/catalog.js';describe('agent-wallet MCP catalog', () => {- it('leads with the free getting_started tool, then the wallet, marketplace, prediction and perps toolsets', () => {+ it('leads with the free getting_started tool, then the wallet, marketplace, prediction, perps and Papertrade toolsets', () => {expect(TOOL_CATALOG.map((t) => t.name)).toEqual(['getting_started',// Wallet and x402 (api/_mcpagent/tools.js)@@ -21,6 +21,8 @@ describe('agent-wallet MCP catalog', () => {'provision_wallet','monetize_endpoint','read_resource',+ 'get_linked_accounts',+ 'set_external_wallet',// Agent marketplace (api/_mcpagent/marketplace-tools.js)'browse_marketplace','browse_public_agents',@@ -62,6 +64,11 @@ describe('agent-wallet MCP catalog', () => {'perps_order_cancel','perps_flatten','perps_limits',+ // Papertrade synthetic perps on HyperEVM (api/_mcpagent/papertrade-tools.js)+ 'papertrade_markets',+ 'papertrade_quote',+ 'papertrade_account',+ 'papertrade_protocol',// Solana trading (api/_mcpagent/trading-tools.js over api/_lib/trading-tools/registry.js)'token_search','get_price',@@ -91,6 +98,35 @@ describe('agent-wallet MCP catalog', () => {'duel_accept','duel_details','duel_markets',+ // Agent commerce (api/_mcpagent/commerce-tools.js)+ 'invoice_create',+ 'invoice_details',+ 'invoice_list',+ 'invoice_verify',+ 'invoice_cancel',+ 'agent_send_preview',+ 'agent_send',+ 'offer_list',+ 'agent_sell',+ 'agent_buy',+ 'agent_buy_confirm',+ 'spending_check',+ 'spending_setup',+ // Resting orders and DCA (api/_mcpagent/orders-tools.js)+ 'order_preview',+ 'limit_order_create',+ 'stop_order_create',+ 'trailing_order_create',+ 'ladder_order_create',+ 'oco_order_create',+ 'limit_order_list',+ 'limit_order_cancel',+ 'limit_order_history',+ 'order_book',+ 'dca_preview',+ 'dca_create',+ 'dca_list',+ 'dca_cancel',]);});diff --git a/tests/papertrade-math.test.js b/tests/papertrade-math.test.jsnew file mode 100644index 000000000..d3e9d2f14--- /dev/null+++ b/tests/papertrade-math.test.js@@ -0,0 +1,123 @@+// Papertrade position math (api/_lib/papertrade/math.js). The bust cases are+// real positions read from the exchange's wallet stream: the contract stored+// these bust prices, and the formula must reproduce them to the raw unit.++import { describe, it, expect } from 'vitest';++import {+ WAD, usdToRaw, rawToUsd, priceToRaw, rawToPrice, decodeInstrument, decodePosition, midRaw, bustPriceRaw,+ valuePosition, payoutPnlRaw, isBust, riskPercent, openCapacity,+} from '../api/_lib/papertrade/math.js';++// The live BTC and ETH instrument tuples from GET /state/trading (schemaVersion 1).+const BTC = decodeInstrument([0, 'BTC', 0, '10', true, false, false, false, false, null, null, null,+ '15000000000000000000000', '814598000000000000000', 1000, '10000000000000000000000000', '476041580087574',+ '100000000000000000', '100000000000000000000000', '23590192866625362236353', '18109832138345653207981',+ '1207459685939735687074747', '1207459685939735687074747']);+const ETH = decodeInstrument([1, 'ETH', 1, '100', true, false, false, false, false, null, null, null,+ '15000000000000000000000', '483979000000000000000', 1000, '10000000000000000000000000', '481304050180130',+ '100000000000000000', '100000000000000000000000', '801888041618533102629272', '687966580469056106171688',+ '40032826918072819712163974', '40032826918072819712163974']);++const long = (entry, marginUsd, lev, inst) => ({+ isLong: true, entryPriceRaw: BigInt(entry), marginRaw: usdToRaw(marginUsd), leverage: lev,+ bustPriceRaw: bustPriceRaw(entry, lev, true, inst.bustBufferRaw),+});+const short = (entry, marginUsd, lev, inst) => ({+ isLong: false, entryPriceRaw: BigInt(entry), marginRaw: usdToRaw(marginUsd), leverage: lev,+ bustPriceRaw: bustPriceRaw(entry, lev, false, inst.bustBufferRaw),+});++describe('papertrade scale conversion', () => {+ it('round-trips USD and prices at contract scale', () => {+ expect(usdToRaw(10)).toBe(10n * WAD);+ expect(rawToUsd(-25n * WAD / 10n)).toBe(-2.5);+ expect(priceToRaw(83065.5, BTC.priceScaleRaw)).toBe(830655n);+ expect(rawToPrice(251215n, ETH.priceScaleRaw)).toBe(2512.15);+ expect(midRaw(830650n, 830661n)).toBe(830655n);+ });++ it('decodes instrument and position tuples in wire order', () => {+ expect(BTC).toMatchObject({ id: 0, symbol: 'BTC', maxLeverage: 1000, openable: true, priceScaleRaw: 10n });+ const p = decodePosition(['53573', 1, true, false, '251215', '250000000000000000000', 50, '246309', 1791662616000, null]);+ expect(p).toMatchObject({ id: '53573', instrumentId: 1, isLong: true, leverage: 50, entryPriceRaw: 251215n, bustPriceRaw: 246309n });+ expect(() => decodeInstrument([0, 'BTC'])).toThrow(TypeError);+ });+});++describe('papertrade bust price', () => {+ it('reproduces the bust the contract stored for live positions', () => {+ expect(bustPriceRaw(830465n, 1000, false, BTC.bustBufferRaw)).toBe(830900n);+ expect(bustPriceRaw(251215n, 50, true, ETH.bustBufferRaw)).toBe(246309n);+ });++ it('busts a $100 long at 100x about 0.95% below entry, as documented', () => {+ const p = long(1_000_000n, 1, 100, BTC);+ expect(rawToPrice(p.bustPriceRaw, BTC.priceScaleRaw)).toBeCloseTo(99_047.1, 1);+ expect(isBust(p, p.bustPriceRaw)).toBe(true);+ expect(isBust(p, p.bustPriceRaw + 1n)).toBe(false);+ });+});++describe('papertrade position valuation', () => {+ it('pays nothing for a move inside the 0.2 bps deadband', () => {+ const p = long(1_000_000n, 100, 100, BTC);+ expect(valuePosition(p, 1_000_020n, BTC).adjustedPnlRaw).toBe(0n);+ expect(valuePosition(p, 1_000_000n, BTC).rawPnlRaw).toBe(0n);+ });++ it('floors a loss at the full margin', () => {+ const p = short(1_000_000n, 100, 100, BTC);+ const v = valuePosition(p, 2_000_000n, BTC);+ expect(v.rawPnlRaw).toBeLessThan(-usdToRaw(100));+ expect(v.adjustedPnlRaw).toBe(-usdToRaw(100));+ });++ it('keeps a small share of a small win and most of a large one', () => {+ const p = long(1_000_000n, 100, 100, BTC);+ const keep = (exit) => {+ const v = valuePosition(p, exit, BTC);+ return Number(v.adjustedPnlRaw * 10_000n / v.rawPnlRaw) / 100;+ };+ const small = keep(1_000_100n); // +0.01%+ const large = keep(1_050_000n); // +5%+ expect(small).toBeGreaterThan(0);+ expect(small).toBeLessThan(40);+ expect(large).toBeGreaterThan(85);+ expect(large).toBeLessThan(90); // never above 1 - baseRate+ });++ it('takes the win fee from gains only', () => {+ expect(payoutPnlRaw(100n * WAD, 2n * 10n ** 16n)).toBe(98n * WAD);+ expect(payoutPnlRaw(-5n * WAD, 2n * 10n ** 16n)).toBe(-5n * WAD);+ });++ it('reports risk as the share of the way from entry to bust', () => {+ const p = long(1_000_000n, 100, 100, BTC);+ const half = (p.entryPriceRaw + p.bustPriceRaw) / 2n;+ expect(riskPercent(p, 1_010_000n)).toBe(0);+ expect(riskPercent(p, half)).toBeCloseTo(50, 0);+ expect(riskPercent(p, p.bustPriceRaw - 5n)).toBe(100);+ });+});++describe('papertrade open capacity', () => {+ it('caps margin by the per-position notional at the chosen leverage', () => {+ const cap = openCapacity({ instrument: BTC, isLong: true, leverage: 100, markRaw: 830655n });+ expect(cap.maxMarginRaw).toBe(100_000n * WAD);+ expect(cap.limitedBy).toBe('max_position_notional');+ });++ it('refuses leverage above the market maximum', () => {+ const cap = openCapacity({ instrument: BTC, isLong: false, leverage: 2000, markRaw: 830655n });+ expect(cap).toMatchObject({ maxMarginRaw: 0n, limitedBy: 'leverage_above_market_max' });+ });++ it('binds on open-interest headroom once the side is nearly full', () => {+ const full = { ...BTC, longOiRaw: BTC.longCapRaw - 10n ** 18n };+ const cap = openCapacity({ instrument: full, isLong: true, leverage: 10, markRaw: 830655n });+ expect(cap.limitedBy).toBe('long_open_interest_cap');+ expect(rawToUsd(cap.headroomRaw)).toBeCloseTo(83_065.5, 0);+ expect(rawToUsd(cap.maxMarginRaw)).toBeCloseTo(8_306.55, 1);+ });+});