@rekt-trading/wheelman 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,332 @@
1
+ // The commands, one function each. The CLI (src/cli.ts) and the MCP server (src/mcp.ts) call these
2
+ // same functions, and `run` drives the same broker, so there is one code path for every surface.
3
+ // Each returns plain data: money as USDC text with 6 decimals, ids as text.
4
+ import { join } from 'node:path';
5
+ import { PublicKey } from '@solana/web3.js';
6
+ import { parseUsdc, traderPda } from '@rekt-trading/1000x';
7
+ import { USDC_MINT, balances, collect, fileStore, sessionEnd, sessionStart, sessionStatus } from "./account.js";
8
+ import { ata, createKnockoutClient } from "./client.js";
9
+ import { MARKETS, parseConfig } from "./config.js";
10
+ import { Refusal } from "./errors.js";
11
+ import { log, setJournal } from "./journal.js";
12
+ import { createMinuteClient } from "./minute.js";
13
+ import { Paper, readVenue, termsFor } from "./paper.js";
14
+ import { priceSource } from "./prices.js";
15
+ import { guard } from "./risk.js";
16
+ import { checkCluster, makeRpc, transact, watch } from "./rpc.js";
17
+ import { Live, dayStart, heldBy, realizedToday, sendBatch, trade } from "./runner.js";
18
+ import { registry } from "./strategies/index.js";
19
+ export async function makeCtx(env, agent = false) {
20
+ const extra = (env.EXTRA_STRATEGIES ?? '').split(',').map((s) => s.trim()).filter((s) => s !== '');
21
+ return { env, strategies: await registry(extra), agent, prices: null, rpcs: new Map() };
22
+ }
23
+ /** Parse what the command needs, and connect: the cluster is checked once per endpoint. */
24
+ async function handles(ctx, needs, game = 'knockout') {
25
+ const cfg = parseConfig(ctx.env, needs, ctx.strategies);
26
+ setJournal(join(cfg.stateDir, 'journal.jsonl'));
27
+ // An agent signs only with a session key; the owner's key never reaches it.
28
+ const signer = ctx.agent ? cfg.session : (cfg.session ?? cfg.wallet);
29
+ if (ctx.connect !== undefined)
30
+ return ctx.connect(cfg, game, signer);
31
+ let rpc = ctx.rpcs.get(cfg.rpcUrl);
32
+ if (rpc === undefined) {
33
+ rpc = (async () => {
34
+ const r = makeRpc(cfg);
35
+ await checkCluster(r);
36
+ return r;
37
+ })();
38
+ ctx.rpcs.set(cfg.rpcUrl, rpc);
39
+ }
40
+ const owner = cfg.owner ?? PublicKey.default;
41
+ const o = { rpc: await rpc, owner, signer, maxPriorityFee: cfg.maxPriorityFee, tip: cfg.tip, store: fileStore(cfg.stateDir) };
42
+ return {
43
+ cfg, rpc: o.rpc, owner, game, knockout: createKnockoutClient(o), minute: createMinuteClient(o),
44
+ sender: { rpc: o.rpc, payer: signer?.publicKey ?? owner, signer, maxPriorityFee: cfg.maxPriorityFee, tip: cfg.tip },
45
+ venue: (market) => readVenue(o.rpc, market),
46
+ };
47
+ }
48
+ export const usdc = (n) => {
49
+ const a = n < 0n ? -n : n;
50
+ return `${n < 0n ? '-' : ''}${a / 1000000n}.${(a % 1000000n).toString().padStart(6, '0')}`;
51
+ };
52
+ const bad = (message) => new Refusal('config', 'BAD_ARGUMENT', message);
53
+ const marketArg = (a) => {
54
+ const m = (a.market ?? '').toUpperCase();
55
+ if (!MARKETS.includes(m))
56
+ throw bad(`market must be one of ${MARKETS.join(', ')}`);
57
+ return m;
58
+ };
59
+ const sideArg = (a) => {
60
+ if (a.side !== 'long' && a.side !== 'short')
61
+ throw bad('side must be long or short');
62
+ return a.side;
63
+ };
64
+ const usdArg = (a) => {
65
+ try {
66
+ const v = parseUsdc(a.usd ?? '');
67
+ if (v > 0n)
68
+ return v;
69
+ }
70
+ catch {
71
+ // refused below
72
+ }
73
+ throw bad('usd must be an amount of USDC above 0, like 1.50');
74
+ };
75
+ const intentOf = (a) => a.minute === true
76
+ ? { kind: 'round', side: sideArg(a), stake: usdArg(a) }
77
+ : { kind: 'open', side: sideArg(a), stake: usdArg(a), takeProfitX: a.target ?? 0, timerS: a.timer ?? 0 };
78
+ // ---- read commands ----
79
+ export async function markets(ctx) {
80
+ const h = await handles(ctx, {});
81
+ const out = [];
82
+ for (const symbol of MARKETS) {
83
+ try {
84
+ const m = await h.knockout.market(symbol);
85
+ out.push({
86
+ symbol: m.symbol, open: m.open, why: m.why, minute: m.minute, leverage: m.leverage,
87
+ stake: { min: usdc(m.stake.min), max: usdc(m.stake.max) }, fees: m.fees,
88
+ sideRoom: { long: m.sideRoom.long === null ? null : usdc(m.sideRoom.long), short: m.sideRoom.short === null ? null : usdc(m.sideRoom.short) },
89
+ });
90
+ }
91
+ catch (e) {
92
+ if (!(e instanceof Refusal && e.code === 'NO_SUCH_MARKET'))
93
+ throw e;
94
+ }
95
+ }
96
+ return out;
97
+ }
98
+ export async function preview(ctx, a) {
99
+ const market = marketArg(a);
100
+ const side = sideArg(a);
101
+ const usd = usdArg(a);
102
+ const h = await handles(ctx, {});
103
+ if (a.minute === true) {
104
+ const p = await h.minute.preview({ market, side, usd });
105
+ return {
106
+ game: 'minute', market, side, total: usdc(p.total), stake: usdc(p.stake), leverage: p.leverage, timer: p.timer, target: p.target,
107
+ payoutAtTarget: p.payoutAtTarget === null ? null : usdc(p.payoutAtTarget), payoutAtBarrier: usdc(p.payoutAtBarrier), minuteFees: p.minuteFees,
108
+ };
109
+ }
110
+ const p = await h.knockout.preview({ market, side, usd, target: a.target ?? 0, timer: a.timer ?? 0 });
111
+ return {
112
+ game: 'knockout', market, side, debit: usdc(p.debit), stake: usdc(p.stake), leverage: p.leverage, barrierBps: p.barrierBps,
113
+ target: p.target, targetBps: p.targetBps, timer: p.timer, payoutAtTarget: p.payoutAtTarget === null ? null : usdc(p.payoutAtTarget), payoutAtBarrier: usdc(p.payoutAtBarrier),
114
+ };
115
+ }
116
+ export async function positions(ctx, a) {
117
+ if (a.paper === true) {
118
+ const h = await handles(ctx, {});
119
+ const { paper, save } = await paperAccount(h, a.market ?? h.cfg.market);
120
+ await markPaper(ctx, paper);
121
+ save();
122
+ return paperView(paper);
123
+ }
124
+ const h = await handles(ctx, { key: 'address' });
125
+ const [k, r, b, today] = await Promise.all([h.knockout.positions(), h.minute.rounds(), balances(h.rpc, h.owner, h.sender.payer), todayResult(h)]);
126
+ return {
127
+ owner: h.owner.toBase58(),
128
+ positions: k.map((p) => ({
129
+ id: p.seq.toString(), market: p.market, side: p.side, stake: usdc(p.stake), entryPrice: p.entryPrice, barrierPrice: p.barrierPrice,
130
+ targetPrice: p.targetPrice, state: p.state, openedAt: p.openedAt, timerEndsAt: p.timerEndsAt,
131
+ })),
132
+ rounds: r.map((x) => ({ id: x.seq.toString(), market: x.market, side: x.side, total: usdc(x.total), entryPrice: x.entryPrice, deadline: x.deadline })),
133
+ balances: { sol: b.sol, usdc: usdc(b.usdc), owed: usdc(b.owed), minuteAccount: usdc(b.custody), feePayerSol: b.payerSol },
134
+ today: usdc(today),
135
+ };
136
+ }
137
+ const todayResult = async (h) => (await realizedToday({ ...h, game: 'knockout' })) + (await realizedToday({ ...h, game: 'minute' }));
138
+ // ---- trading commands: paper, dry run, or live; every one through the risk guard ----
139
+ export async function open(ctx, a) {
140
+ const market = marketArg(a);
141
+ const intent = intentOf(a);
142
+ const game = intent.kind === 'round' ? 'minute' : 'knockout';
143
+ if (a.paper === true) {
144
+ const h = await handles(ctx, { limits: true }, game);
145
+ const { paper, save } = await paperAccount(h, market);
146
+ await markPaper(ctx, paper);
147
+ check(intent, paper.book(paper.realizedSince(dayStart() * 1000)), h);
148
+ const [id] = paper.place([intent], Date.now());
149
+ await markPaper(ctx, paper); // the next price fills the order
150
+ save();
151
+ const p = paper.open.find((x) => x.id === id);
152
+ return { paper: true, id, market, side: intent.side, stake: usdc(intent.stake), entryPrice: p?.entry ?? null, usdc: usdc(paper.cash) };
153
+ }
154
+ const h = await handles(ctx, { limits: true, key: a.dryRun === true ? 'address' : 'signer' }, game);
155
+ if (a.dryRun !== true)
156
+ needSigner(ctx, h);
157
+ const live = new Live(h, market);
158
+ await live.refresh();
159
+ check(intent, live.book(await todayResult(h)), h);
160
+ if (a.dryRun === true) {
161
+ const bundle = intent.kind === 'round'
162
+ ? await h.minute.build.round({ market, side: intent.side, usd: intent.stake })
163
+ : await h.knockout.build.open({ market, side: intent.side, usd: intent.stake, target: a.target ?? 0, timer: a.timer ?? 0 });
164
+ const s = await transact(h.sender, bundle, false);
165
+ return { dryRun: true, simulated: true, units: s.units, bytes: s.bytes };
166
+ }
167
+ const sent = await sendBatch(h, market, [intent]);
168
+ log('sent', sent);
169
+ return sent;
170
+ }
171
+ export async function close(ctx, a) {
172
+ if (a.id === undefined || !/^\d+$/.test(a.id))
173
+ throw bad('id must be a position id (its seq)');
174
+ if (a.paper === true) {
175
+ const h = await handles(ctx, {});
176
+ const { paper, save } = await paperAccount(h, a.market ?? h.cfg.market);
177
+ await markPaper(ctx, paper);
178
+ paper.place([{ kind: 'close', id: a.id }], Date.now());
179
+ const closed = await markPaper(ctx, paper); // the next price prices the close
180
+ save();
181
+ const c = closed.find((x) => x.id === a.id);
182
+ return { paper: true, id: a.id, closed: c !== undefined, ...(c === undefined ? {} : { reason: c.reason, exitPrice: c.exit, payout: usdc(c.payout), pnl: usdc(c.pnl) }) };
183
+ }
184
+ const h = await handles(ctx, { key: a.dryRun === true ? 'address' : 'signer' });
185
+ if (a.dryRun === true) {
186
+ const s = await transact(h.sender, await h.knockout.build.close(BigInt(a.id)), false);
187
+ return { dryRun: true, simulated: true, units: s.units, bytes: s.bytes };
188
+ }
189
+ needSigner(ctx, h);
190
+ const sent = await h.knockout.close(BigInt(a.id));
191
+ log('sent', { what: 'close', id: a.id, ...sent });
192
+ return { id: a.id, ...sent };
193
+ }
194
+ /** The risk guard, as the bot applies it: one refusal names the limit. */
195
+ function check(intent, book, h) {
196
+ const v = guard([intent], book, h.cfg.limits);
197
+ if (v.refused.length > 0)
198
+ throw new Refusal('risk', 'RISK_LIMIT', v.refused[0].why);
199
+ }
200
+ function needSigner(ctx, h) {
201
+ if (h.sender.signer === null) {
202
+ throw new Refusal('session', 'NO_SESSION', ctx.agent ? 'trading from an agent needs a session key: run `wheelman session start` as the owner' : 'there is no key to sign with');
203
+ }
204
+ }
205
+ // ---- sessions ----
206
+ const durationS = (text) => {
207
+ const m = /^(\d+)([smhd]?)$/.exec(text ?? '24h');
208
+ if (m === null)
209
+ throw bad('expires must be a duration like 3600, 30m, 24h or 7d');
210
+ return Number(m[1]) * { '': 1, s: 1, m: 60, h: 3600, d: 86_400 }[m[2]];
211
+ };
212
+ export async function sessionStartCommand(ctx, a) {
213
+ const h = await handles(ctx, { key: a.dryRun === true ? 'address' : 'owner' });
214
+ let allowance;
215
+ try {
216
+ allowance = parseUsdc(a.allowance ?? '');
217
+ }
218
+ catch {
219
+ throw bad('allowance must be an amount of USDC, like 20');
220
+ }
221
+ const ownerSender = { ...h.sender, payer: h.owner, signer: h.cfg.wallet };
222
+ const maxStake = (await h.knockout.market(h.cfg.market)).stake.max;
223
+ const r = await sessionStart(ownerSender, h.owner, h.cfg.sessionPath, { allowance, seconds: durationS(a.expires), fuelSol: a.fuel ?? 0.01 }, a.dryRun !== true, maxStake);
224
+ return {
225
+ ...r, allowance: usdc(r.allowance),
226
+ agentEnv: a.dryRun === true ? null : { OWNER: r.owner, SESSION_KEYPAIR_PATH: h.cfg.sessionPath },
227
+ };
228
+ }
229
+ export async function sessionStatusCommand(ctx) {
230
+ const h = await handles(ctx, { key: 'address' });
231
+ const s = await sessionStatus(h.rpc, h.owner, h.cfg.session?.publicKey ?? null);
232
+ return { ...s, remaining: s.remaining === null ? null : usdc(s.remaining) };
233
+ }
234
+ export async function sessionEndCommand(ctx, a) {
235
+ const h = await handles(ctx, { key: a.dryRun === true ? 'address' : 'owner' });
236
+ return sessionEnd({ ...h.sender, payer: h.owner, signer: h.cfg.wallet }, h.owner, h.cfg.session, h.cfg.sessionPath, a.dryRun !== true);
237
+ }
238
+ // ---- the bot ----
239
+ export async function run(ctx, a, signal) {
240
+ if (a.strategy !== undefined)
241
+ ctx.env = { ...ctx.env, STRATEGY: a.strategy };
242
+ const pre = parseConfig(ctx.env, { strategy: true, limits: true }, ctx.strategies);
243
+ const game = pre.strategy.game;
244
+ const live = a.paper !== true && a.dryRun !== true;
245
+ if (live && pre.priceSource === 'replay')
246
+ throw new Refusal('config', 'BAD_CONFIG', 'a replay is for paper mode: set PRICE_SOURCE=coinbase to trade live');
247
+ const h = await handles(ctx, { strategy: true, limits: true, key: live ? 'signer' : a.dryRun === true ? 'address' : undefined }, game);
248
+ const { cfg } = h;
249
+ log('ready', { mode: a.paper ? 'paper' : a.dryRun ? 'dry-run' : 'live', strategy: cfg.strategy.id, market: cfg.market, rpc: h.rpc.host, owner: cfg.owner?.toBase58() ?? 'none' });
250
+ if (a.dryRun === true)
251
+ return dryRun(h);
252
+ const source = ctx.prices ?? priceSource(cfg.priceSource, cfg.replayFile, ctx.env);
253
+ const loop = { market: cfg.market, strategy: cfg.strategy, params: cfg.params, limits: cfg.limits, source, signal };
254
+ if (a.paper === true) {
255
+ // A replay runs on a fresh paper account; a live price runs on the one the paper commands use.
256
+ const { paper, save } = await paperAccount(h, cfg.market, cfg.priceSource === 'replay');
257
+ await trade({ ...loop, broker: paper, todayPnl: paper.realizedSince(dayStart() * 1000) });
258
+ save();
259
+ const s = paper.summary();
260
+ const summary = { ...s, result: usdc(s.result), usdc: usdc(s.usdc) };
261
+ log('paper-summary', summary);
262
+ return summary;
263
+ }
264
+ const broker = new Live(h, cfg.market);
265
+ await broker.refresh();
266
+ const today = await realizedToday(h);
267
+ const b = broker.book(today);
268
+ log('state', { open: b.open, usdc: usdc(b.free), sol: b.sol, today: usdc(today) });
269
+ await watch(cfg, watched(h), () => broker.wake(), signal);
270
+ await trade({ ...loop, broker, todayPnl: today });
271
+ return { stopped: true };
272
+ }
273
+ /** The accounts whose change wakes the bot. */
274
+ const watched = (h) => h.game === 'minute' ? [h.minute.book, h.minute.player, h.minute.custody] : [traderPda(h.owner).address, ata(h.owner, USDC_MINT)];
275
+ /** Build and simulate the transactions this configuration sends. Nothing is sent. */
276
+ async function dryRun(h) {
277
+ const { cfg } = h;
278
+ const held = await heldBy(h);
279
+ const stake = cfg.params.stake_usdc ?? 1000000n;
280
+ const order = (side) => ({ market: cfg.market, side, usd: stake, target: cfg.params.take_profit_x ?? 0, timer: cfg.params.time_stop_s ?? 0 });
281
+ const out = [];
282
+ const attempt = async (what, build) => {
283
+ try {
284
+ const s = await transact(h.sender, await build(), false);
285
+ out.push({ what, simulated: true, units: s.units, bytes: s.bytes });
286
+ }
287
+ catch (e) {
288
+ if (!(e instanceof Refusal))
289
+ throw e;
290
+ out.push({ what, simulated: false, code: e.code, message: e.message });
291
+ }
292
+ log('simulated', out.at(-1));
293
+ };
294
+ if (h.game === 'minute')
295
+ await attempt('round', () => h.minute.build.round({ market: cfg.market, side: 'long', usd: stake }));
296
+ else {
297
+ const straddle = cfg.strategy.id === 'knockout-straddle';
298
+ await attempt(straddle ? 'open long and short' : 'open', () => h.knockout.build.open(straddle ? [order('long'), order('short')] : order('long')));
299
+ const live = held.find((p) => p.market === cfg.market && p.entry !== null);
300
+ await attempt(`close ${live?.id ?? '(none open: a seq that does not exist)'}`, () => h.knockout.build.close(BigInt(live?.id ?? '999999999')));
301
+ }
302
+ if ((await collect(h.sender, h.owner, false)) !== null)
303
+ out.push({ what: 'collect', simulated: true });
304
+ return out;
305
+ }
306
+ // ---- the paper account ----
307
+ async function paperAccount(h, market, fresh = false) {
308
+ const venue = await h.venue(market);
309
+ const path = join(h.cfg.stateDir, 'paper.json');
310
+ const price = (i) => termsFor(venue, i.kind === 'round' ? 'minute' : 'knockout', i.side, i.stake, i.kind === 'open' ? i.takeProfitX : 0, i.kind === 'open' ? i.timerS : 0);
311
+ const paper = fresh ? new Paper(h.cfg.paperUsdc, market, price) : Paper.load(path, h.cfg.paperUsdc, market, price);
312
+ return { paper, save: () => (fresh ? undefined : paper.save(path)) };
313
+ }
314
+ /** One price per market the paper account holds, now: it fills orders and ends what it ends. */
315
+ async function markPaper(ctx, paper) {
316
+ ctx.prices ??= priceSource(ctx.env.PRICE_SOURCE ?? 'coinbase', ctx.env.REPLAY_FILE, ctx.env);
317
+ const closed = [];
318
+ for (const m of new Set([paper.market, ...paper.open.map((p) => p.market)])) {
319
+ const t = await ctx.prices.latest(m);
320
+ // A price read now is later than any order or close placed before it.
321
+ closed.push(...paper.mark({ ...t, time: Math.max(t.time, Date.now() + 1) }));
322
+ }
323
+ return closed;
324
+ }
325
+ function paperView(paper) {
326
+ return {
327
+ paper: true, usdc: usdc(paper.cash),
328
+ positions: paper.open.map((p) => ({ id: p.id, game: p.game, market: p.market, side: p.side, stake: usdc(p.stake), entryPrice: p.entry, closing: p.closing })),
329
+ closed: paper.closed.slice(-20).map((c) => ({ ...c, stake: usdc(c.stake), payout: usdc(c.payout), pnl: usdc(c.pnl) })),
330
+ today: usdc(paper.realizedSince(dayStart() * 1000)),
331
+ };
332
+ }
package/dist/config.js ADDED
@@ -0,0 +1,256 @@
1
+ // Configuration: environment variables only (`.env` on a laptop, the host's settings elsewhere).
2
+ // `.env.example` documents every variable. A bad value is refused here, before any RPC call.
3
+ import { readFileSync } from 'node:fs';
4
+ import { Keypair, PublicKey } from '@solana/web3.js';
5
+ import { parseUsdc } from '@rekt-trading/1000x';
6
+ import { Refusal } from "./errors.js";
7
+ import { addSecret } from "./journal.js";
8
+ import { PRICE_SOURCES, pythFeeds, pythKey, resolveSourceName } from "./prices.js";
9
+ export const MARKETS = ['BTC', 'ETH', 'SOL', 'XRP', 'XAU'];
10
+ export class ConfigError extends Refusal {
11
+ constructor(message) {
12
+ super('config', 'BAD_CONFIG', message);
13
+ }
14
+ }
15
+ export function parseConfig(env, needs, strategies) {
16
+ const problems = [];
17
+ const get = (name) => {
18
+ const v = env[name]?.trim();
19
+ return v === undefined || v === '' ? undefined : v;
20
+ };
21
+ const url = (name, schemes) => {
22
+ const v = get(name);
23
+ if (v === undefined)
24
+ return undefined;
25
+ addSecret(v);
26
+ try {
27
+ const u = new URL(v);
28
+ const local = u.hostname === 'localhost' && schemes.map((s) => s.replace('s:', ':')).includes(u.protocol);
29
+ if (!schemes.includes(u.protocol) && !local)
30
+ problems.push(`${name} must start with ${schemes.join(' or ')}`);
31
+ }
32
+ catch {
33
+ problems.push(`${name} is not a URL`);
34
+ }
35
+ return v;
36
+ };
37
+ const num = (name, def, min, max) => {
38
+ const v = get(name);
39
+ const n = v === undefined ? def : Number(v);
40
+ if (!Number.isFinite(n) || n < min || n > max)
41
+ problems.push(`${name} must be a number from ${min} to ${max}`);
42
+ return n;
43
+ };
44
+ const usdc = (name, def) => {
45
+ const v = get(name) ?? def;
46
+ if (v === undefined) {
47
+ if (needs.limits)
48
+ problems.push(`${name} is required`);
49
+ return 0n;
50
+ }
51
+ try {
52
+ const n = parseUsdc(v);
53
+ if (n < 0n)
54
+ throw new Error('negative');
55
+ return n;
56
+ }
57
+ catch {
58
+ problems.push(`${name} must be an amount of USDC, like 1.50`);
59
+ return 0n;
60
+ }
61
+ };
62
+ const address = (name) => {
63
+ const v = get(name);
64
+ if (v === undefined)
65
+ return null;
66
+ try {
67
+ return new PublicKey(v);
68
+ }
69
+ catch {
70
+ problems.push(`${name} is not an address`);
71
+ return null;
72
+ }
73
+ };
74
+ const keypair = (pathName, secretName) => {
75
+ const secret = secretName === undefined ? undefined : get(secretName);
76
+ addSecret(secret);
77
+ const path = get(pathName);
78
+ try {
79
+ if (path !== undefined)
80
+ return loadKeypair(readFileSync(path, 'utf8'));
81
+ if (secret !== undefined)
82
+ return loadKeypair(secret);
83
+ }
84
+ catch (e) {
85
+ problems.push(`${secretName !== undefined && path === undefined ? secretName : pathName} could not be read: ${e.message}`);
86
+ }
87
+ return null;
88
+ };
89
+ const rpcUrl = url('RPC_URL', ['https:']);
90
+ if (rpcUrl === undefined)
91
+ problems.push('RPC_URL is required: an HTTPS JSON-RPC endpoint from any provider');
92
+ const wsUrl = url('RPC_WS_URL', ['wss:']) ?? (rpcUrl ?? '').replace(/^http/, 'ws');
93
+ const grpcUrl = url('GRPC_URL', ['https:', 'http:']) ?? null;
94
+ const grpcToken = get('GRPC_TOKEN') ?? null;
95
+ addSecret(grpcToken ?? undefined);
96
+ const sendUrl = url('SEND_URL', ['https:']) ?? rpcUrl ?? '';
97
+ const fallbackUrl = url('RPC_FALLBACK_URL', ['https:']) ?? null;
98
+ const maxRps = num('RPC_MAX_RPS', 10, 1, 500);
99
+ const tipLamports = num('SEND_TIP_LAMPORTS', 0, 0, 10_000_000);
100
+ const tipAccount = address('SEND_TIP_ACCOUNT');
101
+ if (tipLamports > 0 && tipAccount === null)
102
+ problems.push('SEND_TIP_LAMPORTS needs SEND_TIP_ACCOUNT');
103
+ const maxPriorityFee = num('MAX_PRIORITY_FEE', 100_000, 0, 10_000_000);
104
+ // The keys. Never printed; only addresses are shown.
105
+ const wallet = keypair('KEYPAIR_PATH', 'WALLET_SECRET_KEY');
106
+ const sessionPath = get('SESSION_KEYPAIR_PATH') ?? 'wallets/session-keypair.json';
107
+ const session = get('SESSION_KEYPAIR_PATH') === undefined ? null : keypair('SESSION_KEYPAIR_PATH');
108
+ const named = address('OWNER');
109
+ const owner = wallet?.publicKey ?? named;
110
+ if (wallet !== null && named !== null && !named.equals(wallet.publicKey))
111
+ problems.push('OWNER is not the address of the configured wallet');
112
+ if (session !== null && owner === null)
113
+ problems.push('a session key needs OWNER: the address of the wallet it trades for');
114
+ if (needs.key === 'owner' && wallet === null)
115
+ problems.push('this command needs the owner\'s wallet: set KEYPAIR_PATH or WALLET_SECRET_KEY');
116
+ if (needs.key === 'signer' && wallet === null && session === null)
117
+ problems.push('set KEYPAIR_PATH or WALLET_SECRET_KEY, or a session key (SESSION_KEYPAIR_PATH and OWNER)');
118
+ if (needs.key === 'address' && owner === null)
119
+ problems.push('set OWNER (an address), or a wallet');
120
+ const market = (get('MARKET') ?? 'BTC').toUpperCase();
121
+ if (!MARKETS.includes(market))
122
+ problems.push(`MARKET must be one of ${MARKETS.join(', ')}`);
123
+ const priceSource = get('PRICE_SOURCE') ?? 'coinbase';
124
+ const replayFile = get('REPLAY_FILE');
125
+ if (!PRICE_SOURCES.includes(priceSource))
126
+ problems.push(`PRICE_SOURCE must be ${PRICE_SOURCES.join(', ')}`);
127
+ if (priceSource === 'replay' && replayFile === undefined)
128
+ problems.push('PRICE_SOURCE=replay needs REPLAY_FILE');
129
+ // The caller's own Pyth key is optional. Whatever way it is given, it is registered so no log line can carry it.
130
+ let hasPythKey = false;
131
+ try {
132
+ const key = pythKey(env);
133
+ hasPythKey = key !== null;
134
+ addSecret(key ?? undefined);
135
+ }
136
+ catch (e) {
137
+ problems.push(e.message);
138
+ }
139
+ try {
140
+ pythFeeds(get('PYTH_FEEDS'));
141
+ }
142
+ catch (e) {
143
+ problems.push(e.message);
144
+ }
145
+ if (priceSource === 'pyth' && !hasPythKey && problems.every((p) => !p.startsWith('PYTH_API_KEY_FILE'))) {
146
+ problems.push('PRICE_SOURCE=pyth needs your Pyth key: set PYTH_API_KEY, or PYTH_API_KEY_FILE');
147
+ }
148
+ const exchangeFeed = resolveSourceName(PRICE_SOURCES.includes(priceSource) ? priceSource : 'replay', hasPythKey ? { PYTH_API_KEY: 'set' } : {}) === 'coinbase';
149
+ const limits = {
150
+ maxStake: usdc('MAX_STAKE_USDC', '1'),
151
+ maxOpen: num('MAX_OPEN', 2, 1, 12),
152
+ dailyLoss: usdc('DAILY_LOSS_USDC', undefined),
153
+ minBalance: usdc('MIN_BALANCE_USDC', '0'),
154
+ };
155
+ if (needs.limits && get('DAILY_LOSS_USDC') !== undefined && limits.dailyLoss === 0n)
156
+ problems.push('DAILY_LOSS_USDC must be above 0: the bot trades only with a loss stop');
157
+ if (limits.dailyLoss > 0n && limits.maxStake > limits.dailyLoss)
158
+ problems.push('MAX_STAKE_USDC is above DAILY_LOSS_USDC, so no trade could open');
159
+ let strategy = null;
160
+ const params = {};
161
+ if (needs.strategy) {
162
+ const id = get('STRATEGY');
163
+ strategy = id === undefined ? null : (strategies.get(id) ?? null);
164
+ if (id === undefined)
165
+ problems.push(`STRATEGY is required: one of ${[...strategies.keys()].join(', ')}`);
166
+ else if (strategy === null)
167
+ problems.push(`STRATEGY ${id} does not exist: use one of ${[...strategies.keys()].join(', ')}`);
168
+ if (strategy?.game === 'knockout' && exchangeFeed && market === 'XAU') {
169
+ problems.push('the exchange feed has no XAU price; set PRICE_SOURCE=pyth with your Pyth key (PYTH_API_KEY), use replay, or add an adapter in src/prices.ts');
170
+ }
171
+ }
172
+ if (strategy !== null) {
173
+ const known = new Set(Object.keys(strategy.params).map((k) => `PARAM_${k.toUpperCase()}`));
174
+ for (const name of Object.keys(env)) {
175
+ if (name.startsWith('PARAM_') && !known.has(name))
176
+ problems.push(`${name} is not a parameter of ${strategy.id}`);
177
+ }
178
+ for (const [key, p] of Object.entries(strategy.params)) {
179
+ const name = `PARAM_${key.toUpperCase()}`;
180
+ const r = parseParam(name, p, get(name) ?? p.default);
181
+ if ('problem' in r)
182
+ problems.push(r.problem);
183
+ else {
184
+ params[key] = r.value;
185
+ if (typeof r.value === 'bigint' && r.value > limits.maxStake)
186
+ problems.push(`${name} is above MAX_STAKE_USDC`);
187
+ }
188
+ }
189
+ if (strategy.id === 'knockout-straddle') {
190
+ if (limits.maxOpen < 2)
191
+ problems.push('knockout-straddle opens two positions: MAX_OPEN must be at least 2');
192
+ const each = params.stake_usdc;
193
+ if (typeof each === 'bigint' && limits.dailyLoss > 0n && 2n * each > limits.dailyLoss) {
194
+ problems.push('knockout-straddle stakes two sides: DAILY_LOSS_USDC must be at least twice PARAM_STAKE_USDC');
195
+ }
196
+ }
197
+ }
198
+ const paperUsdc = usdc('PAPER_USDC', '100');
199
+ if (problems.length > 0)
200
+ throw new ConfigError(`the configuration is refused:\n - ${problems.join('\n - ')}`);
201
+ return {
202
+ rpcUrl: rpcUrl, wsUrl, grpcUrl, grpcToken, sendUrl, fallbackUrl, maxRps, maxPriorityFee,
203
+ tip: tipLamports > 0 && tipAccount !== null ? { lamports: tipLamports, account: tipAccount } : null,
204
+ wallet, session, sessionPath, owner, market, strategy, params, priceSource, replayFile, limits, paperUsdc,
205
+ stateDir: get('STATE_DIR') ?? '.wheelman',
206
+ };
207
+ }
208
+ /** One strategy parameter from its text, inside its bounds. */
209
+ export function parseParam(name, p, text) {
210
+ if (p.kind === 'choice')
211
+ return p.choices.includes(text) ? { value: text } : { problem: `${name} must be one of ${p.choices.join(', ')}` };
212
+ if (p.kind === 'usdc') {
213
+ try {
214
+ const v = parseUsdc(text);
215
+ if (v >= parseUsdc(p.min) && v <= parseUsdc(p.max))
216
+ return { value: v };
217
+ }
218
+ catch {
219
+ // refused below
220
+ }
221
+ return { problem: `${name} must be an amount of USDC from ${p.min} to ${p.max}` };
222
+ }
223
+ const v = Number(text);
224
+ if (text !== '' && Number.isFinite(v) && ((p.zeroOff === true && v === 0) || (v >= p.min && v <= p.max)))
225
+ return { value: v };
226
+ return { problem: `${name} must be a number from ${p.min} to ${p.max}${p.zeroOff === true ? ', or 0 for none' : ''}` };
227
+ }
228
+ /** A keypair from a Solana keypair file (a JSON array of 64 numbers) or a base58 secret key. */
229
+ export function loadKeypair(text) {
230
+ try {
231
+ const t = text.trim();
232
+ const bytes = t.startsWith('[') ? Uint8Array.from(JSON.parse(t)) : base58Secret(t);
233
+ return Keypair.fromSecretKey(bytes);
234
+ }
235
+ catch {
236
+ // Never pass the parser's message on: it can quote the secret.
237
+ throw new Error('it is not a keypair file (64 numbers) or a base58 secret key');
238
+ }
239
+ }
240
+ /** A 64-byte secret key from base58 (the form wallets export). */
241
+ function base58Secret(text) {
242
+ const alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
243
+ let n = 0n;
244
+ for (const ch of text) {
245
+ const digit = alphabet.indexOf(ch);
246
+ if (digit < 0)
247
+ throw new Error('not base58');
248
+ n = n * 58n + BigInt(digit);
249
+ }
250
+ const out = new Uint8Array(64);
251
+ for (let i = 63; i >= 0; i--, n >>= 8n)
252
+ out[i] = Number(n & 0xffn);
253
+ if (n !== 0n)
254
+ throw new Error('longer than 64 bytes');
255
+ return out;
256
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,24 @@
1
+ // One error type for every refusal, and the one JSON envelope the CLI and the MCP server print.
2
+ // { ok: true, data } or { ok: false, error: { category, code, message, retryable } }
3
+ // `retryable` is true only where sending the same request again cannot open a second position.
4
+ export class Refusal extends Error {
5
+ category;
6
+ code;
7
+ retryable;
8
+ /** How long a loop waits before it tries again, in ms. */
9
+ waitMs;
10
+ constructor(category, code, message, retryable = false, waitMs = retryable ? 30_000 : 600_000) {
11
+ super(message);
12
+ this.category = category;
13
+ this.code = code;
14
+ this.retryable = retryable;
15
+ this.waitMs = waitMs;
16
+ }
17
+ }
18
+ export function envelopeOf(e) {
19
+ if (e instanceof Refusal)
20
+ return { ok: false, error: { category: e.category, code: e.code, message: e.message, retryable: e.retryable } };
21
+ return { ok: false, error: { category: 'internal', code: 'UNEXPECTED', message: e instanceof Error ? e.message : String(e), retryable: false } };
22
+ }
23
+ /** JSON with bigint as decimal text. */
24
+ export const toJson = (value, indent) => JSON.stringify(value, (_k, v) => (typeof v === 'bigint' ? v.toString() : v), indent);
@@ -0,0 +1,63 @@
1
+ // The log. Every event is one JSON line in JOURNAL_PATH and one short line on stdout. It is a log
2
+ // only: the bot reads its state from the chain. Every line is redacted first: no key, token or
3
+ // keyed URL is ever written.
4
+ import { appendFileSync, mkdirSync } from 'node:fs';
5
+ import { dirname } from 'node:path';
6
+ const secrets = new Set();
7
+ let journalPath = null;
8
+ /** Human log lines go to stdout, or to stderr when stdout carries JSON (-o json, the MCP server). */
9
+ let toStderr = false;
10
+ export function logToStderr(on) {
11
+ toStderr = on;
12
+ }
13
+ export function setJournal(path) {
14
+ journalPath = path;
15
+ if (path !== null)
16
+ mkdirSync(dirname(path), { recursive: true });
17
+ }
18
+ /** Remember a value that must never be written: a token, a key, or a URL that can carry one. */
19
+ export function addSecret(value) {
20
+ if (value === undefined || value === '')
21
+ return;
22
+ secrets.add(value);
23
+ try {
24
+ const u = new URL(value);
25
+ if (u.search !== '')
26
+ secrets.add(u.search.slice(1));
27
+ if (u.pathname.length > 1)
28
+ secrets.add(u.pathname);
29
+ }
30
+ catch {
31
+ // not a URL: the value itself is enough
32
+ }
33
+ }
34
+ export function redact(text) {
35
+ let out = text;
36
+ for (const s of [...secrets].sort((a, b) => b.length - a.length)) {
37
+ if (s.length >= 4)
38
+ out = out.split(s).join('[redacted]');
39
+ }
40
+ return out.replace(/([?&](?:api[-_]?key|token|key|c)=)[^&\s"'#]+/gi, '$1[redacted]');
41
+ }
42
+ /** The host of a URL, which is all a log line may say about an endpoint. */
43
+ export const hostOf = (url) => {
44
+ try {
45
+ return new URL(url).host;
46
+ }
47
+ catch {
48
+ return 'an invalid URL';
49
+ }
50
+ };
51
+ export function log(kind, fields = {}) {
52
+ const line = redact(JSON.stringify({ time: new Date().toISOString(), ...fields, kind }, (_k, v) => typeof v === 'bigint' ? v.toString() : v));
53
+ if (journalPath !== null)
54
+ appendFileSync(journalPath, `${line}\n`);
55
+ const rest = Object.entries(fields)
56
+ .map(([k, v]) => `${k}=${typeof v === 'object' ? JSON.stringify(v, (_k, x) => (typeof x === 'bigint' ? x.toString() : x)) : String(v)}`)
57
+ .join(' ');
58
+ const human = redact(`${new Date().toISOString().slice(11, 19)} ${kind} ${rest}`);
59
+ if (toStderr)
60
+ console.error(human);
61
+ else
62
+ console.log(human);
63
+ }