Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(marketing): add the motion studio pipeline and the rendered Give your AI a body video in 16x9 and 9x16

nirholas048ff4117b93
diff --git a/api/_lib/event-markets/routes.js b/api/_lib/event-markets/routes.js
index 2d30da009..0d1222dab 100644
--- a/api/_lib/event-markets/routes.js
+++ b/api/_lib/event-markets/routes.js
@@ -15,6 +15,7 @@ import {
} from './index.js';
import { standingsRoutes } from './standings-routes.js';
import { forecasterRoutes } from './forecaster-routes.js';
+import { stakingRoutes } from './staking/routes.js';
/** Typed seam errors become the v1 envelope; anything else propagates. */
async function guarded(fn) {
@@ -103,6 +104,7 @@ export function publicRoutes(prefix = '/event-markets') {
{ method: 'GET', path: `${prefix}/:slug/history`, name: 'event_markets.history', auth: 'public', handler: historyRoute },
{ method: 'GET', path: `${prefix}/:slug/picks`, name: 'event_markets.picks', auth: 'required', handler: picksRoute },
{ method: 'POST', path: `${prefix}/:slug/pick`, name: 'event_markets.pick', auth: 'required', handler: pickRoute },
+ ...stakingRoutes(prefix),
{ method: 'DELETE', path: `${prefix}/:slug/pick`, name: 'event_markets.withdraw', auth: 'required', handler: withdrawRoute },
{ method: 'POST', path: prefix, name: 'event_markets.create', auth: 'required', handler: adminCreate },
{ method: 'PATCH', path: `${prefix}/:slug`, name: 'event_markets.edit', auth: 'required', handler: adminEdit },
diff --git a/api/_lib/event-markets/staking/chain.js b/api/_lib/event-markets/staking/chain.js
new file mode 100644
index 000000000..fe2892fd9
--- /dev/null
+++ b/api/_lib/event-markets/staking/chain.js
@@ -0,0 +1,86 @@
+// Chain reads and UNSIGNED transaction building for staked Event Markets.
+// The server never holds a staker's key and never signs on their behalf: every
+// builder returns a base64 transaction with the staker as fee payer and no
+// signatures, for the user's own wallet to review and sign.
+
+import { Connection, PublicKey, Transaction } from '@solana/web3.js';
+import {
+ TOKEN_PROGRAM_ID, createAssociatedTokenAccountIdempotentInstruction, getAccount, getAssociatedTokenAddressSync,
+} from '@solana/spl-token';
+import { build, decodePool, decodePosition, poolPda, positionPda, programId, vaultFor, decodeConfig, configPda } from './program.js';
+import { stakingConfig } from './config.js';
+
+let conn;
+export function connection() {
+ if (!conn) conn = new Connection(stakingConfig().rpcUrl, 'confirmed');
+ return conn;
+}
+
+const tokenProgramCache = new Map();
+/** Classic SPL or Token-2022, read from the mint account's owner. */
+export async function tokenProgramFor(mint) {
+ if (!tokenProgramCache.has(mint)) {
+ const info = await connection().getAccountInfo(new PublicKey(mint));
+ if (!info) throw new Error('stake mint not found on this cluster');
+ tokenProgramCache.set(mint, info.owner);
+ }
+ return tokenProgramCache.get(mint);
+}
+
+export const poolIdBytes = (hex) => Buffer.from(hex, 'hex');
+
+export async function readPool(poolIdHex) {
+ const info = await connection().getAccountInfo(poolPda(programId(), poolIdBytes(poolIdHex)));
+ return info ? decodePool(info.data) : null;
+}
+
+export async function readConfig() {
+ const info = await connection().getAccountInfo(configPda(programId()));
+ return info ? decodeConfig(info.data) : null;
+}
+
+export async function readPosition(poolIdHex, owner) {
+ const program = programId();
+ const info = await connection().getAccountInfo(positionPda(program, poolPda(program, poolIdBytes(poolIdHex)), new PublicKey(owner)));
+ return info ? decodePosition(info.data) : null;
+}
+
+export async function vaultBalance(poolIdHex, mint) {
+ const program = programId();
+ const vault = vaultFor(poolPda(program, poolIdBytes(poolIdHex)), mint, await tokenProgramFor(mint));
+ try {
+ return (await getAccount(connection(), vault, 'confirmed', await tokenProgramFor(mint))).amount;
+ } catch {
+ return 0n;
+ }
+}
+
+async function unsigned(feePayer, instructions) {
+ const { blockhash, lastValidBlockHeight } = await connection().getLatestBlockhash('confirmed');
+ const tx = new Transaction({ feePayer: new PublicKey(feePayer), blockhash, lastValidBlockHeight }).add(...instructions);
+ return {
+ transaction: tx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64'),
+ last_valid_block_height: lastValidBlockHeight,
+ };
+}
+
+export async function buildStakeTx(pool, { wallet, outcome, amount }) {
+ const tokenProgram = await tokenProgramFor(pool.mint);
+ return unsigned(wallet, [build.stake(programId(), {
+ staker: wallet, poolId: poolIdBytes(pool.poolIdHex), mint: pool.mint, outcome, amount, tokenProgram,
+ })]);
+}
+
+/** Claim and refund create the owner's token account first when it is missing, so a payout can never fail on that. */
+export async function buildPayoutTx(pool, { wallet, kind }) {
+ const tokenProgram = await tokenProgramFor(pool.mint);
+ const owner = new PublicKey(wallet);
+ const ata = getAssociatedTokenAddressSync(new PublicKey(pool.mint), owner, false, tokenProgram);
+ const args = { owner: wallet, poolId: poolIdBytes(pool.poolIdHex), mint: pool.mint, tokenProgram };
+ return unsigned(wallet, [
+ createAssociatedTokenAccountIdempotentInstruction(owner, ata, owner, new PublicKey(pool.mint), tokenProgram),
+ kind === 'claim' ? build.claim(programId(), args) : build.refund(programId(), args),
+ ]);
+}
+
+export { TOKEN_PROGRAM_ID };
diff --git a/api/_lib/event-markets/staking/config.js b/api/_lib/event-markets/staking/config.js
new file mode 100644
index 000000000..d7f8ed77e
--- /dev/null
+++ b/api/_lib/event-markets/staking/config.js
@@ -0,0 +1,61 @@
+// Policy for staked Event Markets: which tokens, how much, what the house keeps,
+// and who may stake. Every number here is a RECOMMENDATION pending the owner's
+// decision (docs/event-markets-staking.md, "Owner decisions"). Defaults err on
+// the side of small stakes and a closed door: staking is off until
+// EVENT_MARKETS_STAKING_ENABLED=1.
+
+import { env } from '../../env.js';
+
+export const CLUSTERS = {
+ localnet: { rpc: 'http://127.0.0.1:8899' },
+ devnet: { rpc: null },
+ mainnet: { rpc: null },
+};
+
+const USDC_MAINNET = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const USDC_DEVNET = '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU';
+
+/** Base-unit limits per token. USDC has 6 decimals; so does the platform coin. */
+export const TOKENS = {
+ usdc: {
+ symbol: 'USDC', decimals: 6,
+ min: 1_000_000n, // 1 USDC
+ maxStake: 100_000_000n, // 100 USDC per account per market
+ maxPool: 5_000_000_000n, // 5,000 USDC per market
+ dailyCap: 250_000_000n, // 250 USDC staked per account per rolling 24h
+ },
+ three: {
+ symbol: '$THREE', decimals: 6,
+ min: 1_000_000_000n, // 1,000 $THREE
+ maxStake: 1_000_000_000_000n, // 1,000,000 $THREE
+ maxPool: 50_000_000_000_000n, // 50,000,000 $THREE
+ dailyCap: 2_500_000_000_000n, // 2,500,000 $THREE
+ },
+};
+
+/** House fee: 3% of the pool, half of it routed to the $THREE buyback. */
+export const FEE = { feeBps: 300, buybackShareBps: 5000 };
+/** Pools void themselves (everyone refunded) this long after the lock if unresolved. */
+export const VOID_AFTER_LOCK_SECONDS = 7 * 24 * 3600;
+
+export const TERMS_VERSION = '2026-10-13';
+
+export function stakingConfig() {
+ const cluster = process.env.EVENT_MARKETS_STAKE_CLUSTER || 'devnet';
+ if (!CLUSTERS[cluster]) throw new Error(`EVENT_MARKETS_STAKE_CLUSTER must be one of ${Object.keys(CLUSTERS).join(', ')}`);
+ return {
+ enabled: process.env.EVENT_MARKETS_STAKING_ENABLED === '1',
+ cluster,
+ rpcUrl: process.env.EVENT_MARKETS_STAKE_RPC_URL
+ || (cluster === 'mainnet' ? env.SOLANA_RPC_URL : cluster === 'devnet' ? env.SOLANA_RPC_URL_DEVNET : CLUSTERS.localnet.rpc),
+ minAge: Number(process.env.EVENT_MARKETS_STAKING_MIN_AGE || 21),
+ blockedCountries: new Set((process.env.EVENT_MARKETS_STAKING_BLOCKED_COUNTRIES || 'US,GB,FR,AU,SG,CN,KP,IR,CU,SY,RU,BY,MM,SD,SS')
+ .split(',').map((c) => c.trim().toUpperCase()).filter(Boolean)),
+ };
+}
+
+export function mintFor(tokenKey, cluster) {
+ if (tokenKey === 'usdc') return cluster === 'mainnet' ? USDC_MAINNET : USDC_DEVNET;
+ if (tokenKey === 'three') return env.THREE_TOKEN_MINT || 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+ throw new Error(`unknown stake token ${tokenKey}`);
+}
diff --git a/api/_lib/event-markets/staking/gate.js b/api/_lib/event-markets/staking/gate.js
new file mode 100644
index 000000000..968780ec6
--- /dev/null
+++ b/api/_lib/event-markets/staking/gate.js
@@ -0,0 +1,35 @@
+// Who may see the staking panel. Everyone else gets the free-to-play version only.
+// Order matters and every refusal names a reason the UI can explain:
+// flag off -> kill switch -> region -> attestation.
+// Region comes from the edge geo header (api/_lib/client-geo.js), never from the
+// client's claim. An unknown region is treated as blocked: when in doubt, free.
+
+import { clientCountry } from '../../client-geo.js';
+import { stakingConfig, TERMS_VERSION } from './config.js';
+
+/**
+ * @param {{req:object, attestation:?{min_age:number,country:string,terms_version:string}, stakesEnabled:boolean}} ctx
+ * @returns {{available:boolean, reason:?string, country:?string, needs_attestation:boolean, min_age:number}}
+ */
+export function evaluateGate({ req, attestation, stakesEnabled }) {
+ const cfg = stakingConfig();
+ const country = clientCountry(req);
+ const base = { country, min_age: cfg.minAge, needs_attestation: false };
+ if (!cfg.enabled) return { ...base, available: false, reason: 'disabled' };
+ if (!stakesEnabled) return { ...base, available: false, reason: 'paused' };
+ if (!country) return { ...base, available: false, reason: 'region_unknown' };
+ if (cfg.blockedCountries.has(country)) return { ...base, available: false, reason: 'region_blocked' };
+ const current = attestation && attestation.terms_version === TERMS_VERSION && attestation.min_age >= cfg.minAge;
+ if (!current) return { ...base, available: false, reason: 'attestation_required', needs_attestation: true };
+ if (attestation.country !== country) return { ...base, available: false, reason: 'attestation_region_changed', needs_attestation: true };
+ return { ...base, available: true, reason: null };
+}
+
+export const GATE_MESSAGES = {
+ disabled: 'Staked markets are not open yet. You can still make free picks.',
+ paused: 'New stakes are paused. Free picks are unaffected, and any claim or refund you are owed still works.',
+ region_unknown: 'We could not confirm your region, so staking is unavailable. Free picks are open to everyone.',
+ region_blocked: 'Staked markets are not available in your region. Free picks are open to everyone.',
+ attestation_required: 'Confirm your age and region to unlock staking.',
+ attestation_region_changed: 'Your region changed since you confirmed. Confirm again to continue.',
+};
diff --git a/api/_lib/event-markets/staking/limits.js b/api/_lib/event-markets/staking/limits.js
new file mode 100644
index 000000000..5434b6599
--- /dev/null
+++ b/api/_lib/event-markets/staking/limits.js
@@ -0,0 +1,43 @@
+// Stake limit checks, evaluated server-side BEFORE a transaction is built so the
+// user sees a plain refusal instead of a failed on-chain call. The program
+// enforces the per-account and per-pool caps again on-chain; the daily cap is
+// server-only. All amounts are BigInt base units.
+
+import { TOKENS } from './config.js';
+
+export class StakeRefusal extends Error {
+ constructor(code, message, detail = null) {
+ super(message);
+ this.code = code;
+ this.detail = detail;
+ }
+}
+
+const fmt = (v, decimals) => {
+ const s = v.toString().padStart(decimals + 1, '0');
+ const whole = s.slice(0, -decimals) || '0';
+ const frac = s.slice(-decimals).replace(/0+$/, '');
+ return frac ? `${whole}.${frac}` : whole;
+};
+export const formatAmount = fmt;
+
+/**
+ * @param {{tokenKey:string, decimals:number, minStake:bigint, maxStake:bigint, maxPool:bigint, totalStaked:bigint}} pool
+ * @param {{amount:bigint, position:bigint, accountDay:bigint}} s position = this wallet's current stake; accountDay = the account's stake over the last 24h
+ */
+export function checkStakeLimits(pool, { amount, position, accountDay }) {
+ const sym = TOKENS[pool.tokenKey].symbol;
+ const show = (v) => `${fmt(v, pool.decimals)} ${sym}`;
+ if (amount <= 0n) throw new StakeRefusal('invalid_amount', 'Enter an amount greater than zero.');
+ if (amount < pool.minStake) throw new StakeRefusal('below_minimum', `The minimum stake on this market is ${show(pool.minStake)}.`, { min: pool.minStake.toString() });
+ if (position + amount > pool.maxStake) {
+ throw new StakeRefusal('over_account_cap', `One account can stake at most ${show(pool.maxStake)} on a market. You can add ${show(pool.maxStake - position)} more.`, { room: (pool.maxStake - position).toString() });
+ }
+ if (pool.totalStaked + amount > pool.maxPool) {
+ throw new StakeRefusal('over_pool_cap', `This market's pool is capped at ${show(pool.maxPool)}. ${show(pool.maxPool - pool.totalStaked)} of room is left.`, { room: (pool.maxPool - pool.totalStaked).toString() });
+ }
+ const daily = TOKENS[pool.tokenKey].dailyCap;
+ if (accountDay + amount > daily) {
+ throw new StakeRefusal('over_daily_cap', `Your daily staking limit is ${show(daily)}. You have ${show(daily - accountDay)} left in the last 24 hours.`, { room: (daily - accountDay).toString() });
+ }
+}
diff --git a/api/_lib/event-markets/staking/reconcile.js b/api/_lib/event-markets/staking/reconcile.js
new file mode 100644
index 000000000..f19469bec
--- /dev/null
+++ b/api/_lib/event-markets/staking/reconcile.js
@@ -0,0 +1,29 @@
+// Admin reconciliation: for each pool, does the chain agree with our ledger, and
+// does the vault hold exactly what the program says it should?
+//
+// Invariant (all BigInt base units):
+// vault balance == totalStaked - feePaid - paidOut
+// chain totalStaked == sum of recorded stakes
+// chain paidOut == sum of recorded claims and refunds
+// Rounding dust left after every claim is part of totalStaked - feePaid - paidOut,
+// so it is not a discrepancy. A short vault is the alarm case; a surplus means
+// tokens were sent to the vault outside the program (harmless, but reported).
+
+export function reconcilePool({ chain, vaultBalance, ledger }) {
+ const expectedVault = chain.totalStaked - chain.feePaid - chain.paidOut;
+ const problems = [];
+ if (vaultBalance < expectedVault) problems.push({ code: 'vault_short', delta: (expectedVault - vaultBalance).toString() });
+ if (vaultBalance > expectedVault) problems.push({ code: 'vault_surplus', delta: (vaultBalance - expectedVault).toString() });
+ if (chain.totalStaked !== ledger.staked) problems.push({ code: 'ledger_stake_mismatch', delta: (chain.totalStaked - ledger.staked).toString() });
+ if (chain.paidOut !== ledger.paidOut) problems.push({ code: 'ledger_payout_mismatch', delta: (chain.paidOut - ledger.paidOut).toString() });
+ return {
+ ok: problems.length === 0,
+ expected_vault: expectedVault.toString(),
+ vault: vaultBalance.toString(),
+ chain_total_staked: chain.totalStaked.toString(),
+ ledger_staked: ledger.staked.toString(),
+ chain_paid_out: chain.paidOut.toString(),
+ ledger_paid_out: ledger.paidOut.toString(),
+ problems,
+ };
+}
diff --git a/api/_lib/event-markets/staking/record.js b/api/_lib/event-markets/staking/record.js
new file mode 100644
index 000000000..f03eb7417
--- /dev/null
+++ b/api/_lib/event-markets/staking/record.js
@@ -0,0 +1,90 @@
+// Turns confirmed on-chain transactions into ledger rows. The client may say
+// "I just staked, signature X", but nothing in the ledger comes from that claim:
+// the transaction is fetched from the cluster and parsed, and the pool, wallet,
+// outcome and amount are read from the transaction itself. A background sync
+// (syncPoolLedger) records anything made without the UI, so the daily cap and
+// the reconciliation view cannot be bypassed by skipping the record call.
+
+import { createHash } from 'node:crypto';
+import { PublicKey } from '@solana/web3.js';
+import { connection } from './chain.js';
+import { getPoolByAddress, recordLedger } from './store.js';
+import { programId } from './program.js';
+
+const disc = (name) => createHash('sha256').update(`global:${name}`).digest().subarray(0, 8);
+const KINDS = { [disc('stake').toString('hex')]: 'stake', [disc('claim').toString('hex')]: 'claim', [disc('refund').toString('hex')]: 'refund' };
+
+/**
+ * Parse a getTransaction result into the single event it carries, or null when
+ * it failed or does not contain exactly one stake, claim or refund of ours.
+ */
+export function parseProgramTx(tx, program = programId()) {
+ if (!tx || tx.meta?.err) return null;
+ const message = tx.transaction.message;
+ const keys = message.getAccountKeys
+ ? message.getAccountKeys({ accountKeysFromLookups: tx.meta?.loadedAddresses }).keySegments().flat()
+ : message.accountKeys;
+ const ixs = (message.compiledInstructions || message.instructions.map((i) => ({ programIdIndex: i.programIdIndex, accountKeyIndexes: i.accounts, data: Buffer.from(i.data, 'base64') })));
+ const ours = ixs.filter((i) => keys[i.programIdIndex].equals(program));
+ if (ours.length !== 1) return null;
+ const ix = ours[0];
+ const data = Buffer.from(ix.data);
+ const kind = KINDS[data.subarray(0, 8).toString('hex')];
+ if (!kind) return null;
+ const at = (n) => keys[ix.accountKeyIndexes[n]];
+ if (kind === 'stake') {
+ return { kind, pool: at(1).toBase58(), wallet: at(6).toBase58(), outcome: data[8], amount: data.readBigUInt64LE(9) };
+ }
+ // claim / refund: accounts are [pool, mint, vault, position, owner_tokens, owner, token_program]
+ const pool = at(0).toBase58();
+ const vault = at(2).toBase58();
+ const idx = keys.findIndex((k) => k.toBase58() === vault);
+ const pre = tx.meta.preTokenBalances.find((b) => b.accountIndex === idx);
+ const post = tx.meta.postTokenBalances.find((b) => b.accountIndex === idx);
+ const amount = BigInt(pre?.uiTokenAmount.amount ?? 0) - BigInt(post?.uiTokenAmount.amount ?? 0);
+ return { kind, pool, wallet: at(5).toBase58(), outcome: null, amount };
+}
+
+export async function fetchParsed(signature) {
+ const tx = await connection().getTransaction(signature, { commitment: 'confirmed', maxSupportedTransactionVersion: 0 });
+ if (!tx) return null;
+ const parsed = parseProgramTx(tx);
+ return parsed && { ...parsed, signature, slot: tx.slot };
+}
+
+/** Record one signature. Returns the parsed event, or null when it is not one of ours. */
+export async function recordSignature(signature, accountId) {
+ const event = await fetchParsed(signature);
+ if (!event) return null;
+ const pool = await getPoolByAddress(event.pool);
+ if (!pool) return null;
+ const inserted = await recordLedger({
+ marketId: pool.marketId, accountId, wallet: event.wallet, kind: event.kind,
+ outcomeIndex: event.outcome, amount: event.amount, signature, slot: event.slot,
+ });
+ return { ...event, marketId: pool.marketId, inserted };
+}
+
+/** Walk every signature touching the pool and record the ones the ledger has not seen. */
+export async function syncPoolLedger(pool, { accountForWallet }) {
+ const conn = connection();
+ let before;
+ let recorded = 0;
+ for (;;) {
+ const page = await conn.getSignaturesForAddress(new PublicKey(pool.poolAddress), { before, limit: 500 }, 'confirmed');
+ if (!page.length) break;
+ for (const s of page) {
+ if (s.err) continue;
+ const event = await fetchParsed(s.signature);
+ if (!event || event.pool !== pool.poolAddress) continue;
+ const inserted = await recordLedger({
+ marketId: pool.marketId, accountId: await accountForWallet(event.wallet), wallet: event.wallet, kind: event.kind,
+ outcomeIndex: event.outcome, amount: event.amount, signature: s.signature, slot: event.slot,
+ });
+ if (inserted) recorded++;
+ }
+ before = page[page.length - 1].signature;
+ if (page.length < 500) break;
+ }
+ return recorded;
+}
diff --git a/api/_lib/event-markets/staking/routes.js b/api/_lib/event-markets/staking/routes.js
new file mode 100644
index 000000000..9ebec041d
--- /dev/null
+++ b/api/_lib/event-markets/staking/routes.js
@@ -0,0 +1,81 @@
+// REST routes for staked Event Markets, mounted next to the free-to-play routes
+// by api/_lib/event-markets/routes.js. The server builds UNSIGNED transactions
+// and records confirmed ones; it never signs or holds a staker's funds.
+// GET :slug/staking panel state (gate, pool, odds, your position)
+// POST :slug/staking/attest age and region attestation
+// POST :slug/staking/stake unsigned stake tx + preview
+// POST :slug/staking/payout unsigned claim or refund tx
+// POST :slug/staking/record verify + ledger a confirmed signature
+// Guide: docs/event-markets-staking.md.
+
+import { apiError } from '../../agents-v1/http.js';
+import { getMarket } from '../index.js';
+import { attest, prepareStake, preparePayout, stakingView } from './service.js';
+import { StakeRefusal } from './limits.js';
+import { recordSignature } from './record.js';
+
+const SIG_RE = /^[1-9A-HJ-NP-Za-km-z]{64,90}$/;
+
+async function marketOr404(slug) {
+ const market = await getMarket(slug);
+ if (!market || market.status === 'draft') throw apiError(404, 'not_found', 'No market with that id.');
+ return market;
+}
+
+const refuse = (err) => {
+ if (err instanceof StakeRefusal) return apiError(err.code === 'not_offered' ? 404 : 403, err.code, err.message, err.detail);
+ return err;
+};
+
+async function view({ req, params, query, principal }) {
+ const market = await marketOr404(params.slug);
+ try {
+ return await stakingView(req, market.id, principal, query.wallet || null);
+ } catch (err) {
+ throw refuse(err);
+ }
+}
+
+async function attestRoute({ req, body, principal }) {
+ try {
+ return { gate: await attest(req, principal, { confirmedAge: body.confirmed_age, confirmedRegion: body.confirmed_region }) };
+ } catch (err) {
+ throw refuse(err);
+ }
+}
+
+async function stakeRoute({ req, params, body, principal }) {
+ const market = await marketOr404(params.slug);
+ try {
+ return await prepareStake(req, market.id, principal, { wallet: body.wallet, outcomeId: body.outcome_id, amount: body.amount });
+ } catch (err) {
+ throw refuse(err);
+ }
+}
+
+async function payoutRoute({ params, body }) {
+ const market = await marketOr404(params.slug);
+ if (body.kind !== 'claim' && body.kind !== 'refund') throw apiError(400, 'invalid_kind', 'kind must be claim or refund.');
+ try {
+ return await preparePayout(market.id, { wallet: body.wallet, kind: body.kind });
+ } catch (err) {
+ throw refuse(err);
+ }
+}
+
+async function recordRoute({ body, principal }) {
+ if (typeof body.signature !== 'string' || !SIG_RE.test(body.signature)) throw apiError(400, 'invalid_signature', 'signature must be a transaction signature.');
+ const event = await recordSignature(body.signature, principal.userId);
+ if (!event) throw apiError(422, 'not_a_stake_tx', 'That transaction is not a confirmed stake, claim or refund on a staked market.');
+ return { recorded: event.inserted, kind: event.kind, amount: event.amount.toString() };
+}
+
+export function stakingRoutes(prefix = '/event-markets') {
+ return [
+ { method: 'GET', path: `${prefix}/:slug/staking`, name: 'event_markets.staking', auth: 'optional', handler: view },
+ { method: 'POST', path: `${prefix}/:slug/staking/attest`, name: 'event_markets.staking_attest', auth: 'required', handler: attestRoute },
+ { method: 'POST', path: `${prefix}/:slug/staking/stake`, name: 'event_markets.staking_stake', auth: 'required', handler: stakeRoute },
+ { method: 'POST', path: `${prefix}/:slug/staking/payout`, name: 'event_markets.staking_payout', auth: 'required', handler: payoutRoute },
+ { method: 'POST', path: `${prefix}/:slug/staking/record`, name: 'event_markets.staking_record', auth: 'required', handler: recordRoute },
+ ];
+}
diff --git a/api/_lib/event-markets/staking/service.js b/api/_lib/event-markets/staking/service.js
new file mode 100644
index 000000000..df79e8e6d
--- /dev/null
+++ b/api/_lib/event-markets/staking/service.js
@@ -0,0 +1,148 @@
+// Orchestration for staked Event Markets: what a market page needs to render the
+// panel, the stake preview, and the unsigned transactions. Route handlers and the
+// admin CLI both call in here. Nothing in this module signs or sends a transaction.
+
+import { PublicKey } from '@solana/web3.js';
+import { evaluateGate, GATE_MESSAGES } from './gate.js';
+import { checkStakeLimits, formatAmount, StakeRefusal } from './limits.js';
+import { previewStake, poolShares } from './math.js';
+import { TOKENS, TERMS_VERSION, stakingConfig } from './config.js';
+import { buildPayoutTx, buildStakeTx, readPool, readPosition } from './chain.js';
+import { accountExposure, getAttestation, getPoolByMarket, getSettings, saveAttestation } from './store.js';
+import { clientCountry } from '../../client-geo.js';
+
+const str = (v) => (v == null ? null : v.toString());
+
+function requireWallet(wallet) {
+ try {
+ return new PublicKey(wallet).toBase58();
+ } catch {
+ throw new StakeRefusal('invalid_wallet', 'wallet must be a Solana address.');
+ }
+}
+
+function outcomeIndexFor(pool, outcomeId) {
+ const i = pool.outcomeIds.indexOf(outcomeId);
+ if (i < 0) throw new StakeRefusal('invalid_outcome', 'outcome_id is not an outcome of this market.');
+ return i;
+}
+
+function parseAmount(raw) {
+ if (typeof raw !== 'string' || !/^\d{1,30}$/.test(raw)) throw new StakeRefusal('invalid_amount', 'amount must be a whole number of base units, as a string.');
+ return BigInt(raw);
+}
+
+async function gateFor(req, principal) {
+ const [attestation, settings] = await Promise.all([
+ principal?.userId ? getAttestation(principal.userId) : null,
+ getSettings(),
+ ]);
+ const gate = evaluateGate({ req, attestation, stakesEnabled: settings.stakesEnabled });
+ return { ...gate, message: gate.reason ? GATE_MESSAGES[gate.reason] : null, signed_in: Boolean(principal?.userId) };
+}
+
+/** Public view for the market page. Staked data appears only when the gate is open. */
+export async function stakingView(req, marketId, principal, wallet = null) {
+ const pool = await getPoolByMarket(marketId);
+ if (!pool) return { offered: false };
+ const gate = await gateFor(req, principal);
+ // A viewer who is gated out of NEW stakes still sees their own claim/refund state.
+ const chain = await readPool(pool.poolIdHex);
+ if (!chain) return { offered: false };
+ const token = TOKENS[pool.tokenKey];
+ const base = {
+ offered: true,
+ gate,
+ cluster: pool.cluster,
+ token: { key: pool.tokenKey, symbol: token.symbol, decimals: pool.decimals, mint: pool.mint },
+ status: chain.statusName,
+ terms_version: TERMS_VERSION,
+ limits: { min: str(pool.minStake), max_stake: str(pool.maxStake), max_pool: str(pool.maxPool), daily_cap: str(token.dailyCap) },
+ fee: { fee_bps: chain.feeBps, buyback_share_bps: chain.buybackShareBps },
+ lock_at: pool.lockAt,
+ void_after: pool.voidAfter,
+ total_staked: str(chain.totalStaked),
+ outcomes: pool.outcomeIds.map((id, i) => ({ outcome_id: id, staked: str(chain.totals[i]), share: poolShares(chain.totals)[i] })),
+ winning_outcome_id: chain.statusName === 'resolved' ? pool.outcomeIds[chain.winningOutcome] : null,
+ };
+ if (wallet) {
+ const position = await readPosition(pool.poolIdHex, requireWallet(wallet));
+ if (position) {
+ const idx = position.outcome;
+ base.position = {
+ outcome_id: pool.outcomeIds[idx], amount: str(position.amount),
+ claimable: chain.statusName === 'resolved' && idx === chain.winningOutcome,
+ refundable: chain.statusName === 'void',
+ payout: chain.statusName === 'resolved' && idx === chain.winningOutcome
+ ? str(previewStake({ totals: chain.totals.map((t, j) => (j === idx ? t - position.amount : t)), feeBps: chain.feeBps, buybackShareBps: chain.buybackShareBps }, idx, position.amount).payout)
+ : null,
+ };
+ }
+ }
+ return base;
+}
+
+/** Build a stake: gate, limits, preview, and the unsigned transaction. */
+export async function prepareStake(req, marketId, principal, { wallet, outcomeId, amount }) {
+ const pool = await getPoolByMarket(marketId);
+ if (!pool) throw new StakeRefusal('not_offered', 'This market has no staked version.');
+ const gate = await gateFor(req, principal);
+ if (!gate.available) throw new StakeRefusal(gate.reason, gate.message, { gate });
+ const w = requireWallet(wallet);
+ const outcome = outcomeIndexFor(pool, outcomeId);
+ const amt = parseAmount(amount);
+ const chain = await readPool(pool.poolIdHex);
+ if (!chain || chain.statusName !== 'open') throw new StakeRefusal('not_open', 'This market is no longer taking stakes.');
+ if (Date.now() >= Number(chain.lockTs) * 1000) throw new StakeRefusal('locked', 'This market is locked.');
+ const position = await readPosition(pool.poolIdHex, w);
+ if (position && position.outcome !== outcome) throw new StakeRefusal('outcome_mismatch', 'This wallet already backs a different outcome. A position can back only one.');
+ const exposure = await accountExposure(principal.userId, marketId);
+ checkStakeLimits({ ...pool, totalStaked: chain.totalStaked }, { amount: amt, position: position?.amount ?? 0n, accountDay: exposure.day });
+
+ const p = previewStake({ totals: chain.totals, feeBps: chain.feeBps, buybackShareBps: chain.buybackShareBps }, outcome, amt, position?.amount ?? 0n);
+ const built = await buildStakeTx(pool, { wallet: w, outcome, amount: amt });
+ return {
+ ...built,
+ confirm: {
+ chain: 'solana', cluster: pool.cluster, token: TOKENS[pool.tokenKey].symbol, mint: pool.mint,
+ pool_address: pool.poolAddress, wallet: w, outcome_id: outcomeId,
+ amount: str(amt), amount_display: formatAmount(amt, pool.decimals),
+ },
+ preview: {
+ stake: str(p.stake), pool_after: str(p.total), fee_if_resolved: str(p.fee),
+ payout_if_right: str(p.payout), profit_if_right: str(p.profit), multiple_if_right: p.multiple,
+ refunded_if_wins: p.void_if_wins,
+ note: p.void_if_wins ? 'Nobody else is on the other side yet. If it stays that way you are refunded in full, with no fee.' : null,
+ },
+ };
+}
+
+export async function preparePayout(marketId, { wallet, kind }) {
+ const pool = await getPoolByMarket(marketId);
+ if (!pool) throw new StakeRefusal('not_offered', 'This market has no staked version.');
+ const w = requireWallet(wallet);
+ const chain = await readPool(pool.poolIdHex);
+ if (!chain) throw new StakeRefusal('not_offered', 'This market has no staked version.');
+ const position = await readPosition(pool.poolIdHex, w);
+ if (!position) throw new StakeRefusal('no_position', 'This wallet has nothing to collect on this market. It may already have been paid.');
+ if (kind === 'claim') {
+ if (chain.statusName !== 'resolved') throw new StakeRefusal('not_resolved', 'This market has not been resolved yet.');
+ if (position.outcome !== chain.winningOutcome) throw new StakeRefusal('not_winner', 'This wallet did not back the winning outcome.');
+ } else if (chain.statusName !== 'void') {
+ throw new StakeRefusal('not_void', 'This market was not voided, so there is nothing to refund.');
+ }
+ const built = await buildPayoutTx(pool, { wallet: w, kind });
+ return { ...built, confirm: { chain: 'solana', cluster: pool.cluster, token: TOKENS[pool.tokenKey].symbol, mint: pool.mint, wallet: w, kind, pool_address: pool.poolAddress } };
+}
+
+export async function attest(req, principal, { confirmedAge, confirmedRegion }) {
+ const cfg = stakingConfig();
+ const country = clientCountry(req);
+ if (!country) throw new StakeRefusal('region_unknown', GATE_MESSAGES.region_unknown);
+ if (cfg.blockedCountries.has(country)) throw new StakeRefusal('region_blocked', GATE_MESSAGES.region_blocked);
+ if (confirmedAge !== true || confirmedRegion !== true) {
+ throw new StakeRefusal('attestation_incomplete', `Confirm you are at least ${cfg.minAge} and that staking is lawful where you live.`);
+ }
+ await saveAttestation(principal.userId, { minAge: cfg.minAge, country, termsVersion: TERMS_VERSION });
+ return gateFor(req, principal);
+}
diff --git a/api/_lib/event-markets/staking/store.js b/api/_lib/event-markets/staking/store.js
new file mode 100644
index 000000000..f4a2a8da1
--- /dev/null
+++ b/api/_lib/event-markets/staking/store.js
@@ -0,0 +1,97 @@
+// SQL for staked Event Markets: pools, the verified stake ledger, the kill
+// switch and age/region attestations. Tables: migrations/20261013000000_event_market_staking.sql.
+
+import { sql } from '../../db.js';
+
+const big = (v) => BigInt(v ?? 0);
+
+export function poolFromRow(r) {
+ if (!r) return null;
+ return {
+ marketId: r.market_id, cluster: r.cluster, programId: r.program_id, poolIdHex: r.pool_id_hex,
+ poolAddress: r.pool_address, mint: r.mint, tokenKey: r.token_key, decimals: r.decimals,
+ outcomeIds: r.outcome_ids, minStake: big(r.min_stake), maxStake: big(r.max_stake), maxPool: big(r.max_pool),
+ feeBps: r.fee_bps, buybackShareBps: r.buyback_share_bps, lockAt: r.lock_at, voidAfter: r.void_after,
+ status: r.status, createSignature: r.create_signature, resolveSignature: r.resolve_signature,
+ };
+}
+
+export async function getPoolByMarket(marketId) {
+ const [row] = await sql`select * from event_market_stake_pools where market_id = ${marketId}`;
+ return poolFromRow(row);
+}
+
+export async function getPoolByAddress(address) {
+ const [row] = await sql`select * from event_market_stake_pools where pool_address = ${address}`;
+ return poolFromRow(row);
+}
+
+export async function listPools() {
+ return (await sql`select * from event_market_stake_pools order by created_at desc`).map(poolFromRow);
+}
+
+export async function insertPool(p) {
+ await sql`
+ insert into event_market_stake_pools
+ (market_id, cluster, program_id, pool_id_hex, pool_address, mint, token_key, decimals, outcome_ids,
+ min_stake, max_stake, max_pool, fee_bps, buyback_share_bps, lock_at, void_after, create_signature)
+ values (${p.marketId}, ${p.cluster}, ${p.programId}, ${p.poolIdHex}, ${p.poolAddress}, ${p.mint}, ${p.tokenKey}, ${p.decimals},
+ ${p.outcomeIds}::uuid[], ${p.minStake.toString()}, ${p.maxStake.toString()}, ${p.maxPool.toString()},
+ ${p.feeBps}, ${p.buybackShareBps}, ${p.lockAt}, ${p.voidAfter}, ${p.createSignature})`;
+}
+
+export async function markPoolStatus(marketId, status, signature = null) {
+ await sql`update event_market_stake_pools set status = ${status}, resolve_signature = coalesce(${signature}, resolve_signature) where market_id = ${marketId}`;
+}
+
+/** Idempotent on signature: re-recording a confirmed transaction is a no-op. */
+export async function recordLedger({ marketId, accountId, wallet, kind, outcomeIndex, amount, signature, slot }) {
+ const [row] = await sql`
+ insert into event_market_stakes (market_id, account_id, wallet, kind, outcome_index, amount, signature, slot)
+ values (${marketId}, ${accountId}, ${wallet}, ${kind}, ${outcomeIndex}, ${amount.toString()}, ${signature}, ${slot})
+ on conflict (signature) do nothing
+ returning id`;
+ return Boolean(row);
+}
+
+/** Sum of an account's recorded stake on one market, and over the last 24h across all markets. */
+export async function accountExposure(accountId, marketId) {
+ const [row] = await sql`
+ select coalesce(sum(amount) filter (where market_id = ${marketId}), 0)::text as on_market,
+ coalesce(sum(amount) filter (where created_at > now() - interval '24 hours'), 0)::text as day
+ from event_market_stakes where account_id = ${accountId} and kind = 'stake'`;
+ return { onMarket: big(row.on_market), day: big(row.day) };
+}
+
+export async function ledgerTotals(marketId) {
+ const [row] = await sql`
+ select coalesce(sum(amount) filter (where kind = 'stake'), 0)::text as staked,
+ coalesce(sum(amount) filter (where kind in ('claim', 'refund')), 0)::text as paid_out,
+ count(*) filter (where kind = 'stake')::int as stakes
+ from event_market_stakes where market_id = ${marketId}`;
+ return { staked: big(row.staked), paidOut: big(row.paid_out), stakes: row.stakes };
+}
+
+export async function getSettings() {
+ const [row] = await sql`select stakes_enabled, updated_at from event_market_stake_settings where id = 1`;
+ return { stakesEnabled: row ? row.stakes_enabled : true, updatedAt: row?.updated_at ?? null };
+}
+
+export async function setStakesEnabled(enabled, adminId) {
+ await sql`
+ insert into event_market_stake_settings (id, stakes_enabled, updated_by, updated_at) values (1, ${enabled}, ${adminId}, now())
+ on conflict (id) do update set stakes_enabled = excluded.stakes_enabled, updated_by = excluded.updated_by, updated_at = now()`;
+}
+
+export async function getAttestation(accountId) {
+ const [row] = await sql`select min_age, country, terms_version, attested_at from event_market_stake_attestations where account_id = ${accountId}`;
+ return row || null;
+}
+
+export async function saveAttestation(accountId, { minAge, country, termsVersion }) {
+ await sql`
+ insert into event_market_stake_attestations (account_id, min_age, country, terms_version)
+ values (${accountId}, ${minAge}, ${country}, ${termsVersion})
+ on conflict (account_id) do update set min_age = excluded.min_age, country = excluded.country,
+ terms_version = excluded.terms_version, attested_at = now()`;
+}
diff --git a/api/_lib/migrations/20261013000000_event_market_staking.sql b/api/_lib/migrations/20261013000000_event_market_staking.sql
new file mode 100644
index 000000000..109b49f82
--- /dev/null
+++ b/api/_lib/migrations/20261013000000_event_market_staking.sql
@@ -0,0 +1,66 @@
+-- Event Markets staking (brief 10): pool registry, stake ledger, kill switch, attestations.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261013000000_event_market_staking.sql
+-- Idempotent and additive. Nothing here touches event_market_picks, so staked and
+-- free-to-play standings can never mix. Docs: docs/event-markets-staking.md.
+
+-- One on-chain pool per market. Created only by the owner-gated admin CLI.
+CREATE TABLE IF NOT EXISTS event_market_stake_pools (
+ market_id uuid PRIMARY KEY REFERENCES event_markets(id) ON DELETE CASCADE,
+ cluster text NOT NULL CHECK (cluster IN ('localnet', 'devnet', 'mainnet')),
+ program_id text NOT NULL,
+ pool_id_hex text NOT NULL,
+ pool_address text NOT NULL UNIQUE,
+ mint text NOT NULL,
+ token_key text NOT NULL CHECK (token_key IN ('usdc', 'three')),
+ decimals smallint NOT NULL CHECK (decimals BETWEEN 0 AND 18),
+ outcome_ids uuid[] NOT NULL,
+ min_stake numeric(40, 0) NOT NULL CHECK (min_stake > 0),
+ max_stake numeric(40, 0) NOT NULL,
+ max_pool numeric(40, 0) NOT NULL,
+ fee_bps integer NOT NULL CHECK (fee_bps BETWEEN 0 AND 1000),
+ buyback_share_bps integer NOT NULL CHECK (buyback_share_bps BETWEEN 0 AND 10000),
+ lock_at timestamptz NOT NULL,
+ void_after timestamptz NOT NULL,
+ status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'resolved', 'void')),
+ create_signature text NOT NULL,
+ resolve_signature text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ CHECK (max_stake >= min_stake AND max_pool >= max_stake AND void_after > lock_at)
+);
+
+-- Every confirmed stake, claim and refund, recorded from the verified transaction
+-- (never from the client's say-so). The admin reconciliation view compares this
+-- ledger to the chain.
+CREATE TABLE IF NOT EXISTS event_market_stakes (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ market_id uuid NOT NULL REFERENCES event_market_stake_pools(market_id) ON DELETE CASCADE,
+ account_id uuid REFERENCES users(id) ON DELETE SET NULL,
+ wallet text NOT NULL,
+ kind text NOT NULL CHECK (kind IN ('stake', 'claim', 'refund')),
+ outcome_index smallint,
+ amount numeric(40, 0) NOT NULL CHECK (amount >= 0),
+ signature text NOT NULL UNIQUE,
+ slot bigint NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS event_market_stakes_market_idx ON event_market_stakes (market_id, kind);
+CREATE INDEX IF NOT EXISTS event_market_stakes_account_idx ON event_market_stakes (account_id, created_at DESC);
+
+-- Single-row switch. stakes_enabled = false stops new stake transactions being built
+-- the instant it is written; claims and refunds are never blocked by it.
+CREATE TABLE IF NOT EXISTS event_market_stake_settings (
+ id smallint PRIMARY KEY DEFAULT 1 CHECK (id = 1),
+ stakes_enabled boolean NOT NULL DEFAULT true,
+ updated_by uuid REFERENCES users(id) ON DELETE SET NULL,
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+INSERT INTO event_market_stake_settings (id) VALUES (1) ON CONFLICT DO NOTHING;
+
+-- An account's own attestation that it meets the age and jurisdiction terms.
+CREATE TABLE IF NOT EXISTS event_market_stake_attestations (
+ account_id uuid PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
+ min_age smallint NOT NULL,
+ country char(2) NOT NULL,
+ terms_version text NOT NULL,
+ attested_at timestamptz NOT NULL DEFAULT now()
+);
diff --git a/api/event-markets/staking-admin.js b/api/event-markets/staking-admin.js
new file mode 100644
index 000000000..426d414f5
--- /dev/null
+++ b/api/event-markets/staking-admin.js
@@ -0,0 +1,66 @@
+// /api/event-markets/staking-admin: owner view of every staked pool. Admin only.
+// GET reconcile: sync each pool's ledger from the chain, then compare vault
+// balance, on-chain totals and recorded stakes. Also the kill-switch state.
+// POST { action: 'pause' | 'resume' } flip the instant kill switch for NEW stakes
+// Claims and refunds are never blocked by the switch. Guide: docs/event-markets-staking.md.
+
+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
+import { requireAdmin } from '../_lib/admin.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { sql } from '../_lib/db.js';
+import { stakingConfig } from '../_lib/event-markets/staking/config.js';
+import { readConfig, readPool, vaultBalance } from '../_lib/event-markets/staking/chain.js';
+import { ledgerTotals, listPools, getSettings, setStakesEnabled } from '../_lib/event-markets/staking/store.js';
+import { reconcilePool } from '../_lib/event-markets/staking/reconcile.js';
+import { syncPoolLedger } from '../_lib/event-markets/staking/record.js';
+
+/** Attribute an unrecorded on-chain event to an account when that wallet staked through the UI before. */
+async function accountForWallet(wallet) {
+ const [row] = await sql`select account_id from event_market_stakes where wallet = ${wallet} and account_id is not null limit 1`;
+ return row?.account_id ?? null;
+}
+
+async function reconcileAll() {
+ const out = [];
+ for (const pool of await listPools()) {
+ const [title] = await sql`select title, slug from event_markets where id = ${pool.marketId}`;
+ let entry = { market_id: pool.marketId, slug: title?.slug, title: title?.title, token: pool.tokenKey, cluster: pool.cluster, status: pool.status, pool_address: pool.poolAddress };
+ try {
+ const synced = await syncPoolLedger(pool, { accountForWallet });
+ const [chain, vault, ledger] = await Promise.all([readPool(pool.poolIdHex), vaultBalance(pool.poolIdHex, pool.mint), ledgerTotals(pool.marketId)]);
+ entry = chain
+ ? { ...entry, chain_status: chain.statusName, synced_from_chain: synced, ...reconcilePool({ chain, vaultBalance: vault, ledger }) }
+ : { ...entry, ok: false, problems: [{ code: 'pool_missing_on_chain' }] };
+ } catch (err) {
+ entry = { ...entry, ok: false, problems: [{ code: 'chain_unreachable', message: err.message }] };
+ }
+ out.push(entry);
+ }
+ return out;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+ const admin = await requireAdmin(req, res);
+ if (!admin) return;
+
+ if (req.method === 'GET') {
+ const cfg = stakingConfig();
+ const [settings, pools, onchain] = await Promise.all([getSettings(), reconcileAll(), readConfig().catch(() => null)]);
+ return json(res, 200, {
+ flag_enabled: cfg.enabled,
+ cluster: cfg.cluster,
+ stakes_enabled: settings.stakesEnabled,
+ onchain_paused: onchain ? onchain.paused : null,
+ pools,
+ all_ok: pools.every((p) => p.ok),
+ }, { 'cache-control': 'no-store' });
+ }
+
+ if (!(await requireCsrf(req, res, admin.id))) return;
+ const body = (await readJson(req)) || {};
+ if (body.action !== 'pause' && body.action !== 'resume') return error(res, 400, 'validation_error', 'action must be pause or resume');
+ await setStakesEnabled(body.action === 'resume', admin.id);
+ return json(res, 200, { stakes_enabled: body.action === 'resume' });
+});
diff --git a/contracts/event-markets-stake/README.md b/contracts/event-markets-stake/README.md
new file mode 100644
index 000000000..4d5b11740
--- /dev/null
+++ b/contracts/event-markets-stake/README.md
@@ -0,0 +1,30 @@
+# event-markets-stake
+
+Minimal Anchor program (0.31) for staked Event Markets: a parimutuel pool per market. Spec and decisions: [docs/event-markets-staking.md](../../docs/event-markets-staking.md). **Unaudited. Not deployed to any cluster.**
+
+## Instructions
+
+| Instruction | Who | Effect |
+| --- | --- | --- |
+| `initialize` | authority | Creates the config: resolver, fee destinations, fee bps, buyback share. |
+| `set_config` | authority | Changes any config field, pauses or resumes, rotates the authority. |
+| `create_pool` | resolver | New pool for a 32-byte id, with outcome count, min, max, pool cap, lock and void deadlines. Snapshots fee and destinations. |
+| `stake` | anyone | Stakes on one outcome. A wallet can back one outcome per pool. |
+| `lock` | resolver | Closes staking early. |
+| `resolve` | resolver | Records the winner and pays the fee to the treasury and buyback accounts. |
+| `void_pool` | resolver | Voids; every staker refunds in full. |
+| `void_expired` | anyone | Voids an unresolved pool after `void_after_ts`. |
+| `claim` | winner | Pays `floor(stake * (total - fee) / winning_total)`. One shot. |
+| `refund` | staker | Returns the full stake from a void pool. One shot. |
+
+`pause` stops `create_pool` and `stake` only. Claims, refunds and `void_expired` are never blocked.
+
+PDAs: `["config"]`, `["pool", pool_id]`, `["position", pool, owner]`; the vault is the pool's associated token account. Supports SPL Token and Token-2022.
+
+## Test
+
+`npm run test:stake-program` builds the program, boots `solana-test-validator` with it loaded, runs [tests/event-markets-staking.chain.test.js](../../tests/event-markets-staking.chain.test.js) (full cycle, every error path, double claim, wrong authority, payout parity with the JS math, Token-2022), and stops the validator by PID. Needs the Solana CLI (`cargo-build-sbf`).
+
+## Deploy
+
+Owner-gated, see the step list in the decision record. Never commit `target/deploy/*-keypair.json`; `contracts/*/target/` is gitignored.
diff --git a/docs/event-markets-staking.md b/docs/event-markets-staking.md
new file mode 100644
index 000000000..54a1bc961
--- /dev/null
+++ b/docs/event-markets-staking.md
@@ -0,0 +1,101 @@
+# Staked Event Markets on Solana
+
+Status: built and tested on a local validator. Not deployed to any cluster. Off by default (`EVENT_MARKETS_STAKING_ENABLED` unset). The free-to-play picks remain the public product; staking is a second, separate panel that only appears for eligible viewers once the owner turns it on.
+
+Legend: **[Rec]** is my recommended default, chosen so the owner is not interviewed. **[Owner]** is a decision only the owner (and counsel) can make. Every default lives in [api/_lib/event-markets/staking/config.js](../api/_lib/event-markets/staking/config.js) or on-chain config, so changing one is a one-line edit.
+
+## What was built
+
+| Piece | Where |
+| --- | --- |
+| Anchor program: create pool, stake, lock, resolve, claim, refund, void, permissionless expiry void | [contracts/event-markets-stake/](../contracts/event-markets-stake/README.md) |
+| Server: unsigned stake and payout transactions, preview, gate, caps, ledger, reconciliation | [api/_lib/event-markets/staking/](../api/_lib/event-markets/staking/) |
+| Routes | `GET/POST /api/event-markets/:slug/staking[/attest\|/stake\|/payout\|/record]` |
+| Admin API and page | `/api/event-markets/staking-admin`, `/admin/event-markets-staking` |
+| Owner CLI (every fund-moving command is dry-run until `--yes`) | [scripts/event-markets-stake-admin.mjs](../scripts/event-markets-stake-admin.mjs) |
+| Stake panel on the market page | [src/event-markets/staking-panel.js](../src/event-markets/staking-panel.js) |
+| Tests | [tests/event-markets-staking.test.js](../tests/event-markets-staking.test.js), [tests/event-markets-staking.chain.test.js](../tests/event-markets-staking.chain.test.js) |
+
+The server never holds funds and never signs a stake. It returns a base64 transaction with the staker as fee payer and no signatures; the staker's own wallet signs after an explicit confirm. The only keys the platform holds are the program authority (config changes) and the resolver (create pool, lock, resolve, void). Neither can move a staker's funds to anywhere except the pool's own payouts and the fee destinations recorded in the pool at creation.
+
+## Decision record
+
+### 1. Model: parimutuel, 3% fee [Rec]
+
+All stakes on a market go in one pool. Winners split the pool, minus the fee, in proportion to their stake on the winning outcome. There is no house counterparty and no price to take, so the platform carries no market risk.
+
+```
+fee = floor(total * fee_bps / 10000)
+payout = floor(stake * (total - fee) / winning_total)
+```
+
+Rounding dust (a few base units) stays in the vault. The JS preview and the program use the same integer math; the chain test asserts equality to the base unit for every payout. Fee 3% (300 bps) [Rec]; the program hard-caps it at 10% so a bad config cannot take more. [Owner]: confirm the rate.
+
+### 2. Stake tokens: USDC and $THREE [Rec]
+
+One token per pool, chosen when the pool is created. Classic SPL and Token-2022 mints both work. USDC gives a stable unit; $THREE keeps the platform coin at the center. Devnet uses the devnet USDC mint and the real $THREE mint address from `THREE_TOKEN_MINT`. [Owner]: confirm the token list.
+
+### 3. Fee split and buyback share [Rec]
+
+50% of the fee goes to a $THREE buyback wallet, 50% to the treasury. Both destinations and the split are snapshotted into each pool at creation, so a later config change cannot redirect a live pool. The program transfers the fee at resolve time; the platform does not hold it. The buyback wallet only receives the fee token; executing the actual buyback is a separate owner-gated action and is not built here. [Owner]: split ratio, and the two destination wallets.
+
+### 4. Limits [Rec]
+
+| | USDC | $THREE |
+| --- | --- | --- |
+| Min stake | 1 | 1,000 |
+| Max per account per market | 100 | 1,000,000 |
+| Max pool per market | 5,000 | 50,000,000 |
+| Daily per account (server) | 250 | 2,500,000 |
+
+Min, per-account and pool caps are enforced on-chain as well as by the server. The daily cap is server-side. Small on purpose for a first launch. [Owner]: raise after the audit.
+
+### 5. Timing [Rec]
+
+- Staking closes at the market's `locks_at` (the on-chain `lock_ts`). The resolver can also lock early.
+- The owner resolves on-chain after the platform market resolves; the winner is read from the platform's resolved row, never typed in.
+- If the pool is not resolved within 7 days of the lock, anyone can void it (`void_expired`) and every staker refunds. This bounds the damage of a lost or compromised resolver key to a delay, never a loss.
+
+### 6. Void, refund and the no-winner cases [Rec]
+
+- **Void** (platform void, tie, cancellation, or expiry): every staker refunds their full stake. No fee is taken.
+- **Nobody picked the winner:** the pool is voided and everyone refunds in full. The house does not keep losers' stakes when no one could have won. The CLI refuses to resolve in this case and points at `void`.
+- **No contest** (every stake on the winner): nobody loses, so the pool refunds with no fee.
+- Claims, refunds and `void_expired` can never be blocked by the kill switch or by pausing the program.
+
+### 7. Safety controls
+
+- Per-account and per-market caps (above), plus the daily cap.
+- Instant kill switch: the admin page, or `pause` in the CLI. It stops new pools and new stakes only.
+- Admin reconciliation page: for every pool, vault balance against `totalStaked - feePaid - paidOut`, and on-chain totals against recorded stakes. A short vault is flagged as the alarm case.
+- Staked and free-to-play never share a leaderboard. Stakes are not points, never enter scoring, and the panel states this.
+- Token names, symbols and entrant labels are untrusted data: a stake or payout is only ever built from the signed-in user's own request, the pool's recorded outcome ids and the user's wallet.
+
+### 8. Jurisdiction and age gating [Owner]
+
+I am not a lawyer and this is not legal advice. Staking real tokens on event outcomes is likely regulated as gambling, a wagering product or a derivative in many places. Open questions for counsel:
+
+1. Which jurisdictions may the product serve at all, and is a licence needed anywhere it is offered?
+2. Is a parimutuel prediction pool on platform-internal events (Arena results, bounties) treated differently from sports or political outcomes?
+3. Minimum age. Default 21 [Rec] (the strictest common threshold).
+4. Do the terms, KYC or sanctions screening need more than a self-attestation?
+5. Does a buyback funded by wagering fees change how $THREE is characterized?
+
+Defaults shipped [Rec], all editable by env: blocked regions `US,GB,FR,AU,SG,CN,KP,IR,CU,SY,RU,BY,MM,SD,SS` (`EVENT_MARKETS_STAKING_BLOCKED_COUNTRIES`); minimum age 21 (`EVENT_MARKETS_STAKING_MIN_AGE`). Region comes from the edge geo header, never from the client; an unknown region counts as blocked. Eligibility needs a signed-in account, a current attestation (age, lawful in region, terms version) and a matching region. Everyone else sees the free picks only. Because the gate relies on a geo header, VPN use defeats it; that is a legal question above, not an engineering one.
+
+### 9. Reusable audited code [finding]
+
+I searched for an audited, reusable parimutuel or escrow program. The repo has [contracts/knock-escrow/](../contracts/knock-escrow/README.md), a two-party escrow that cannot express pools, per-outcome totals or proportional payouts. `solana-agent-sdk` and `agent-payments-sdk` build and send transfers but ship no on-chain program. I found no audited open-source parimutuel pool that supports both token programs and the void rules above, so the program is new and minimal (about 600 lines). It is **unaudited**.
+
+## Owner steps (one command each)
+
+Nothing below has been run. Fund-moving commands print recipient, amount, token and chain, and do nothing without `--yes` (and `--confirm-mainnet` on mainnet).
+
+1. **Audit.** Have the program reviewed externally. Local suite: `npm run test:stake-program`.
+2. **Generate the keys** (authority and resolver, hardware-backed in production): `solana-keygen new -o ~/.config/three-ws/stake-authority.json` and the same for the resolver; set `EVENT_MARKETS_STAKE_AUTHORITY_KEYPAIR` and `EVENT_MARKETS_STAKE_RESOLVER_KEYPAIR` to the file paths.
+3. **Deploy the program.** `cd contracts/event-markets-stake && cargo build-sbf && solana program deploy target/deploy/event_markets_stake.so --program-id target/deploy/event_markets_stake-keypair.json --url mainnet-beta` (devnet first with `--url devnet`). Set `EVENT_MARKETS_STAKE_PROGRAM_ID`.
+4. **Apply the migration.** `npm run db:status` then `npm run db:migrate` (20261013000000).
+5. **Initialize the config.** `node --env-file=.env scripts/event-markets-stake-admin.mjs init --treasury <wallet> --buyback <wallet> --yes`
+6. **Create a pool for a market.** `... create-pool --market <slug> --token usdc --yes`
+7. **Enable the flag.** `gcloud run services update three-ws-api --region us-central1 --update-env-vars EVENT_MARKETS_STAKING_ENABLED=1,EVENT_MARKETS_STAKE_CLUSTER=mainnet`
+8. **After a market resolves:** `... resolve --market <slug> --yes` (or `void` if nobody picked the winner).
diff --git a/marketing/motion-studio/assets/screens/manifest.json b/marketing/motion-studio/assets/screens/manifest.json
new file mode 100644
index 000000000..4bed2e10b
--- /dev/null
+++ b/marketing/motion-studio/assets/screens/manifest.json
@@ -0,0 +1,47 @@
+{
+ "capturedAt": "2026-10-10T22:32:25.937Z",
+ "origin": "https://three.ws",
+ "viewport": "1920x1080",
+ "shots": [
+ {
+ "id": "home",
+ "url": "https://three.ws/",
+ "status": 200,
+ "title": "three.ws - The 3D Agent Layer of the Internet",
+ "file": "marketing/motion-studio/assets/screens/home.png",
+ "pageErrors": []
+ },
+ {
+ "id": "forge",
+ "url": "https://three.ws/forge",
+ "status": 200,
+ "title": "Forge · Text & Image → 3D · three.ws",
+ "file": "marketing/motion-studio/assets/screens/forge.png",
+ "pageErrors": []
+ },
+ {
+ "id": "characters",
+ "url": "https://three.ws/characters",
+ "status": 200,
+ "title": "Characters - three.ws",
+ "file": "marketing/motion-studio/assets/screens/characters.png",
+ "pageErrors": []
+ },
+ {
+ "id": "marketplace",
+ "url": "https://three.ws/marketplace",
+ "status": 200,
+ "title": "Agent Marketplace · three.ws",
+ "file": "marketing/motion-studio/assets/screens/marketplace.png",
+ "pageErrors": []
+ },
+ {
+ "id": "atlas",
+ "url": "https://three.ws/atlas",
+ "status": 200,
+ "title": "Atlas · three.ws",
+ "file": "marketing/motion-studio/assets/screens/atlas.png",
+ "pageErrors": []
+ }
+ ]
+}
diff --git a/pages/event-markets-staking-admin.html b/pages/event-markets-staking-admin.html
new file mode 100644
index 000000000..14e60783b
--- /dev/null
+++ b/pages/event-markets-staking-admin.html
@@ -0,0 +1,157 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot: no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <meta name="robots" content="noindex" />
+ <title>Staking reconciliation · Event Markets · three.ws</title>
+ <meta name="description" content="Admin view of every staked pool: vault balance against on-chain totals and recorded stakes, plus the instant stake kill switch." />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/mobile.css" />
+ <style>
+ * { box-sizing: border-box; }
+ html, body { margin: 0; background: var(--bg-0); color: var(--ink); }
+ body { font-family: var(--font-body, 'Inter', system-ui, sans-serif); min-height: 100vh; }
+ .emq { max-width: 880px; margin: 0 auto; padding: 44px 18px 96px; }
+ .emq h1 { font-size: clamp(1.6rem, 4.5vw, 2.3rem); margin: 0 0 8px; letter-spacing: -0.03em; color: var(--ink-bright, var(--ink)); }
+ .emq-lede { margin: 0 0 20px; color: var(--ink-dim); line-height: 1.55; max-width: 62ch; }
+ .emq-flag { border: 1px solid var(--stroke-strong); border-radius: 10px; padding: 10px 14px; margin: 0 0 18px; font-size: 0.9rem; color: var(--ink-dim); }
+ .emq-flag[data-on="true"] { border-color: var(--accent); color: var(--ink); }
+ .emq-bar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin: 0 0 16px; }
+ .emq-tab, .emq-btn { font: inherit; font-size: 0.88rem; font-weight: 600; padding: 8px 14px; border-radius: 10px; border: 1px solid var(--stroke-strong); background: transparent; color: var(--ink); cursor: pointer; transition: background 140ms ease, border-color 140ms ease; }
+ .emq-tab:hover, .emq-btn:hover { background: var(--surface-2, rgba(255,255,255,0.06)); }
+ .emq-tab:active, .emq-btn:active { transform: translateY(1px); }
+ .emq-tab:focus-visible, .emq-btn:focus-visible, .emq textarea:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .emq-tab[aria-selected="true"] { border-color: var(--accent); color: var(--accent); }
+ .emq-btn[data-primary] { background: var(--accent); border-color: var(--accent); color: var(--accent-ink, #000); }
+ .emq-btn[disabled] { opacity: 0.45; cursor: not-allowed; }
+ .emq-spacer { flex: 1; }
+ .emq-card { border: 1px solid var(--stroke-strong); border-radius: 14px; background: var(--surface-2, rgba(255,255,255,0.04)); padding: 16px; margin: 0 0 12px; }
+ .emq-head { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin: 0 0 10px; font-size: 0.82rem; color: var(--ink-dim); }
+ .emq-head a { color: var(--accent); text-decoration: none; font-weight: 600; }
+ .emq-head a:hover { text-decoration: underline; }
+ .emq-kind { text-transform: uppercase; letter-spacing: 0.07em; font-weight: 650; font-size: 0.72rem; }
+ .emq-text { white-space: pre-wrap; word-break: break-word; line-height: 1.5; margin: 0 0 10px; }
+ .emq textarea { width: 100%; min-height: 120px; font: inherit; color: var(--ink); background: var(--bg-0); border: 1px solid var(--stroke-strong); border-radius: 10px; padding: 10px; resize: vertical; }
+ .emq-meta { font-size: 0.8rem; color: var(--ink-dim); margin: 0 0 10px; }
+ .emq-actions { display: flex; flex-wrap: wrap; gap: 8px; }
+ .emq-note { margin: 10px 0 0; padding: 10px 12px; border-radius: 10px; border: 1px dashed var(--stroke-strong); font-size: 0.85rem; white-space: pre-wrap; word-break: break-word; }
+ .emq-note[data-error] { border-color: #d9534f; }
+ .emq-empty { border: 1px dashed var(--stroke-strong); border-radius: 14px; padding: 28px; text-align: center; color: var(--ink-dim); line-height: 1.6; }
+ .emq-skel { height: 118px; border-radius: 14px; margin: 0 0 12px; background: linear-gradient(90deg, var(--surface-2, rgba(255,255,255,0.04)), var(--stroke-strong), var(--surface-2, rgba(255,255,255,0.04))); background-size: 200% 100%; animation: emq-shimmer 1.4s linear infinite; }
+ @keyframes emq-shimmer { to { background-position: -200% 0; } }
+ @media (prefers-reduced-motion: reduce) { .emq-skel { animation: none; } }
+ .emq-kv { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 6px 16px; margin: 8px 0 0; font-size: 0.84rem; }
+ .emq-kv dt { color: var(--ink-dim); } .emq-kv dd { margin: 0 0 6px; font-variant-numeric: tabular-nums; word-break: break-all; }
+ .emq-status { font-weight: 700; } .emq-status[data-ok="false"] { color: #d9534f; }
+ </style>
+</head>
+<body>
+ <script src="/nav.js"></script>
+ <main class="emq">
+ <h1>Staking reconciliation</h1>
+ <p class="emq-lede">Each pool's vault balance against the program's totals and the stakes this site recorded. The kill switch stops new stakes instantly. Claims and refunds are never blocked.</p>
+ <div class="emq-flag" id="flag" role="status"></div>
+ <div class="emq-bar">
+ <button class="emq-btn" id="refresh" type="button">Reconcile now</button>
+ <span class="emq-spacer"></span>
+ <button class="emq-btn" data-primary id="toggle" type="button" disabled>Pause new stakes</button>
+ </div>
+ <div id="list" aria-live="polite"></div>
+ </main>
+ <script type="module">
+ const state = { csrf: null, data: null };
+ const $ = (id) => document.getElementById(id);
+ const el = (tag, props = {}, ...kids) => { const n = Object.assign(document.createElement(tag), props); for (const k of kids) n.append(k); return n; };
+ const unwrap = async (r) => {
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j.error_description || j.message || `request failed (${r.status})`);
+ return j.data || j;
+ };
+ async function csrf() {
+ if (state.csrf) return state.csrf;
+ const j = await fetch('/api/csrf-token', { credentials: 'include' }).then((r) => r.json()).catch(() => ({}));
+ state.csrf = j.data?.token || j.token || null;
+ return state.csrf;
+ }
+ function problemText(p) {
+ const map = {
+ vault_short: 'Vault holds less than the program owes. Pause stakes and investigate.',
+ vault_surplus: 'Vault holds more than expected (tokens sent outside the program).',
+ ledger_stake_mismatch: 'Recorded stakes differ from on-chain total.',
+ ledger_payout_mismatch: 'Recorded payouts differ from on-chain paid out.',
+ pool_missing_on_chain: 'Pool account not found on chain.',
+ chain_unreachable: 'RPC unreachable',
+ };
+ return `${map[p.code] || p.code}${p.delta ? ` (delta ${p.delta})` : ''}${p.message ? `: ${p.message}` : ''}`;
+ }
+ function card(p) {
+ const c = el('article', { className: 'emq-card' });
+ const head = el('div', { className: 'emq-head' });
+ head.append(p.slug ? el('a', { href: `/event-markets/${encodeURIComponent(p.slug)}`, textContent: p.title || p.slug }) : el('span', { textContent: p.market_id }));
+ head.append(el('span', { className: 'emq-kind', textContent: `${p.token} on ${p.cluster}` }));
+ head.append(el('span', { textContent: `db ${p.status} / chain ${p.chain_status || 'unknown'}` }));
+ const s = el('span', { className: 'emq-status', textContent: p.ok ? 'Balanced' : 'Needs attention' });
+ s.dataset.ok = String(!!p.ok);
+ head.append(s);
+ c.append(head);
+ if (p.expected_vault !== undefined) {
+ const kv = el('dl', { className: 'emq-kv' });
+ for (const [k, v] of [['Vault', p.vault], ['Expected vault', p.expected_vault], ['Chain staked', p.chain_total_staked], ['Ledger staked', p.ledger_staked], ['Chain paid out', p.chain_paid_out], ['Ledger paid out', p.ledger_paid_out], ['Pool', p.pool_address]]) {
+ kv.append(el('dt', { textContent: k }), el('dd', { textContent: v }));
+ }
+ c.append(kv);
+ }
+ for (const pr of p.problems || []) {
+ const n = el('p', { className: 'emq-note', textContent: problemText(pr) });
+ n.setAttribute('data-error', ''); n.setAttribute('role', 'alert');
+ c.append(n);
+ }
+ return c;
+ }
+ function render() {
+ const d = state.data;
+ $('flag').dataset.on = String(d.stakes_enabled && d.flag_enabled);
+ $('flag').textContent = `Feature flag ${d.flag_enabled ? 'on' : 'off'} · cluster ${d.cluster} · new stakes ${d.stakes_enabled ? 'allowed' : 'PAUSED (kill switch)'}${d.onchain_paused ? ' · program also paused on chain' : ''}`;
+ const t = $('toggle');
+ t.disabled = false;
+ t.textContent = d.stakes_enabled ? 'Pause new stakes' : 'Resume new stakes';
+ const list = $('list');
+ if (!d.pools.length) {
+ list.replaceChildren(el('div', { className: 'emq-empty', textContent: 'No staked pools yet. A pool appears here once the owner creates one with scripts/event-markets-stake-admin.mjs create-pool.' }));
+ return;
+ }
+ list.replaceChildren(...d.pools.map(card));
+ }
+ async function load() {
+ $('list').replaceChildren(el('div', { className: 'emq-skel' }), el('div', { className: 'emq-skel' }));
+ try {
+ state.data = await unwrap(await fetch('/api/event-markets/staking-admin', { credentials: 'include' }));
+ render();
+ } catch (err) {
+ const box = el('div', { className: 'emq-empty', textContent: `Could not load: ${err.message}. Sign in as an admin and reload.` });
+ box.setAttribute('role', 'alert');
+ $('list').replaceChildren(box);
+ }
+ }
+ $('refresh').onclick = load;
+ $('toggle').onclick = async () => {
+ const t = $('toggle'); t.disabled = true;
+ try {
+ const token = await csrf();
+ await unwrap(await fetch('/api/event-markets/staking-admin', {
+ method: 'POST', credentials: 'include',
+ headers: { 'content-type': 'application/json', ...(token ? { 'x-csrf-token': token } : {}) },
+ body: JSON.stringify({ action: state.data.stakes_enabled ? 'pause' : 'resume' }),
+ }));
+ await load();
+ } catch (err) { t.disabled = false; $('flag').textContent = `Switch failed: ${err.message}`; }
+ };
+ load();
+ </script>
+</body>
+</html>
diff --git a/scripts/event-markets-stake-admin.mjs b/scripts/event-markets-stake-admin.mjs
new file mode 100644
index 000000000..68581eb77
--- /dev/null
+++ b/scripts/event-markets-stake-admin.mjs
@@ -0,0 +1,181 @@
+#!/usr/bin/env node
+// Owner-gated admin for staked Event Markets. Every command that sends a
+// transaction prints a confirmation table (cluster, program, signer, recipient,
+// amount, token) and DOES NOTHING until re-run with --yes. On mainnet it also
+// needs --confirm-mainnet. Keys are read from keypair files named in the env and
+// are never printed. Run with the production env loaded, e.g.
+// node --env-file=.env scripts/event-markets-stake-admin.mjs <command> [flags]
+//
+// init --treasury <owner> --buyback <owner> [--fee-bps 300 --buyback-share-bps 5000]
+// create-pool --market <slug|id> --token usdc|three [--lock-grace-seconds 0]
+// resolve --market <slug|id> (winner comes from the resolved market row)
+// void --market <slug|id> (resolver void: everyone refunded)
+// pause | resume (on-chain config pause: blocks new pools and stakes)
+// status read-only: the config and every pool
+//
+// Env: EVENT_MARKETS_STAKE_PROGRAM_ID, EVENT_MARKETS_STAKE_CLUSTER,
+// EVENT_MARKETS_STAKE_AUTHORITY_KEYPAIR, EVENT_MARKETS_STAKE_RESOLVER_KEYPAIR (file paths).
+// Guide: docs/event-markets-staking.md.
+
+import { readFileSync } from 'node:fs';
+import { Keypair, Transaction, sendAndConfirmTransaction, PublicKey } from '@solana/web3.js';
+import { build, poolIdFor, poolPda, programId } from '../api/_lib/event-markets/staking/program.js';
+import { FEE, TOKENS, VOID_AFTER_LOCK_SECONDS, mintFor, stakingConfig } from '../api/_lib/event-markets/staking/config.js';
+import { connection, readConfig, readPool, tokenProgramFor } from '../api/_lib/event-markets/staking/chain.js';
+import { getPoolByMarket, insertPool, listPools, markPoolStatus } from '../api/_lib/event-markets/staking/store.js';
+import { formatAmount } from '../api/_lib/event-markets/staking/limits.js';
+import { getMarket } from '../api/_lib/event-markets/index.js';
+
+const [cmd, ...rest] = process.argv.slice(2);
+const flag = (name, dflt = null) => {
+ const i = rest.indexOf(`--${name}`);
+ return i !== -1 && rest[i + 1] && !rest[i + 1].startsWith('--') ? rest[i + 1] : dflt;
+};
+const has = (name) => rest.includes(`--${name}`);
+const die = (msg) => { console.error(`error: ${msg}`); process.exit(1); };
+
+function key(envName) {
+ const f = process.env[envName];
+ if (!f) die(`${envName} must point at a keypair file`);
+ return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(f, 'utf8'))));
+}
+
+/** Prints the table and returns true only when the owner passed --yes (and --confirm-mainnet on mainnet). */
+function gate(title, rows) {
+ const cfg = stakingConfig();
+ console.log(`\n${title}`);
+ console.table([{ field: 'chain', value: `solana (${cfg.cluster})` }, { field: 'program', value: programId().toBase58() }, ...rows.map(([field, value]) => ({ field, value: String(value) }))]);
+ if (!has('yes')) { console.log('Dry run. Re-run with --yes to sign and send.'); return false; }
+ if (cfg.cluster === 'mainnet' && !has('confirm-mainnet')) { console.log('Mainnet needs --confirm-mainnet as well. Nothing sent.'); return false; }
+ return true;
+}
+
+async function send(ixs, signer) {
+ const sig = await sendAndConfirmTransaction(connection(), new Transaction().add(...ixs), [signer], { commitment: 'confirmed' });
+ console.log(`sent ${sig}`);
+ return sig;
+}
+
+async function marketOrDie() {
+ const ref = flag('market');
+ if (!ref) die('--market <slug|id> is required');
+ return getMarket(ref, { includeDraft: true }).catch(() => die(`no market ${ref}`));
+}
+
+const commands = {
+ async init() {
+ const authority = key('EVENT_MARKETS_STAKE_AUTHORITY_KEYPAIR');
+ const resolver = key('EVENT_MARKETS_STAKE_RESOLVER_KEYPAIR');
+ const treasury = flag('treasury') || die('--treasury <owner pubkey> is required');
+ const buyback = flag('buyback') || die('--buyback <owner pubkey> is required');
+ const feeBps = Number(flag('fee-bps', FEE.feeBps));
+ const share = Number(flag('buyback-share-bps', FEE.buybackShareBps));
+ if (!gate('Initialize the staking program config', [
+ ['signer (authority)', authority.publicKey.toBase58()], ['resolver', resolver.publicKey.toBase58()],
+ ['treasury recipient', treasury], ['buyback recipient', buyback], ['fee', `${feeBps / 100}% of each pool`], ['buyback share of fee', `${share / 100}%`],
+ ])) return;
+ await send([build.initialize(programId(), { authority: authority.publicKey, resolver: resolver.publicKey, treasury, buyback, feeBps, buybackShareBps: share })], authority);
+ },
+
+ async 'create-pool'() {
+ const resolver = key('EVENT_MARKETS_STAKE_RESOLVER_KEYPAIR');
+ const market = await marketOrDie();
+ const tokenKey = flag('token') || die('--token usdc|three is required');
+ const token = TOKENS[tokenKey] || die(`unknown token ${tokenKey}`);
+ if (await getPoolByMarket(market.id)) die('this market already has a pool');
+ const cfg = stakingConfig();
+ const mint = mintFor(tokenKey, cfg.cluster);
+ const lockTs = Math.floor(new Date(market.locks_at).getTime() / 1000);
+ const voidAfterTs = lockTs + VOID_AFTER_LOCK_SECONDS;
+ if (lockTs * 1000 <= Date.now()) die('the market has already locked');
+ const poolId = poolIdFor(market.id);
+ const outcomeIds = market.outcomes.map((o) => o.outcome_id ?? o.id);
+ const config = await readConfig() || die('program config not initialized; run init first');
+ if (!gate(`Create a staked pool for "${market.title}"`, [
+ ['signer (resolver)', resolver.publicKey.toBase58()], ['token', `${token.symbol} (${mint})`], ['outcomes', outcomeIds.length],
+ ['min / max stake', `${formatAmount(token.min, token.decimals)} / ${formatAmount(token.maxStake, token.decimals)} ${token.symbol}`],
+ ['pool cap', `${formatAmount(token.maxPool, token.decimals)} ${token.symbol}`], ['locks', new Date(lockTs * 1000).toISOString()],
+ ['auto-void after', new Date(voidAfterTs * 1000).toISOString()], ['fee', `${config.feeBps / 100}% (buyback share ${config.buybackShareBps / 100}%)`],
+ ['fee recipients', `treasury ${config.treasury.toBase58()}, buyback ${config.buyback.toBase58()}`], ['funds moved', 'none (rent for the pool and vault accounts only)'],
+ ])) return;
+ const tokenProgram = await tokenProgramFor(mint);
+ const sig = await send([build.createPool(programId(), {
+ resolver: resolver.publicKey, poolId, mint, outcomeCount: outcomeIds.length, minStake: token.min, maxStake: token.maxStake,
+ maxPool: token.maxPool, lockTs, voidAfterTs, tokenProgram,
+ })], resolver);
+ await insertPool({
+ marketId: market.id, cluster: cfg.cluster, programId: programId().toBase58(), poolIdHex: poolId.toString('hex'),
+ poolAddress: poolPda(programId(), poolId).toBase58(), mint, tokenKey, decimals: token.decimals, outcomeIds,
+ minStake: token.min, maxStake: token.maxStake, maxPool: token.maxPool, feeBps: config.feeBps, buybackShareBps: config.buybackShareBps,
+ lockAt: new Date(lockTs * 1000), voidAfter: new Date(voidAfterTs * 1000), createSignature: sig,
+ });
+ console.log('pool recorded');
+ },
+
+ async resolve() {
+ const resolver = key('EVENT_MARKETS_STAKE_RESOLVER_KEYPAIR');
+ const market = await marketOrDie();
+ if (market.status !== 'resolved' || !market.winner) die(`market is ${market.status}; resolve it in the platform first, the on-chain winner is read from it`);
+ const pool = await getPoolByMarket(market.id) || die('this market has no staked pool');
+ const winning = pool.outcomeIds.indexOf(market.winner.outcome_id);
+ if (winning < 0) die('market winner is not in the pool outcome list');
+ const chain = await readPool(pool.poolIdHex) || die('pool not found on chain');
+ if (chain.statusName !== 'open') die(`pool is already ${chain.statusName}`);
+ const config = await readConfig();
+ const token = TOKENS[pool.tokenKey];
+ const fee = (chain.totalStaked * BigInt(chain.feeBps)) / 10_000n;
+ const buyback = (fee * BigInt(chain.buybackShareBps)) / 10_000n;
+ const winningTotal = chain.totals[winning];
+ const nobody = winningTotal === 0n;
+ if (!gate(`Resolve the pool for "${market.title}"`, [
+ ['signer (resolver)', resolver.publicKey.toBase58()], ['winner', `${market.winner.label} (outcome ${winning})`], ['token', `${token.symbol} (${pool.mint})`],
+ ['pool total', `${formatAmount(chain.totalStaked, pool.decimals)} ${token.symbol}`], ['fee moves out', `${formatAmount(fee, pool.decimals)} ${token.symbol}`],
+ ['to treasury', `${formatAmount(fee - buyback, pool.decimals)} -> ${config.treasury.toBase58()}`], ['to buyback', `${formatAmount(buyback, pool.decimals)} -> ${config.buyback.toBase58()}`],
+ ['result', nobody ? 'NOBODY PICKED THE WINNER: use the void command instead, everyone is refunded' : 'winners claim their own payouts'],
+ ])) return;
+ if (nobody) die('nobody staked on the winner; run void so every staker is refunded');
+ const sig = await send([build.resolve(programId(), {
+ resolver: resolver.publicKey, poolId: Buffer.from(pool.poolIdHex, 'hex'), mint: pool.mint, winningOutcome: winning,
+ treasuryOwner: config.treasury, buybackOwner: config.buyback, tokenProgram: await tokenProgramFor(pool.mint),
+ })], resolver);
+ await markPoolStatus(market.id, 'resolved', sig);
+ },
+
+ async void() {
+ const resolver = key('EVENT_MARKETS_STAKE_RESOLVER_KEYPAIR');
+ const market = await marketOrDie();
+ const pool = await getPoolByMarket(market.id) || die('this market has no staked pool');
+ const chain = await readPool(pool.poolIdHex) || die('pool not found on chain');
+ if (chain.statusName !== 'open') die(`pool is already ${chain.statusName}`);
+ if (!gate(`Void the pool for "${market.title}"`, [
+ ['signer (resolver)', resolver.publicKey.toBase58()], ['token', `${TOKENS[pool.tokenKey].symbol} (${pool.mint})`],
+ ['pool total', `${formatAmount(chain.totalStaked, pool.decimals)} ${TOKENS[pool.tokenKey].symbol}`], ['result', 'every staker may refund their full stake; no fee is taken'],
+ ])) return;
+ const sig = await send([build.voidPool(programId(), { resolver: resolver.publicKey, poolId: Buffer.from(pool.poolIdHex, 'hex') })], resolver);
+ await markPoolStatus(market.id, 'void', sig);
+ },
+
+ async pause() { await setPaused(true); },
+ async resume() { await setPaused(false); },
+
+ async status() {
+ const config = await readConfig();
+ console.log(config ? { authority: config.authority.toBase58(), resolver: config.resolver.toBase58(), treasury: config.treasury.toBase58(), buyback: config.buyback.toBase58(), feeBps: config.feeBps, buybackShareBps: config.buybackShareBps, paused: config.paused } : 'config not initialized');
+ for (const p of await listPools()) {
+ const c = await readPool(p.poolIdHex);
+ console.log(p.marketId, p.tokenKey, c ? `${c.statusName} staked=${c.totalStaked}` : 'missing on chain');
+ }
+ },
+};
+
+async function setPaused(paused) {
+ const authority = key('EVENT_MARKETS_STAKE_AUTHORITY_KEYPAIR');
+ if (!gate(`${paused ? 'Pause' : 'Resume'} the program (new pools and stakes)`, [
+ ['signer (authority)', authority.publicKey.toBase58()], ['effect', paused ? 'create_pool and stake fail on chain; claims and refunds keep working' : 'new pools and stakes allowed again'],
+ ])) return;
+ await send([build.setConfig(programId(), { authority: authority.publicKey, paused })], authority);
+}
+
+if (!commands[cmd]) die(`usage: ${Object.keys(commands).join(' | ')} [flags]; see the header of this file`);
+await commands[cmd]();
+process.exit(0);
diff --git a/src/event-markets/event-markets.css b/src/event-markets/event-markets.css
index 8a2f95618..ce5185f55 100644
--- a/src/event-markets/event-markets.css
+++ b/src/event-markets/event-markets.css
@@ -41,7 +41,7 @@
.em-card:active { transform: translateY(0); }
.em-card h3 { font-size: var(--text-lg); line-height: 1.2; overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.em-meta { display: flex; justify-content: space-between; gap: .5rem; align-items: center; font-size: var(--text-sm); color: var(--ink-dim); }
-.em-pill { display: inline-flex; align-items: center; gap: .3rem; padding: .15rem .55rem; border-radius: var(--radius-pill); border: 1px solid var(--stroke); font-size: var(--text-sm); font-weight: var(--weight-semibold); }
+.em-pill { white-space: nowrap; display: inline-flex; align-items: center; gap: .3rem; padding: .15rem .55rem; border-radius: var(--radius-pill); border: 1px solid var(--stroke); font-size: var(--text-sm); font-weight: var(--weight-semibold); }
.em-pill.open { color: var(--success); border-color: color-mix(in srgb, var(--success) 45%, transparent); }
.em-pill.locked { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 45%, transparent); }
.em-pill.resolved { color: var(--accent-violet); border-color: color-mix(in srgb, var(--accent-violet) 45%, transparent); }
@@ -95,9 +95,9 @@
.em-more { margin-top: .75rem; }
/* pick dialog */
-.em-dialog { border: 1px solid var(--stroke-strong); background: var(--surface-1, var(--stage)); color: var(--ink); border-radius: var(--radius-lg); padding: 1.25rem; max-width: min(26rem, calc(100vw - 2rem)); width: 100%; }
-.em-dialog::backdrop { background: var(--scrim-modal); }
-.em-dialog h2 { font-size: var(--text-lg); margin-bottom: .5rem; }
+.em-dialog { position: fixed; inset: 0; margin: auto; height: fit-content; max-height: calc(100dvh - 2rem); overflow: auto; font-family: var(--font-body); border: 1px solid var(--stroke-strong); background: var(--bg, var(--stage-lift)); color: var(--ink); border-radius: var(--radius-lg); padding: 1.25rem; max-width: none; width: min(26rem, calc(100vw - 2rem)); box-sizing: border-box; }
+.em-dialog::backdrop { background: rgba(0, 0, 0, 0.6); }
+.em-dialog h2 { font-family: var(--font-display); color: var(--ink-bright); font-size: var(--text-lg); margin-bottom: .5rem; }
.em-dialog p { color: var(--ink-dim); line-height: 1.5; margin: 0 0 .9rem; }
.em-dialog label { display: block; font-size: var(--text-sm); color: var(--ink-dim); margin-bottom: .3rem; }
.em-dialog input[type=range] { width: 100%; }
@@ -123,7 +123,7 @@
/* share */
.em-share { display: flex; flex-wrap: wrap; gap: .5rem; }
-.em-toast { position: fixed; left: 50%; bottom: 1.5rem; transform: translateX(-50%); background: var(--ink-bright); color: var(--on-bright); padding: .6rem 1rem; border-radius: var(--radius-md); font-weight: var(--weight-semibold); z-index: 50; max-width: calc(100vw - 2rem); }
+.em-toast { position: fixed; font-family: var(--font-body); left: 50%; bottom: 1.5rem; transform: translateX(-50%); background: var(--ink-bright); color: var(--on-bright); padding: .6rem 1rem; border-radius: var(--radius-md); font-weight: var(--weight-semibold); z-index: 50; max-width: calc(100vw - 2rem); }
.em-challenge { border-color: var(--accent); }
@media (prefers-reduced-motion: reduce) { .em *, .em-skel { animation: none !important; transition: none !important; } }
@@ -147,7 +147,8 @@
.em-tk-tag { display: inline-flex; align-items: center; gap: .4rem; font-weight: var(--weight-semibold); color: var(--ink-bright); flex: none; }
.em-tk-tag .dot { width: .5rem; height: .5rem; border-radius: 50%; background: var(--success); }
.em-tk-view { overflow: hidden; flex: 1 1 auto; min-width: 0; mask-image: linear-gradient(90deg, transparent, #000 1.5rem, #000 calc(100% - 1.5rem), transparent); }
-.em-tk-list { display: inline-flex; gap: 2rem; margin: 0; padding: 0; list-style: none; white-space: nowrap; animation: em-tk-scroll 40s linear infinite; }
+.em-tk-list { display: inline-flex; gap: 2rem; margin: 0; padding: 0; list-style: none; white-space: nowrap; }
+.em-tk-list[data-scroll='true'] { animation: em-tk-scroll 40s linear infinite; }
.em-tk-list[data-paused='true'] { animation-play-state: paused; }
.em-tk-list:hover { animation-play-state: paused; }
.em-tk-item a { text-decoration: none; color: inherit; border-radius: var(--radius-sm); }
@@ -225,3 +226,12 @@
.em-auto fieldset { border: 1px solid var(--stroke); border-radius: var(--radius-md); display: flex; flex-wrap: wrap; gap: .4rem 1rem; padding: .6rem .8rem; }
.em-check { display: inline-flex; align-items: center; gap: .45rem; }
.em-auto-nums { display: flex; flex-wrap: wrap; gap: .8rem; } .em-auto-nums label { display: flex; flex-direction: column; gap: .25rem; font-size: var(--text-sm); }
+
+/* ── staked markets panel ── */
+.em-stake-kv { display: grid; grid-template-columns: max-content 1fr; gap: .25rem .9rem; margin: .8rem 0; font-size: var(--text-sm); }
+.em-stake-kv dt { color: var(--ink-dim); }
+.em-stake-kv dd { margin: 0; word-break: break-all; font-variant-numeric: tabular-nums; color: var(--ink-bright); }
+[data-staking] select, [data-staking] input[type=text] { width: 100%; box-sizing: border-box; margin: .25rem 0 .7rem; padding: .55rem .7rem; font: inherit; color: var(--ink); background: transparent; border: 1px solid var(--stroke-strong); border-radius: var(--radius-md, 10px); }
+[data-staking] select:focus-visible, [data-staking] input:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+[data-staking] .row { display: flex; gap: .5rem; flex-wrap: wrap; justify-content: flex-end; }
+[data-staking] .em-check { display: flex; gap: .5rem; align-items: center; margin: .4rem 0; }
diff --git a/src/event-markets/market.js b/src/event-markets/market.js
index d10028b7c..2d4e1bfa9 100644
--- a/src/event-markets/market.js
+++ b/src/event-markets/market.js
@@ -3,6 +3,7 @@
import { attachLiveOdds } from './market-live.js';
import { h, api, ApiError, SOURCE_LABELS, seriesColor, pct, countdown, when, initials, profileHref, statusLabel } from './common.js';
import { agentsPanel } from './forecasting.js';
+import { stakingPanel } from './staking-panel.js';
const root = document.getElementById('em-root');
const live = document.getElementById('em-live');
@@ -175,7 +176,14 @@ function rulePanel(m) {
return h('section', { class: 'em-panel', 'aria-labelledby': 'em-h-rule' },
h('h2', { id: 'em-h-rule' }, 'How it resolves'),
h('p', { class: 'em-rule' }, m.resolution_text),
- h('p', { class: 'em-note' }, 'Picks are free-to-play points. Nothing is staked and no funds move. Implied odds are the share of crowd points on each entrant.'));
+ h('p', { class: 'em-note' }, 'Picks are free-to-play points. Free picks never move funds. Where staking is offered it is a separate panel and never changes these standings. Implied odds are the share of crowd points on each entrant.'));
+}
+
+function stakeSlot() {
+ S.staking ??= stakingPanel({
+ slug, getMarket: () => S.market, signedIn: () => S.viewer !== null, requireSignIn: ensureSignedIn, toast, announce,
+ });
+ return S.staking.el;
}
function sharePanel(m) {
@@ -315,7 +323,7 @@ function render() {
...banners(m),
h('div', { class: 'em-layout' },
h('div', null, entrantsPanel(m), chartPanel(m)),
- h('div', null, clockPanel(m), rulePanel(m), S.agents ??= agentsPanel(slug), sharePanel(m))));
+ h('div', null, clockPanel(m), stakeSlot(), rulePanel(m), S.agents ??= agentsPanel(slug), sharePanel(m))));
root.removeAttribute('aria-busy');
if (focus) [...root.querySelectorAll('.em-ent')].find((e) => e.querySelector('.nm')?.textContent === focus)?.querySelector('button')?.focus();
startClock();
diff --git a/src/event-markets/staking-panel.js b/src/event-markets/staking-panel.js
new file mode 100644
index 000000000..afe83d121
--- /dev/null
+++ b/src/event-markets/staking-panel.js
@@ -0,0 +1,172 @@
+// Stake panel for /event-markets/:slug, shown next to the free pick ONLY when the
+// server says staking is offered and the viewer's region and age gate is open.
+// Everyone else sees the free-to-play market exactly as before.
+//
+// The server builds an UNSIGNED transaction plus the preview; the wallet signs it
+// here, after an explicit confirm that restates recipient, amount, token and chain.
+// Nothing is sent without that click. Staked standings are never merged with the
+// free-to-play leaderboard. Guide: docs/event-markets-staking.md.
+
+import { api, h, pct, when } from './common.js';
+
+const PROVIDERS = [
+ { name: 'Phantom', detect: () => window.phantom?.solana || (window.solana?.isPhantom && window.solana) },
+ { name: 'Solflare', detect: () => window.solflare },
+ { name: 'Backpack', detect: () => window.backpack?.solana || (window.solana?.isBackpack && window.solana) },
+];
+
+const b64ToBytes = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
+
+/** "12.5" -> 12500000n for a token with `decimals`. Returns null when the text is not a valid amount. */
+export function toBaseUnits(text, decimals) {
+ const m = /^(\d{1,15})(?:\.(\d{1,18}))?$/.exec(String(text).trim());
+ if (!m || (m[2] || '').length > decimals) return null;
+ return BigInt(m[1]) * 10n ** BigInt(decimals) + BigInt((m[2] || '').padEnd(decimals, '0') || '0');
+}
+
+export function fromBaseUnits(v, decimals) {
+ const s = BigInt(v).toString().padStart(decimals + 1, '0');
+ const frac = s.slice(-decimals).replace(/0+$/, '');
+ return frac ? `${s.slice(0, -decimals)}.${frac}` : s.slice(0, -decimals);
+}
+
+export function stakingPanel({ slug, getMarket, signedIn, requireSignIn, toast, announce }) {
+ const box = h('div', { 'data-staking': '' });
+ const S = { view: null, wallet: null, busy: false, outcomeId: null, amount: '', quote: null, error: '', note: '' };
+ const path = (suffix) => `/${encodeURIComponent(slug)}/staking${suffix}`;
+
+ async function load() {
+ try {
+ S.view = await api(path(S.wallet ? `?wallet=${encodeURIComponent(S.wallet.address)}` : ''));
+ } catch {
+ S.view = { offered: false };
+ }
+ draw();
+ }
+
+ async function connect() {
+ const entry = PROVIDERS.map((p) => ({ ...p, provider: p.detect() })).find((p) => p.provider);
+ if (!entry) throw new Error('No Solana wallet found. Install Phantom, Solflare or Backpack.');
+ const r = await entry.provider.connect();
+ const pk = r?.publicKey ?? entry.provider.publicKey;
+ S.wallet = { provider: entry.provider, name: entry.name, address: typeof pk === 'string' ? pk : pk.toBase58() };
+ }
+
+ async function signAndSend(base64Tx) {
+ const { Transaction } = await import('@solana/web3.js');
+ const tx = Transaction.from(b64ToBytes(base64Tx));
+ const res = await S.wallet.provider.signAndSendTransaction(tx);
+ return res?.signature ?? res;
+ }
+
+ async function guard(fn) {
+ S.busy = true; S.error = ''; draw();
+ try { await fn(); }
+ catch (err) { S.error = err?.message || 'Something went wrong. Nothing was sent.'; }
+ S.busy = false; draw();
+ }
+
+ const attest = (age, region) => guard(async () => {
+ if (!signedIn() && !(await requireSignIn())) return;
+ await api(path('/attest'), { method: 'POST', body: { confirmed_age: age, confirmed_region: region } });
+ await load();
+ });
+
+ const quote = () => guard(async () => {
+ if (!signedIn() && !(await requireSignIn())) return;
+ if (!S.wallet) await connect();
+ const units = toBaseUnits(S.amount, S.view.token.decimals);
+ if (!S.outcomeId) throw new Error('Choose who you think wins.');
+ if (units == null || units === 0n) throw new Error(`Enter an amount in ${S.view.token.symbol} with at most ${S.view.token.decimals} decimals.`);
+ S.quote = await api(path('/stake'), { method: 'POST', body: { wallet: S.wallet.address, outcome_id: S.outcomeId, amount: units.toString() } });
+ });
+
+ const confirmStake = () => guard(async () => {
+ const q = S.quote;
+ const signature = await signAndSend(q.transaction);
+ await api(path('/record'), { method: 'POST', body: { signature } });
+ S.quote = null; S.amount = '';
+ S.note = `Stake sent: ${q.confirm.amount_display} ${q.confirm.token}. It appears in the pool once confirmed on Solana.`;
+ toast?.('Stake sent');
+ announce?.(S.note);
+ await load();
+ });
+
+ const payout = (kind) => guard(async () => {
+ if (!S.wallet) await connect();
+ const built = await api(path('/payout'), { method: 'POST', body: { wallet: S.wallet.address, kind } });
+ const signature = await signAndSend(built.transaction);
+ await api(path('/record'), { method: 'POST', body: { signature } });
+ S.note = kind === 'claim' ? 'Winnings claimed to your wallet.' : 'Refund sent to your wallet.';
+ toast?.(S.note);
+ await load();
+ });
+
+ function quoteTable(q) {
+ const rows = [
+ ['Chain', `Solana (${q.confirm.cluster})`], ['Token', `${q.confirm.token}`], ['You stake', `${q.confirm.amount_display} ${q.confirm.token}`],
+ ['Pool', q.confirm.pool_address], ['Your wallet', q.confirm.wallet],
+ ['Pool after your stake', `${fromBaseUnits(q.preview.pool_after, S.view.token.decimals)} ${q.confirm.token}`],
+ ['Fee if it resolves', `${fromBaseUnits(q.preview.fee_if_resolved, S.view.token.decimals)} ${q.confirm.token} (${S.view.fee.fee_bps / 100}% of the pool)`],
+ ['Payout if you are right', `${fromBaseUnits(q.preview.payout_if_right, S.view.token.decimals)} ${q.confirm.token}`],
+ ['Profit if you are right', `${fromBaseUnits(q.preview.profit_if_right, S.view.token.decimals)} ${q.confirm.token}`],
+ ];
+ return h('dl', { class: 'em-stake-kv' }, rows.map(([k, v]) => [h('dt', null, k), h('dd', null, v)]));
+ }
+
+ function draw() {
+ const v = S.view;
+ const m = getMarket();
+ if (!v) { box.replaceChildren(h('section', { class: 'em-panel' }, h('div', { class: 'em-skel', style: 'height:8rem' }))); return; }
+ if (!v.offered || v.gate?.reason === 'disabled') { box.replaceChildren(); return; }
+ const pos = v.position;
+ const kids = [h('h2', { id: 'em-h-stake' }, `Stake ${v.token.symbol}`)];
+
+ if (pos && (pos.claimable || pos.refundable)) {
+ kids.push(
+ h('p', null, pos.claimable
+ ? `You called it. Your payout is ${fromBaseUnits(pos.payout, v.token.decimals)} ${v.token.symbol}.`
+ : `This market was voided. Your ${fromBaseUnits(pos.amount, v.token.decimals)} ${v.token.symbol} stake is refunded in full, with no fee.`),
+ h('button', { class: 'em-btn primary', type: 'button', disabled: S.busy, onclick: () => payout(pos.claimable ? 'claim' : 'refund') }, pos.claimable ? 'Claim winnings' : 'Claim refund'));
+ } else if (v.status !== 'open') {
+ kids.push(h('p', { class: 'em-note' }, v.status === 'resolved' ? 'This staked market is resolved. Winners claim from their own wallet.' : 'This staked market is closed.'));
+ } else if (!v.gate.available && !v.gate.needs_attestation) {
+ kids.push(h('p', { class: 'em-note' }, v.gate.message));
+ } else if (v.gate.needs_attestation) {
+ const age = h('input', { type: 'checkbox', id: 'em-att-age' });
+ const region = h('input', { type: 'checkbox', id: 'em-att-reg' });
+ kids.push(
+ h('p', { class: 'em-note' }, v.gate.message),
+ h('label', { for: 'em-att-age', class: 'em-check' }, age, ` I am at least ${v.gate.min_age} years old.`),
+ h('label', { for: 'em-att-reg', class: 'em-check' }, region, ' Staking real tokens is lawful where I live.'),
+ h('button', { class: 'em-btn primary', type: 'button', disabled: S.busy, onclick: () => attest(age.checked, region.checked) }, 'Confirm and continue'));
+ } else {
+ const outcomes = m.outcomes;
+ const select = h('select', { id: 'em-stake-out', 'aria-label': 'Who wins', onchange: (e) => { S.outcomeId = e.target.value; S.quote = null; } },
+ h('option', { value: '' }, 'Choose who wins'),
+ v.outcomes.map((o) => {
+ const label = outcomes.find((x) => x.id === o.outcome_id)?.label ?? 'Entrant';
+ return h('option', { value: o.outcome_id, selected: S.outcomeId === o.outcome_id }, `${label} (${pct(o.share * 100)} of the pool)`);
+ }));
+ const amount = h('input', { id: 'em-stake-amt', type: 'text', inputmode: 'decimal', autocomplete: 'off', placeholder: `${fromBaseUnits(v.limits.min, v.token.decimals)} min`, value: S.amount, oninput: (e) => { S.amount = e.target.value; S.quote = null; } });
+ kids.push(
+ h('p', { class: 'em-note' }, `Real ${v.token.symbol} on Solana (${v.cluster}). Pool of ${fromBaseUnits(v.total_staked, v.token.decimals)} ${v.token.symbol}, ${v.fee.fee_bps / 100}% fee. Min ${fromBaseUnits(v.limits.min, v.token.decimals)}, max ${fromBaseUnits(v.limits.max_stake, v.token.decimals)} per account. Locks ${when(v.lock_at)}. If the market is voided, or nobody picked the winner, every stake is refunded.`),
+ h('label', { for: 'em-stake-out' }, 'Your call'), select,
+ h('label', { for: 'em-stake-amt' }, `Amount (${v.token.symbol})`), amount,
+ S.quote ? quoteTable(S.quote) : null,
+ S.quote?.preview.note ? h('p', { class: 'em-note' }, S.quote.preview.note) : null,
+ h('div', { class: 'row' },
+ S.quote
+ ? [h('button', { class: 'em-btn', type: 'button', disabled: S.busy, onclick: () => { S.quote = null; draw(); } }, 'Edit'),
+ h('button', { class: 'em-btn primary', type: 'button', disabled: S.busy, onclick: confirmStake }, `Confirm and sign ${S.quote.confirm.amount_display} ${S.quote.confirm.token}`)]
+ : h('button', { class: 'em-btn primary', type: 'button', disabled: S.busy, onclick: quote }, S.wallet ? 'Preview stake' : 'Connect wallet and preview')),
+ pos ? h('p', { class: 'em-note' }, `Your stake: ${fromBaseUnits(pos.amount, v.token.decimals)} ${v.token.symbol}.`) : null);
+ }
+ if (S.error) kids.push(h('p', { class: 'em-err', role: 'alert' }, S.error));
+ if (S.note) kids.push(h('p', { class: 'em-note', role: 'status' }, S.note));
+ box.replaceChildren(h('section', { class: 'em-panel', 'aria-labelledby': 'em-h-stake' }, kids));
+ }
+
+ load();
+ return { el: box, reload: load };
+}
diff --git a/tests/event-markets-staking.chain.test.js b/tests/event-markets-staking.chain.test.js
index c9705ef02..e72b03ad6 100644
--- a/tests/event-markets-staking.chain.test.js
+++ b/tests/event-markets-staking.chain.test.js
@@ -160,7 +160,7 @@ d('event_markets_stake on a local validator', () => {
const p0 = await pool(poolId);
const preview = previewStake({ totals: p0.totals, feeBps: p0.feeBps, buybackShareBps: p0.buybackShareBps }, 1, 777_777n);
await stake(b, poolId, 1, 777_777n);
- await waitUntil(p0.lockTs);
+ await lockNow(poolId);
await send([build.resolve(program, { resolver: resolver.publicKey, poolId, mint, winningOutcome: 1, treasuryOwner: treasuryOwner.publicKey, buybackOwner: buybackOwner.publicKey })], [resolver]);
const stakeTotal = 2_000_003n + 777_777n;
const before = await bal(mint, b.publicKey);
@@ -216,11 +216,11 @@ d('event_markets_stake on a local validator', () => {
const [a, stranger] = await Promise.all([funded(mint, 1_000_000n), funded(mint, 0n)]);
const poolId = await newPool({ outcomes: 2, lockIn: 18, voidIn: 20 });
await stake(a, poolId, 0, 250_000n);
- expect(await fails([build.voidExpired(program, { poolId })], [stranger])).toBe('NotExpired');
+ expect(await fails([build.voidExpired(program, { poolId })], [])).toBe('NotExpired');
const p = await pool(poolId);
await waitUntil(p.voidAfterTs);
expect(await fails([build.resolve(program, { resolver: resolver.publicKey, poolId, mint, winningOutcome: 0, treasuryOwner: treasuryOwner.publicKey, buybackOwner: buybackOwner.publicKey })], [resolver])).toBe('Expired');
- await send([build.voidExpired(program, { poolId })], [stranger]);
+ await send([build.voidExpired(program, { poolId })], []);
await send([build.refund(program, { owner: a.publicKey, poolId, mint })], [a]);
expect(await bal(mint, a.publicKey)).toBe(1_000_000n);
}, 120_000);
diff --git a/tests/event-markets-staking.test.js b/tests/event-markets-staking.test.js
new file mode 100644
index 000000000..998e7aadc
--- /dev/null
+++ b/tests/event-markets-staking.test.js
@@ -0,0 +1,149 @@
+// Unit tests for the staking server modules and the stake panel's amount helpers.
+// The on-chain parity (preview equals the program to the base unit) is covered by
+// event-markets-staking.chain.test.js against a real validator.
+import { describe, it, expect, afterEach } from 'vitest';
+import { Keypair, PublicKey } from '@solana/web3.js';
+import { createHash } from 'node:crypto';
+import { splitFee, payoutFor, previewStake, poolShares } from '../api/_lib/event-markets/staking/math.js';
+import { checkStakeLimits, StakeRefusal, formatAmount } from '../api/_lib/event-markets/staking/limits.js';
+import { evaluateGate } from '../api/_lib/event-markets/staking/gate.js';
+import { reconcilePool } from '../api/_lib/event-markets/staking/reconcile.js';
+import { parseProgramTx } from '../api/_lib/event-markets/staking/record.js';
+import { TOKENS } from '../api/_lib/event-markets/staking/config.js';
+import { toBaseUnits, fromBaseUnits } from '../src/event-markets/staking-panel.js';
+
+describe('parimutuel math', () => {
+ it('floors the fee and gives the treasury the remainder', () => {
+ expect(splitFee(1_000_001n, 300, 5000)).toEqual({ fee: 30_000n, buyback: 15_000n, treasury: 15_000n });
+ expect(splitFee(3n, 300, 5000)).toEqual({ fee: 0n, buyback: 0n, treasury: 0n });
+ });
+ it('pays floor(stake * (total - fee) / winningTotal) and never more than the pool', () => {
+ const totals = [600n, 300n, 100n];
+ const total = 1000n;
+ const { fee } = splitFee(total, 300, 5000);
+ const paid = [200n, 400n].reduce((s, st) => s + payoutFor(st, total, fee, totals[0]), 0n);
+ expect(paid <= total - fee).toBe(true);
+ expect(payoutFor(0n, total, fee, 0n)).toBe(0n);
+ });
+ it('previews a refund, not a payout, when nobody is on the other side', () => {
+ const p = previewStake({ totals: [0n, 0n], feeBps: 300, buybackShareBps: 5000 }, 0, 100n);
+ expect(p).toMatchObject({ void_if_wins: true, payout: 100n, fee: 0n });
+ const q = previewStake({ totals: [0n, 50n], feeBps: 300, buybackShareBps: 5000 }, 0, 100n);
+ expect(q.void_if_wins).toBe(false);
+ expect(q.payout).toBe(payoutFor(100n, 150n, splitFee(150n, 300, 5000).fee, 100n));
+ });
+ it('rejects negative and non-integer amounts', () => {
+ expect(() => splitFee(-1n, 300, 5000)).toThrow(RangeError);
+ expect(() => previewStake({ totals: [0n, 0n], feeBps: 1, buybackShareBps: 1 }, 0, '1.5')).toThrow(RangeError);
+ });
+ it('shares are even when the pool is empty', () => {
+ expect(poolShares([0n, 0n, 0n, 0n])).toEqual([0.25, 0.25, 0.25, 0.25]);
+ });
+});
+
+describe('stake limits', () => {
+ const pool = { tokenKey: 'usdc', decimals: 6, minStake: 1_000_000n, maxStake: 100_000_000n, maxPool: 500_000_000n, totalStaked: 0n };
+ const ok = { amount: 5_000_000n, position: 0n, accountDay: 0n };
+ const code = (fn) => { try { fn(); } catch (e) { return e instanceof StakeRefusal ? e.code : e; } return null; };
+ it('accepts a stake inside every cap', () => expect(code(() => checkStakeLimits(pool, ok))).toBeNull());
+ it('refuses zero, below minimum, over account, over pool and over daily', () => {
+ expect(code(() => checkStakeLimits(pool, { ...ok, amount: 0n }))).toBe('invalid_amount');
+ expect(code(() => checkStakeLimits(pool, { ...ok, amount: 999_999n }))).toBe('below_minimum');
+ expect(code(() => checkStakeLimits(pool, { ...ok, position: 98_000_000n }))).toBe('over_account_cap');
+ expect(code(() => checkStakeLimits({ ...pool, totalStaked: 498_000_000n }, ok))).toBe('over_pool_cap');
+ expect(code(() => checkStakeLimits(pool, { ...ok, accountDay: TOKENS.usdc.dailyCap }))).toBe('over_daily_cap');
+ });
+ it('formats base units without float error', () => {
+ expect(formatAmount(1_234_500n, 6)).toBe('1.2345');
+ expect(formatAmount(5n, 6)).toBe('0.000005');
+ expect(formatAmount(2_000_000n, 6)).toBe('2');
+ });
+});
+
+describe('region and age gate', () => {
+ const saved = { ...process.env };
+ afterEach(() => { process.env = { ...saved }; });
+ const req = (country) => ({ headers: country ? { 'x-client-geo-location': country } : {} });
+ const att = { min_age: 21, country: 'DE', terms_version: '2026-10-13' };
+ const on = () => { process.env.EVENT_MARKETS_STAKING_ENABLED = '1'; };
+
+ it('is closed while the flag is off, whatever else is true', () => {
+ delete process.env.EVENT_MARKETS_STAKING_ENABLED;
+ expect(evaluateGate({ req: req('DE'), attestation: att, stakesEnabled: true })).toMatchObject({ available: false, reason: 'disabled' });
+ });
+ it('the kill switch closes it', () => {
+ on();
+ expect(evaluateGate({ req: req('DE'), attestation: att, stakesEnabled: false })).toMatchObject({ available: false, reason: 'paused' });
+ });
+ it('treats an unknown region as blocked and a blocked region as blocked', () => {
+ on();
+ expect(evaluateGate({ req: req(null), attestation: att, stakesEnabled: true }).reason).toBe('region_unknown');
+ expect(evaluateGate({ req: req('US'), attestation: att, stakesEnabled: true }).reason).toBe('region_blocked');
+ });
+ it('needs a current attestation from the same region', () => {
+ on();
+ expect(evaluateGate({ req: req('DE'), attestation: null, stakesEnabled: true })).toMatchObject({ reason: 'attestation_required', needs_attestation: true });
+ expect(evaluateGate({ req: req('DE'), attestation: { ...att, terms_version: 'old' }, stakesEnabled: true }).reason).toBe('attestation_required');
+ expect(evaluateGate({ req: req('DE'), attestation: { ...att, country: 'NL' }, stakesEnabled: true }).reason).toBe('attestation_region_changed');
+ expect(evaluateGate({ req: req('DE'), attestation: att, stakesEnabled: true })).toMatchObject({ available: true, reason: null });
+ });
+});
+
+describe('reconciliation', () => {
+ const chain = { totalStaked: 1000n, feePaid: 30n, paidOut: 400n };
+ it('balances when the vault holds what the program says', () => {
+ expect(reconcilePool({ chain, vaultBalance: 570n, ledger: { staked: 1000n, paidOut: 400n } })).toMatchObject({ ok: true, problems: [] });
+ });
+ it('flags a short vault, a surplus and ledger drift', () => {
+ const r = reconcilePool({ chain, vaultBalance: 500n, ledger: { staked: 900n, paidOut: 399n } });
+ expect(r.ok).toBe(false);
+ expect(r.problems.map((p) => p.code)).toEqual(['vault_short', 'ledger_stake_mismatch', 'ledger_payout_mismatch']);
+ expect(reconcilePool({ chain, vaultBalance: 600n, ledger: { staked: 1000n, paidOut: 400n } }).problems[0]).toMatchObject({ code: 'vault_surplus', delta: '30' });
+ });
+});
+
+describe('parseProgramTx', () => {
+ const program = Keypair.generate().publicKey;
+ const disc = (n) => createHash('sha256').update(`global:${n}`).digest().subarray(0, 8);
+ const keys = Array.from({ length: 10 }, () => Keypair.generate().publicKey);
+ const u64 = (v) => { const b = Buffer.alloc(8); b.writeBigUInt64LE(v); return b; };
+ const txOf = (programKey, ixs, meta = {}) => ({
+ meta: { err: null, preTokenBalances: [], postTokenBalances: [], ...meta },
+ transaction: { message: { accountKeys: [...keys, programKey], instructions: ixs.map((i) => ({ programIdIndex: 10, accounts: i.accounts, data: i.data.toString('base64') })) } },
+ });
+ const stakeData = Buffer.concat([disc('stake'), Buffer.from([2]), u64(7_000_000n)]);
+
+ it('reads pool, wallet, outcome and amount from the transaction itself', () => {
+ const ev = parseProgramTx(txOf(program, [{ accounts: [0, 1, 2, 3, 4, 5, 6, 7, 8], data: stakeData }]), program);
+ expect(ev).toEqual({ kind: 'stake', pool: keys[1].toBase58(), wallet: keys[6].toBase58(), outcome: 2, amount: 7_000_000n });
+ });
+ it('reads a claim amount from the vault balance change', () => {
+ const tx = txOf(program, [{ accounts: [0, 1, 2, 3, 4, 5, 6], data: disc('claim') }], {
+ preTokenBalances: [{ accountIndex: 2, uiTokenAmount: { amount: '900' } }],
+ postTokenBalances: [{ accountIndex: 2, uiTokenAmount: { amount: '650' } }],
+ });
+ expect(parseProgramTx(tx, program)).toMatchObject({ kind: 'claim', amount: 250n, wallet: keys[5].toBase58() });
+ });
+ it('rejects failed transactions, other programs, unknown instructions and multi-instruction bundles', () => {
+ expect(parseProgramTx({ ...txOf(program, [{ accounts: [0], data: stakeData }]), meta: { err: {} } }, program)).toBeNull();
+ expect(parseProgramTx(txOf(Keypair.generate().publicKey, [{ accounts: [0, 1, 2, 3, 4, 5, 6], data: stakeData }]), program)).toBeNull();
+ expect(parseProgramTx(txOf(program, [{ accounts: [0], data: disc('lock') }]), program)).toBeNull();
+ const one = { accounts: [0, 1, 2, 3, 4, 5, 6, 7, 8], data: stakeData };
+ expect(parseProgramTx(txOf(program, [one, one]), program)).toBeNull();
+ expect(parseProgramTx(null, program)).toBeNull();
+ });
+});
+
+describe('stake panel amounts', () => {
+ it('converts decimal text to exact base units', () => {
+ expect(toBaseUnits('12.5', 6)).toBe(12_500_000n);
+ expect(toBaseUnits('0.000001', 6)).toBe(1n);
+ expect(toBaseUnits('7', 6)).toBe(7_000_000n);
+ });
+ it('rejects too many decimals, junk, negatives and empty text', () => {
+ for (const bad of ['1.0000001', 'abc', '-1', '', '1e3', '1,5', '.5']) expect(toBaseUnits(bad, 6)).toBeNull();
+ });
+ it('round-trips through the display form', () => {
+ for (const v of ['0.000001', '12.5', '1000000', '3.14']) expect(fromBaseUnits(toBaseUnits(v, 6), 6)).toBe(v);
+ });
+});