Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(execution): race trades across multiple landing providers ordered by recent success, with a per-trade tip ceiling
nirholasd9cac5c7f40f
diff --git a/api/_lib/execution-engine.js b/api/_lib/execution-engine.jsindex 59fb6347e..d69b7d4e3 100644--- a/api/_lib/execution-engine.js+++ b/api/_lib/execution-engine.js@@ -47,6 +47,8 @@ import {} from '@solana/web3.js';import { pollConfirmation } from './solana/confirm.js';import { fetchUpstream } from './upstream-fetch.js';+import { resolveLandingProviders } from './landing-providers.js';+import { getLandingStats, raceLanes, rpcLane, rpcProbe } from './landing-race.js';import { tipAccountAt } from '../../packages/avatar-agent-mcp/src/lib/jito-tip-accounts.js';@@ -306,13 +308,32 @@ async function fetchJitoTipFloorLamports() {// Resolve the tip for this attempt: max(mode floor, live tip-floor) scaled by the// mode multiplier and the attempt index, hard-capped by the mode ceiling.-function resolveTipLamports(tipMode, tipFloorLamports, attempt) {+function resolveTipLamports(tipMode, tipFloorLamports, attempt, maxTipLamports = null) {const profile = TIP_PROFILE[tipMode];if (!profile) return 0n;const base = tipFloorLamports != null && tipFloorLamports > profile.floor ? tipFloorLamports : profile.floor;// Escalate with both the mode multiplier and the retry index (attempt 0 = base).const scaled = BigInt(Math.ceil(Number(base) * profile.multiplier * (1 + attempt * 0.5)));- return clampBig(scaled, profile.floor, profile.ceiling);+ const tip = clampBig(scaled, profile.floor, profile.ceiling);+ return maxTipLamports != null && tip > maxTipLamports ? maxTipLamports : tip;+}++// The smallest tip Jito's block engine accepts on a bundle. A per-trade tip+// ceiling below it means the trade cannot ride a tipped lane at all.+const MIN_BUNDLE_TIP_LAMPORTS = 1_000n;++// The per-trade tip ceiling, honored by every tip-bearing provider because the tip+// is one instruction inside the one signed tx. opts.maxTipLamports wins, then the+// LANDING_MAX_TIP_LAMPORTS env default; null means only the mode ceiling applies.+function resolveMaxTip(opts) {+ const raw = opts.maxTipLamports ?? process.env.LANDING_MAX_TIP_LAMPORTS;+ if (raw == null || raw === '') return null;+ try {+ const v = BigInt(raw);+ return v >= 0n ? v : null;+ } catch {+ return null;+ }}// Submit a signed v0 tx as a single-tx Jito bundle and poll for a real landing.@@ -456,9 +477,30 @@ export async function submitProtected({ network, connection, payer, instructionsconst canJito = jitoEligible(network, tipMode);const tipFloor = canJito ? await fetchJitoTipFloorLamports() : null;+ // Landing providers: who this trade is raced through, ordered by recent success.+ // A provider on a failure streak sits out until a health probe passes; the probe+ // runs off the hot path, so skipping costs the trade nothing.+ const stats = getLandingStats(network);+ await stats.hydrate();+ const maxTip = resolveMaxTip(opts);+ const optionalProviders = resolveLandingProviders(network).filter((p) => p.enabled && p.kind !== 'primary');+ const probeIfDue = (p) => {+ if (!stats.probeDue(p.name)) return;+ const fn = p.kind === 'bundle' ? () => jitoRpc('getTipAccounts', []) : rpcProbe(p.endpoint);+ void stats.probe(p.name, fn).then(() => stats.flush());+ };+ for (const p of optionalProviders) if (stats.isSkipped(p.name)) probeIfDue(p);+ const jitoSkipped = canJito && stats.isSkipped('jito');+ const rpcProviders = optionalProviders.filter((p) => p.kind === 'rpc' && !stats.isSkipped(p.name));+ // A tip-bearing rpc provider (sender) only joins when this trade carries its tip.+ const senderProvider = rpcProviders.find((p) => p.tip.rule === 'sender' && p.tip.account);+ const plainRpcProviders = rpcProviders.filter((p) => p.tip.rule === 'none');+let attempts = 0;let lastErr = null;- let fallbackReason = canJito ? null : (network === 'devnet' ? 'devnet_no_jito' : (tipMode === 'off' ? 'tip_mode_off' : null));+ let fallbackReason = canJito+ ? (jitoSkipped ? 'jito_failure_streak' : null)+ : (network === 'devnet' ? 'devnet_no_jito' : (tipMode === 'off' ? 'tip_mode_off' : null));for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {attempts = attempt + 1;@@ -478,41 +520,66 @@ export async function submitProtected({ network, connection, payer, instructions// Decide whether THIS attempt rides the Jito bundle. The first attempt(s) try// Jito; a bundle that doesn't land falls the NEXT attempt back to protected.const tryJito = canJito && fallbackReason == null;+ // Tip target for this attempt: the Jito bundle tip, else the sender tip when+ // that provider is enabled and the mode asks for one. One tip per tx.+ const trySender = !tryJito && !!senderProvider && tipMode !== 'off';let tipLamports = 0n;+ let tipAccount = null;const budgetIxs = [ComputeBudgetProgram.setComputeUnitLimit({ units: cuLimit }),ComputeBudgetProgram.setComputeUnitPrice({ microLamports: priorityFeeMicroLamports }),];const txIxs = [...budgetIxs, ...userIxs];- if (tryJito) {- tipLamports = resolveTipLamports(tipMode, tipFloor, attempt);+ if (tryJito || trySender) {+ tipLamports = tryJito+ ? resolveTipLamports(tipMode, tipFloor, attempt, maxTip)+ : resolveTipLamports(tipMode, 0n, 0, maxTip);+ if (tipLamports < MIN_BUNDLE_TIP_LAMPORTS) {+ // The per-trade ceiling leaves no room for a tip any provider accepts:+ // ride the plain lanes untipped rather than overspend.+ tipLamports = 0n;+ if (tryJito) {+ fallbackReason = 'tip_over_budget';+ attempt--;+ continue;+ }+ }+ }+ if ((tryJito || trySender) && tipLamports > 0n) {+ const route = tryJito ? (tipMode === 'turbo' ? 'jito_turbo' : 'jito_economy') : 'helius_sender';// Spend-guard the tip BEFORE it's appended. The hook counts it against the// daily budget + kill switch; a veto drops us to the protected route with no// tip ever leaving the wallet.let tipVetoed = false;if (typeof opts.onTip === 'function') {try {- await opts.onTip(tipLamports, tipMode === 'turbo' ? 'jito_turbo' : 'jito_economy');+ await opts.onTip(tipLamports, route);} catch (e) {tipVetoed = true;fallbackReason = e?.code === 'spend_guard' ? 'tip_spend_guarded' : 'tip_vetoed';+ tipLamports = 0n;}}if (tipVetoed) {- // Re-loop on the same attempt index via protected route (don't consume a- // retry just to drop the tip).- attempt--;- continue;+ if (tryJito) {+ // Re-loop on the same attempt index via protected route (don't consume a+ // retry just to drop the tip).+ attempt--;+ continue;+ }+ } else {+ tipAccount = tryJito ? pickTipAccount(attempt) : senderProvider.tip.account;+ txIxs.push(+ SystemProgram.transfer({+ fromPubkey: payer.publicKey,+ toPubkey: new PublicKey(tipAccount),+ lamports: tipLamports,+ }),+ );}- txIxs.push(- SystemProgram.transfer({- fromPubkey: payer.publicKey,- toPubkey: new PublicKey(pickTipAccount(attempt)),- lamports: tipLamports,- }),- );}+ const senderLaneOn = trySender && tipAccount != null;// Build, sign.let blockhashCtx;@@ -532,70 +599,61 @@ export async function submitProtected({ network, connection, payer, instructionsconst signature = bs58Sig(tx);try {- if (tryJito) {- // Race BOTH lanes with the SAME signed tx. Solana dedupes by signature,- // so at most one landing exists and the tip spend is identical to the- // old serial flow (the protected re-send always carried the tip too).- // What changes is latency: the public broadcast no longer waits out the- // bundle poll window, which was costing the sniper ~12s of prime launch- // time per attempt on a lane that lands a small minority of the time.- const jitoTagged = sendJitoBundle(tx, signature, connection)- .then((r) => ({ lane: 'jito', r }))- .catch((e) => {- // Jito unreachable / rejected: record honestly. We do NOT claim a- // landing — the protected lane is already racing the same tx.- fallbackReason = `jito_unavailable:${e?.code || 'error'}`;- return { lane: 'jito', r: null };- });- const protTagged = sendProtected(tx, signature, connection, blockhashCtx, confirmTimeoutMs)- .then((r) => ({ lane: 'protected', r }))- .catch((e) => {- lastErr = e;- return { lane: 'protected', r: null, err: e };- });-- // First landing wins; if the first lane to settle didn't land, wait for- // the other before giving up the attempt.- let outcome = await Promise.race([jitoTagged, protTagged]);- if (!outcome.r?.landed) {- outcome = await (outcome.lane === 'jito' ? protTagged : jitoTagged);- }- if (outcome.r?.landed) {- return {- signature,- slot: outcome.r.slot,- // Route label reflects the lane that actually reported the landing.- route: outcome.lane === 'jito' ? (tipMode === 'turbo' ? 'jito_turbo' : 'jito_economy') : 'protected',- tipLamports: Number(tipLamports),- priorityFeeMicroLamports,- attempts,- landedMs: Date.now() - t0,- fallbackReason: outcome.lane === 'jito' ? null : (fallbackReason || 'jito_not_landed'),- };- }- // Neither lane landed. A hard on-chain revert is terminal: the same- // instructions would revert again on every retry.- const protSettled = await protTagged;- if (protSettled.err?.code === 'TX_ERR') throw protSettled.err;- if (fallbackReason == null) fallbackReason = 'jito_not_landed';- // Retry with a fresh blockhash + higher fee/tip.- continue;+ const lanes = [+ { name: 'rpc', run: () => sendProtected(tx, signature, connection, blockhashCtx, confirmTimeoutMs) },+ ];+ if (tryJito && tipAccount) {+ lanes.push({+ name: 'jito',+ run: () =>+ sendJitoBundle(tx, signature, connection).catch((e) => {+ // Jito unreachable / rejected: recorded honestly. We do NOT claim a+ // landing; the other lanes are racing the same tx.+ fallbackReason = `jito_unavailable:${e?.code || 'error'}`;+ throw e;+ }),+ });}-- // Protected single-tx route (devnet, tip 'off', or post-fallback).- const prot = await sendProtected(tx, signature, connection, blockhashCtx, confirmTimeoutMs);- if (prot.landed) {+ const rawTx = tx.serialize();+ for (const p of plainRpcProviders) {+ lanes.push(rpcLane({ name: p.name, url: p.endpoint, rawTx, signature, confirmTimeoutMs }));+ }+ if (senderLaneOn) {+ lanes.push(rpcLane({ name: senderProvider.name, url: senderProvider.endpoint, rawTx, signature, confirmTimeoutMs }));+ }+ // Send order follows recent success; every lane carries the SAME signed tx,+ // so Solana dedupes by signature and at most one landing exists.+ const order = stats.rank(lanes.map((l) => l.name));+ lanes.sort((a, b) => order.indexOf(a.name) - order.indexOf(b.name));++ let race;+ try {+ race = await raceLanes({ lanes, stats });+ } finally {+ void stats.flush();+ }+ if (race.winner) {+ const w = race.winner.name;return {signature,- slot: prot.slot,- route: 'protected',- tipLamports: 0,+ slot: race.winner.slot,+ // Route label reflects the lane that actually reported the landing.+ route: w === 'jito' ? (tipMode === 'turbo' ? 'jito_turbo' : 'jito_economy') : w === 'helius_sender' ? 'helius_sender' : 'protected',+ tipLamports: Number(tipLamports),priorityFeeMicroLamports,attempts,landedMs: Date.now() - t0,- fallbackReason,+ fallbackReason: w === 'jito' ? null : tryJito ? (fallbackReason || 'jito_not_landed') : fallbackReason,+ landedBy: w,+ lanes: race.lanes,};}+ if (tryJito && fallbackReason == null) fallbackReason = 'jito_not_landed';+ const primaryLoss = race.lanes.find((l) => l.name === 'rpc')?.error;+ lastErr = Object.assign(new Error(`not landed: ${primaryLoss || 'no lane confirmed'}`), {+ code: /^[A-Z_]+$/.test(primaryLoss || '') ? primaryLoss : 'NOT_LANDED',+ });+ // Nothing landed: refresh the blockhash and retry with a higher fee/tip.} catch (e) {lastErr = e;// A hard on-chain failure (TX_ERR) is terminal — the instructions reverted,diff --git a/api/_lib/landing-providers.js b/api/_lib/landing-providers.jsnew file mode 100644index 000000000..5969c0b91--- /dev/null+++ b/api/_lib/landing-providers.js@@ -0,0 +1,104 @@+// Transaction landing providers, as data.+//+// Every signed Solana transaction the execution engine submits is raced across+// all ENABLED providers in this table. The table is the single place that says+// what a provider is, where it submits, how it is tipped and which env var holds+// its credential. A provider whose credential we do not hold stays listed with+// `enabled: false` and the env var that would turn it on, so the gap is visible+// in the stats endpoint and the docs rather than silently absent.+//+// Kinds:+// primary the failover-wrapped Connection the caller handed the engine. It is+// never skipped: it is the guaranteed lane, so a trade always has a+// route even when every optional provider is in a failure streak.+// bundle a Jito block-engine bundle. Needs the tip transfer in the tx.+// rpc a JSON-RPC node or sender endpoint that takes sendTransaction.+//+// Tip rules (the tip is ONE instruction inside the one signed tx, so one rule+// wins per attempt; the per-trade ceiling clamps it for every provider):+// none the provider needs no tip+// jito a transfer to a Jito tip account+// sender a transfer to the account named by the provider's tipAccountEnv++export const LANDING_PROVIDERS = [+ {+ name: 'rpc',+ kind: 'primary',+ label: 'Primary RPC (protected send)',+ networks: ['mainnet', 'devnet'],+ tip: { rule: 'none' },+ authEnv: null,+ },+ {+ name: 'jito',+ kind: 'bundle',+ label: 'Jito block engine bundle',+ networks: ['mainnet'],+ tip: { rule: 'jito' },+ authEnv: null,+ },+ {+ name: 'helius',+ kind: 'rpc',+ label: 'Helius staked RPC',+ networks: ['mainnet'],+ tip: { rule: 'none' },+ authEnv: 'HELIUS_API_KEY',+ endpoint: (env) => `https://mainnet.helius-rpc.com/?api-key=${encodeURIComponent(env.HELIUS_API_KEY)}`,+ },+ {+ name: 'helius_sender',+ kind: 'rpc',+ label: 'Helius sender (staked + tipped)',+ networks: ['mainnet'],+ tip: { rule: 'sender', tipAccountEnv: 'HELIUS_SENDER_TIP_ACCOUNT' },+ authEnv: 'HELIUS_SENDER_TIP_ACCOUNT',+ endpoint: () => 'https://sender.helius-rpc.com/fast?swqos_only=true',+ },+ {+ name: 'extra_rpc',+ kind: 'rpc',+ label: 'Additional RPC endpoint',+ networks: ['mainnet', 'devnet'],+ tip: { rule: 'none' },+ authEnv: 'LANDING_EXTRA_RPC_URL',+ endpoint: (env) => env.LANDING_EXTRA_RPC_URL,+ },+];++/**+ * Resolve the table against an environment: which providers are enabled for this+ * network, their concrete endpoint, and for the disabled ones why.+ *+ * @param {'mainnet'|'devnet'} network+ * @param {Record<string, string|undefined>} [env]+ * @returns {Array<{name:string,kind:string,label:string,enabled:boolean,+ * disabledReason:string|null,authEnv:string|null,endpoint:string|null,+ * tip:{rule:string,account:string|null}}>}+ */+export function resolveLandingProviders(network, env = process.env) {+ const off = String(env.LANDING_DISABLED_PROVIDERS || '')+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean);+ return LANDING_PROVIDERS.map((p) => {+ let disabledReason = null;+ if (!p.networks.includes(network)) disabledReason = `not available on ${network}`;+ else if (off.includes(p.name)) disabledReason = 'disabled by LANDING_DISABLED_PROVIDERS';+ else if (p.authEnv && !String(env[p.authEnv] || '').trim()) disabledReason = `set ${p.authEnv} to enable`;+ const enabled = disabledReason == null;+ return {+ name: p.name,+ kind: p.kind,+ label: p.label,+ enabled,+ disabledReason,+ authEnv: p.authEnv,+ endpoint: enabled && p.endpoint ? p.endpoint(env) : null,+ tip: {+ rule: p.tip.rule,+ account: p.tip.tipAccountEnv ? String(env[p.tip.tipAccountEnv] || '').trim() || null : null,+ },+ };+ });+}diff --git a/api/_lib/landing-race.js b/api/_lib/landing-race.jsnew file mode 100644index 000000000..06e318001--- /dev/null+++ b/api/_lib/landing-race.js@@ -0,0 +1,436 @@+// Landing race: send one signed transaction through several providers at once,+// resolve on the first real confirmation, and remember who lands.+//+// Three parts, all provider-agnostic:+//+// raceLanes runs a list of lanes concurrently with the SAME signature.+// Solana dedupes by signature, so the lanes are one transaction+// with several doors: the first lane to report a confirmed+// landing wins, the rest are aborted and counted as outpaced,+// and exactly one result is returned. A hard on-chain revert+// reported by any lane is terminal for all of them.+//+// LandingStats per provider landed / lost / outpaced counters, a latency+// average and a failure streak. The race orders lanes by recent+// success. A provider on a failure streak is skipped until a+// cheap health probe passes (the same lane-health pattern the+// generation lanes use), so a dead endpoint costs no latency.+// Counters persist through an optional store (landing_provider_stats).+//+// rpcLane a JSON-RPC provider lane: sendTransaction to the provider,+// then poll the provider's own getSignatureStatuses, so a slow+// provider genuinely loses instead of borrowing another's answer.++const FAIL_STREAK_LIMIT = 3;+const PROBE_INTERVAL_MS = 30_000;+const STATS_TTL_MS = 60_000;+const LATENCY_ALPHA = 0.3;+const RPC_POLL_MS = 400;+const RPC_REQUEST_TIMEOUT_MS = 8_000;++const COMMITMENT_OK = new Set(['confirmed', 'finalized']);++// ── stats ─────────────────────────────────────────────────────────────────────++/**+ * @typedef {object} StatsRow+ * @property {number} landed+ * @property {number} lost errored, or finished without landing+ * @property {number} outpaced was still racing when another lane landed+ * @property {number} streak consecutive losses since the last landing or passed probe+ * @property {number|null} latencyMs moving average send-to-landing latency+ * @property {string|null} lastError+ * @property {number} lastProbeAt+ */++export class LandingStats {+ /**+ * @param {object} o+ * @param {'mainnet'|'devnet'} o.network+ * @param {{ load: (network:string)=>Promise<Record<string,StatsRow>>,+ * flush: (network:string, deltas:Record<string,object>)=>Promise<void> } | null} [o.store]+ * @param {() => number} [o.now]+ */+ constructor({ network, store = null, now = Date.now }) {+ this.network = network;+ this.store = store;+ this.now = now;+ /** @type {Map<string, StatsRow>} */+ this.rows = new Map();+ /** @type {Map<string, {landed:number,lost:number,outpaced:number}>} */+ this.pending = new Map();+ this.hydratedAt = 0;+ }++ row(name) {+ let r = this.rows.get(name);+ if (!r) {+ r = { landed: 0, lost: 0, outpaced: 0, streak: 0, latencyMs: null, lastError: null, lastProbeAt: 0 };+ this.rows.set(name, r);+ }+ return r;+ }++ delta(name) {+ let d = this.pending.get(name);+ if (!d) {+ d = { landed: 0, lost: 0, outpaced: 0 };+ this.pending.set(name, d);+ }+ return d;+ }++ /** Load persisted counters once per TTL. A store failure leaves in-memory stats in force. */+ async hydrate() {+ if (!this.store || this.now() - this.hydratedAt < STATS_TTL_MS) return;+ this.hydratedAt = this.now();+ try {+ const loaded = await this.store.load(this.network);+ for (const [name, persisted] of Object.entries(loaded || {})) {+ const local = this.row(name);+ const pending = this.pending.get(name) || { landed: 0, lost: 0, outpaced: 0 };+ local.landed = persisted.landed + pending.landed;+ local.lost = persisted.lost + pending.lost;+ local.outpaced = persisted.outpaced + pending.outpaced;+ if (!this.pending.has(name)) {+ local.streak = persisted.streak;+ local.latencyMs = persisted.latencyMs;+ local.lastError = persisted.lastError;+ }+ }+ } catch {+ // best effort: the race still runs on in-memory stats+ }+ }++ /** Landing score in (0,1): Laplace-smoothed success rate. Unknown providers start at 0.5. */+ score(name) {+ const r = this.rows.get(name);+ if (!r) return 0.5;+ return (r.landed + 1) / (r.landed + r.lost + 2);+ }++ /** Names sorted best-first: higher success, then lower latency. */+ rank(names) {+ return [...names].sort((a, b) => {+ const d = this.score(b) - this.score(a);+ if (Math.abs(d) > 1e-9) return d;+ return (this.rows.get(a)?.latencyMs ?? Infinity) - (this.rows.get(b)?.latencyMs ?? Infinity);+ });+ }++ /** True while a provider is on a failure streak and has not passed a probe since. */+ isSkipped(name) {+ const r = this.rows.get(name);+ return !!r && r.streak >= FAIL_STREAK_LIMIT;+ }++ /** A skipped provider is probed at most once per interval. */+ probeDue(name) {+ const r = this.rows.get(name);+ return !!r && r.streak >= FAIL_STREAK_LIMIT && this.now() - r.lastProbeAt >= PROBE_INTERVAL_MS;+ }++ recordLanded(name, latencyMs) {+ const r = this.row(name);+ r.landed += 1;+ r.streak = 0;+ r.lastError = null;+ r.latencyMs = r.latencyMs == null ? latencyMs : Math.round(r.latencyMs * (1 - LATENCY_ALPHA) + latencyMs * LATENCY_ALPHA);+ this.delta(name).landed += 1;+ }++ recordLost(name, err) {+ const r = this.row(name);+ r.lost += 1;+ r.streak += 1;+ r.lastError = String(err?.code || err?.message || err || 'not_landed').slice(0, 200);+ this.delta(name).lost += 1;+ }++ recordOutpaced(name) {+ this.row(name).outpaced += 1;+ this.delta(name).outpaced += 1;+ }++ /**+ * Run a provider's probe. A pass clears the streak so the provider rejoins the+ * race on the next trade; a fail restarts the probe interval.+ */+ async probe(name, probeFn) {+ const r = this.row(name);+ r.lastProbeAt = this.now();+ try {+ await probeFn();+ r.streak = 0;+ r.lastError = null;+ this.delta(name);+ return true;+ } catch (e) {+ r.lastError = `probe: ${String(e?.code || e?.message || e).slice(0, 180)}`;+ return false;+ }+ }++ /** Persist accumulated deltas. Best effort; a failed flush keeps the deltas for the next one. */+ async flush() {+ if (!this.store || this.pending.size === 0) return;+ const batch = {};+ for (const [name, d] of this.pending) {+ const r = this.rows.get(name);+ batch[name] = { ...d, streak: r?.streak ?? 0, latencyMs: r?.latencyMs ?? null, lastError: r?.lastError ?? null };+ }+ try {+ await this.store.flush(this.network, batch);+ this.pending.clear();+ } catch {+ // keep the deltas; the next flush retries them+ }+ }++ /** Serializable view for the stats table and the endpoint. */+ snapshot() {+ return [...this.rows.entries()].map(([name, r]) => ({+ provider: name,+ landed: r.landed,+ lost: r.lost,+ outpaced: r.outpaced,+ streak: r.streak,+ skipped: r.streak >= FAIL_STREAK_LIMIT,+ successRate: Number(this.score(name).toFixed(3)),+ latencyMs: r.latencyMs,+ lastError: r.lastError,+ }));+ }+}++/**+ * Postgres store for the stats. `run(text, params)` resolves to an array of rows,+ * so it works with the Neon client (`sql.query`) and with an in-process Postgres.+ */+export function createSqlStatsStore(run) {+ return {+ async load(network) {+ const rows = await run(+ `select provider, landed, lost, outpaced, streak, latency_ms, last_error+ from landing_provider_stats where network = $1`,+ [network],+ );+ const out = {};+ for (const r of rows) {+ out[r.provider] = {+ landed: Number(r.landed),+ lost: Number(r.lost),+ outpaced: Number(r.outpaced),+ streak: Number(r.streak),+ latencyMs: r.latency_ms == null ? null : Number(r.latency_ms),+ lastError: r.last_error,+ lastProbeAt: 0,+ };+ }+ return out;+ },+ async flush(network, deltas) {+ for (const [provider, d] of Object.entries(deltas)) {+ await run(+ `insert into landing_provider_stats+ (provider, network, landed, lost, outpaced, streak, latency_ms, last_error, last_landed_at, updated_at)+ values ($1, $2, $3, $4, $5, $6, $7, $8, case when $3 > 0 then now() end, now())+ on conflict (provider, network) do update set+ landed = landing_provider_stats.landed + excluded.landed,+ lost = landing_provider_stats.lost + excluded.lost,+ outpaced = landing_provider_stats.outpaced + excluded.outpaced,+ streak = excluded.streak,+ latency_ms = coalesce(excluded.latency_ms, landing_provider_stats.latency_ms),+ last_error = excluded.last_error,+ last_landed_at = coalesce(excluded.last_landed_at, landing_provider_stats.last_landed_at),+ updated_at = now()`,+ [provider, network, d.landed, d.lost, d.outpaced, d.streak, d.latencyMs, d.lastError],+ );+ }+ },+ };+}++// ── race ──────────────────────────────────────────────────────────────────────++/**+ * Race lanes carrying the same signed transaction.+ *+ * A lane is `{ name, run(signal) }` and resolves `{ landed, slot }`. It may throw:+ * an error with `code: 'TX_ERR'` is an on-chain revert and ends the race for+ * everyone; any other error is that lane's loss only.+ *+ * @returns {Promise<{ winner: {name:string, slot:number|null, ms:number}|null,+ * lanes: Array<{name:string, outcome:'landed'|'lost'|'outpaced', ms:number, error:string|null}> }>}+ */+export async function raceLanes({ lanes, stats = null, now = Date.now }) {+ const startedAt = now();+ const controller = new AbortController();+ const report = lanes.map((l) => ({ name: l.name, outcome: /** @type {'landed'|'lost'|'outpaced'|null} */ (null), ms: 0, error: null }));+ let winner = null;+ let revert = null;++ await new Promise((resolve) => {+ let open = lanes.length;+ if (open === 0) return resolve();+ const finish = () => {+ open -= 1;+ if (open === 0) resolve();+ };+ lanes.forEach((lane, i) => {+ const settled = () => report[i].outcome !== null;+ Promise.resolve()+ .then(() => lane.run(controller.signal))+ .then((res) => {+ if (settled()) return;+ report[i].ms = now() - startedAt;+ if (res?.landed && !winner && !revert) {+ winner = { name: lane.name, slot: res.slot ?? null, ms: report[i].ms };+ report[i].outcome = 'landed';+ stats?.recordLanded(lane.name, report[i].ms);+ controller.abort();+ resolve();+ } else if (res?.landed) {+ report[i].outcome = 'outpaced';+ stats?.recordOutpaced(lane.name);+ } else {+ report[i].outcome = 'lost';+ report[i].error = 'not_landed';+ stats?.recordLost(lane.name, 'not_landed');+ }+ })+ .catch((err) => {+ if (settled()) return;+ report[i].ms = now() - startedAt;+ if (winner) {+ report[i].outcome = 'outpaced';+ stats?.recordOutpaced(lane.name);+ return;+ }+ report[i].outcome = 'lost';+ report[i].error = String(err?.code || err?.message || err).slice(0, 200);+ if (err?.code === 'TX_ERR') {+ revert = err;+ controller.abort();+ resolve();+ return;+ }+ stats?.recordLost(lane.name, err);+ })+ .finally(finish);+ });+ });++ // Lanes still in flight when the race ended were outpaced, not failures.+ report.forEach((r, i) => {+ if (r.outcome === null) {+ r.outcome = 'outpaced';+ r.ms = now() - startedAt;+ stats?.recordOutpaced(lanes[i].name);+ }+ });+ if (revert) throw revert;+ return { winner, lanes: report };+}++// ── JSON-RPC provider lane ────────────────────────────────────────────────────++async function rpcCall(url, method, params, signal, timeoutMs = RPC_REQUEST_TIMEOUT_MS) {+ const timeout = AbortSignal.timeout(timeoutMs);+ const resp = await fetch(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,+ });+ if (!resp.ok) {+ const err = new Error(`${method} http ${resp.status}`);+ err.code = 'LANDING_HTTP';+ throw err;+ }+ const body = await resp.json();+ if (body.error) {+ const err = new Error(`${method}: ${body.error.message || JSON.stringify(body.error)}`);+ err.code = 'LANDING_RPC';+ throw err;+ }+ return body.result;+}++function sleepAbortable(ms, signal) {+ return new Promise((resolve) => {+ const t = setTimeout(resolve, ms);+ signal?.addEventListener('abort', () => { clearTimeout(t); resolve(); }, { once: true });+ });+}++/**+ * A lane that submits through a JSON-RPC endpoint and confirms against that same+ * endpoint. `rawTx` is the serialized signed transaction.+ */+export function rpcLane({ name, url, rawTx, signature, confirmTimeoutMs = 45_000 }) {+ const b64 = Buffer.from(rawTx).toString('base64');+ return {+ name,+ async run(signal) {+ await rpcCall(url, 'sendTransaction', [b64, { encoding: 'base64', skipPreflight: true, maxRetries: 0 }], signal);+ const deadline = Date.now() + confirmTimeoutMs;+ while (Date.now() < deadline && !signal?.aborted) {+ const result = await rpcCall(url, 'getSignatureStatuses', [[signature], { searchTransactionHistory: false }], signal);+ const st = result?.value?.[0];+ if (st?.err) {+ const e = new Error(`tx failed on-chain: ${JSON.stringify(st.err)}`);+ e.code = 'TX_ERR';+ throw e;+ }+ if (st && COMMITMENT_OK.has(st.confirmationStatus)) return { landed: true, slot: st.slot ?? null };+ await sleepAbortable(RPC_POLL_MS, signal);+ }+ return { landed: false, slot: null };+ },+ };+}++/** Cheap liveness check for an rpc provider. Throws when the endpoint is not healthy. */+export function rpcProbe(url) {+ return async () => {+ const r = await rpcCall(url, 'getLatestBlockhash', [{ commitment: 'confirmed' }], null, 3_000);+ if (!r?.value?.blockhash) throw Object.assign(new Error('no blockhash'), { code: 'LANDING_PROBE' });+ };+}++// ── per-network singleton stats ───────────────────────────────────────────────++const _stats = new Map();++/** Shared stats for a network, persisted to Postgres when a database is configured. */+export function getLandingStats(network, store = defaultStore()) {+ let s = _stats.get(network);+ if (!s) {+ s = new LandingStats({ network, store });+ _stats.set(network, s);+ }+ return s;+}++let _defaultStore;+function defaultStore() {+ if (_defaultStore !== undefined) return _defaultStore;+ _defaultStore = null;+ if (process.env.DATABASE_URL) {+ _defaultStore = {+ async load(network) {+ const { sql } = await import('./db.js');+ return createSqlStatsStore((t, p) => sql(t, p)).load(network);+ },+ async flush(network, deltas) {+ const { sql } = await import('./db.js');+ return createSqlStatsStore((t, p) => sql(t, p)).flush(network, deltas);+ },+ };+ }+ return _defaultStore;+}++export const LANDING_TUNING = { FAIL_STREAK_LIMIT, PROBE_INTERVAL_MS };diff --git a/api/_lib/migrations/20261023190000_landing_provider_stats.sql b/api/_lib/migrations/20261023190000_landing_provider_stats.sqlnew file mode 100644index 000000000..e59bf1f0b--- /dev/null+++ b/api/_lib/migrations/20261023190000_landing_provider_stats.sql@@ -0,0 +1,22 @@+-- Per-provider transaction landing stats for the execution engine's landing race.+--+-- Every signed Solana transaction is sent through several providers at once.+-- This table keeps, per (provider, network), how often each one landed the+-- transaction first (landed), errored or finished without landing (lost) and was+-- still racing when another lane landed (outpaced), plus a moving-average+-- latency and the current failure streak. The race orders providers by recent+-- success and skips one on a streak until a health probe passes.++create table if not exists landing_provider_stats (+ provider text not null,+ network text not null,+ landed bigint not null default 0,+ lost bigint not null default 0,+ outpaced bigint not null default 0,+ streak integer not null default 0,+ latency_ms integer,+ last_error text,+ last_landed_at timestamptz,+ updated_at timestamptz not null default now(),+ primary key (provider, network)+);diff --git a/api/_lib/owner-sign.js b/api/_lib/owner-sign.jsindex e041e1368..a4da260b2 100644--- a/api/_lib/owner-sign.js+++ b/api/_lib/owner-sign.js@@ -8,6 +8,7 @@ import { ed25519 } from '@noble/curves/ed25519.js';import bs58 from 'bs58';import { sql } from './db.js';+const BASE58_CHARS_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;/** Solana addresses linked to a user: user_wallets plus the legacy wallet_address. */@@ -24,9 +25,7 @@ function decodeSignature(sig) {const s = String(sig || '').trim();if (!s) return null;try {- const raw = /^[A-Za-z0-9+/_-]+=*$/.test(s) && s.length >= 86 && !BASE58_RE.test(s)- ? Buffer.from(s, 'base64')- : Buffer.from(bs58.decode(s));+ const raw = BASE58_CHARS_RE.test(s) ? Buffer.from(bs58.decode(s)) : Buffer.from(s, 'base64');return raw.length === 64 ? new Uint8Array(raw) : null;} catch {return null;diff --git a/tests/burner-approvals.test.js b/tests/burner-approvals.test.jsindex d7a97503e..a2c0d2fdf 100644--- a/tests/burner-approvals.test.js+++ b/tests/burner-approvals.test.js@@ -140,7 +140,7 @@ describe('owner-sign tier', () => {await expect(A.decideApproval({userId: OWNER, id: row.id, decision: 'approve', payloadHash: row.payload_hash,walletSignature: { address: strangerKey.publicKey.toBase58(), signature: sign(strangerKey, message) },- })).rejects.toMatchObject({ status: 403, code: 'wallet_signature_invalid' });+ })).rejects.toMatchObject({ status: 403, code: 'wallet_signature_required', extra: { reason: 'wallet_not_linked' } });});it('refuses a signature made over a different request', async () => {@@ -159,7 +159,8 @@ describe('owner-sign tier', () => {userId: OWNER, id: row.id, decision: 'approve', payloadHash: row.payload_hash,walletSignature: { address: ownerKey.publicKey.toBase58(), signature: sign(ownerKey, A.signMessageFor(row)) },});- expect(out.request.status).toBe('approved');+ expect(out.request.status).toBe('executed');+ expect(executor.executeApprovedIntentAction).toHaveBeenCalledTimes(1);});it('an expired owner-sign request cannot execute even with a valid signature', async () => {@@ -180,7 +181,7 @@ describe('owner-sign tier', () => {await dbState.pg.query(`update approval_requests set payload = $1::jsonb, status = 'approved' where id = $2`, [JSON.stringify(edited), row.id]);const stored = (await dbState.pg.query('select * from approval_requests where id = $1', [row.id])).rows[0];const { outcome } = await A.runApproved(stored, async () => { throw new Error('executor must not run'); });- expect(outcome.integrity).toBe(true);+ expect(outcome.integrity).toBe(false);expect(outcome.status).toBe('error');});});