@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.
- package/.env.example +75 -0
- package/LICENSE +191 -0
- package/README.md +287 -2
- package/dist/account.js +162 -0
- package/dist/cli.js +163 -0
- package/dist/client.js +245 -0
- package/dist/commands.js +332 -0
- package/dist/config.js +256 -0
- package/dist/errors.js +24 -0
- package/dist/journal.js +63 -0
- package/dist/mcp.js +117 -0
- package/dist/minute.js +140 -0
- package/dist/paper.js +220 -0
- package/dist/prices.js +374 -0
- package/dist/risk.js +60 -0
- package/dist/rpc.js +321 -0
- package/dist/runner.js +189 -0
- package/dist/setup.js +133 -0
- package/dist/strategies/index.js +34 -0
- package/dist/strategies/knockout.js +111 -0
- package/dist/strategies/minute.js +53 -0
- package/dist/strategies/template.js +24 -0
- package/package.json +57 -4
- package/skills/wheelman/SKILL.md +61 -0
package/dist/account.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// The owner's wallet beyond trading: balances, collecting what is owed, session keys for agents,
|
|
2
|
+
// and a local cache of settled transactions (they never change, so each is fetched once).
|
|
3
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { Keypair, PublicKey, SystemProgram } from '@solana/web3.js';
|
|
6
|
+
import { MAX_DELEGATE_DURATION_S, MAX_DELEGATE_WINDOW_S, MIN_DELEGATE_DURATION_S, authorizeSession, configPda, decodeConfig, decodeTradeDelegate, decodeTraderAccount, decodeVault, delegatePda, endSession, ix, sessionStanding, toBase58, toHex, traderPda, vaultPda, } from '@rekt-trading/1000x';
|
|
7
|
+
import { minuteConfigPda, minuteIx, minutePlayerPda, minutePlayerTokenPda, minuteTraderBookFor } from '@rekt-trading/1000x'; // Minute's API ships in the same package
|
|
8
|
+
import { ata, bundleOf, tokenAmount } from "./client.js";
|
|
9
|
+
import { Refusal } from "./errors.js";
|
|
10
|
+
import { CLOCK, transact } from "./rpc.js";
|
|
11
|
+
export const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');
|
|
12
|
+
export async function balances(rpc, owner, payer = owner) {
|
|
13
|
+
const minuteBook = minuteTraderBookFor(owner, minutePlayerPda(owner).bump).positions;
|
|
14
|
+
const custody = minutePlayerTokenPda(minutePlayerPda(owner).address).address;
|
|
15
|
+
const [w, t, b, mb, c, p] = await rpc.conn.getMultipleAccountsInfo([owner, ata(owner, USDC_MINT), traderPda(owner).address, minuteBook, custody, payer], 'confirmed');
|
|
16
|
+
const pending = (a) => (a === null ? 0n : decodeTraderAccount(new Uint8Array(a.data)).pendingPayout);
|
|
17
|
+
return { sol: (w?.lamports ?? 0) / 1e9, usdc: tokenAmount(t?.data), owed: pending(b) + pending(mb), custody: tokenAmount(c?.data), payerSol: (p?.lamports ?? 0) / 1e9 };
|
|
18
|
+
}
|
|
19
|
+
/** Claim what the venue holds for the wallet, and sweep its Minute account. Anyone may send both. */
|
|
20
|
+
export async function collect(s, owner, send) {
|
|
21
|
+
const player = minutePlayerPda(owner);
|
|
22
|
+
const minuteBook = minuteTraderBookFor(owner, player.bump).positions;
|
|
23
|
+
const custody = minutePlayerTokenPda(player.address).address;
|
|
24
|
+
const [cfg, vault, b, mb, c] = await s.rpc.conn.getMultipleAccountsInfo([configPda().address, vaultPda().address, traderPda(owner).address, minuteBook, custody], 'confirmed');
|
|
25
|
+
const books = [[traderPda(owner).address, b], [minuteBook, mb]].flatMap(([address, account]) => {
|
|
26
|
+
const book = account === null ? null : decodeTraderAccount(new Uint8Array(account.data));
|
|
27
|
+
return book !== null && book.pendingPayout > 0n ? [{ address, destination: book.payoutDestination }] : [];
|
|
28
|
+
});
|
|
29
|
+
const sweep = tokenAmount(c?.data) > 0n;
|
|
30
|
+
if (books.length === 0 && !sweep)
|
|
31
|
+
return null;
|
|
32
|
+
if (cfg === null || vault === null)
|
|
33
|
+
throw new Refusal('venue', 'VENUE_MISSING', 'the venue config or vault is missing');
|
|
34
|
+
const config = decodeConfig(new Uint8Array(cfg.data));
|
|
35
|
+
const vaultToken = decodeVault(new Uint8Array(vault.data)).tokenAccount;
|
|
36
|
+
const built = [];
|
|
37
|
+
for (const { address, destination } of books) {
|
|
38
|
+
built.push(ix.claimPayout({ payer: toHex(s.payer), owner_token: destination, positions: toHex(address), vault: toHex(vaultPda().address), vault_token: vaultToken }));
|
|
39
|
+
}
|
|
40
|
+
if (sweep) {
|
|
41
|
+
built.push(minuteIx.sweep({
|
|
42
|
+
payer: toHex(s.payer), player: toHex(player.address), player_token: toHex(custody), destination: toHex(ata(owner, USDC_MINT)),
|
|
43
|
+
config: toHex(minuteConfigPda().address), knockout_config: toHex(configPda().address), knockout_vault: toHex(vaultPda().address),
|
|
44
|
+
knockout_vault_token: vaultToken, knockout_protocol_token: config.treasury,
|
|
45
|
+
}));
|
|
46
|
+
}
|
|
47
|
+
return { signature: (await transact(s, bundleOf(built), send)).signature };
|
|
48
|
+
}
|
|
49
|
+
function checkSessionPlan(p) {
|
|
50
|
+
if (p.allowance <= 0n)
|
|
51
|
+
throw new Refusal('config', 'BAD_ALLOWANCE', 'the allowance must be above 0');
|
|
52
|
+
if (p.seconds < MIN_DELEGATE_DURATION_S || p.seconds > MAX_DELEGATE_DURATION_S) {
|
|
53
|
+
throw new Refusal('config', 'BAD_EXPIRY', `the expiry must be from ${MIN_DELEGATE_DURATION_S} to ${MAX_DELEGATE_DURATION_S} seconds`);
|
|
54
|
+
}
|
|
55
|
+
if (!(p.fuelSol > 0 && p.fuelSol <= 1))
|
|
56
|
+
throw new Refusal('config', 'BAD_FUEL', 'the fuel must be above 0 and at most 1 SOL');
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Authorise a session key: one transaction, signed by the owner. It creates the owner's book when
|
|
60
|
+
* there is none, authorises the key (expiry, spend window, SPL allowance) and sends it SOL for fees.
|
|
61
|
+
* The key is written (mode 600) BEFORE the send, and removed only when the program refuses.
|
|
62
|
+
*/
|
|
63
|
+
export async function sessionStart(s, owner, path, plan, send, maxStake) {
|
|
64
|
+
checkSessionPlan(plan);
|
|
65
|
+
if (send && existsSync(path))
|
|
66
|
+
throw new Refusal('session', 'SESSION_EXISTS', `${path} exists: end that session first (wheelman session end)`);
|
|
67
|
+
const key = Keypair.generate();
|
|
68
|
+
const me = owner;
|
|
69
|
+
const traderToken = ata(me, USDC_MINT);
|
|
70
|
+
const [b, v] = await s.rpc.conn.getMultipleAccountsInfo([traderPda(me).address, vaultPda().address], 'confirmed');
|
|
71
|
+
const built = [];
|
|
72
|
+
if (b === null) {
|
|
73
|
+
if (v === null)
|
|
74
|
+
throw new Refusal('venue', 'VENUE_MISSING', 'the venue vault is missing');
|
|
75
|
+
built.push(ix.initTraderAccount({
|
|
76
|
+
trader: toHex(me), payer: toHex(me), positions: toHex(traderPda(me).address), vault: toHex(vaultPda().address),
|
|
77
|
+
vault_token: decodeVault(new Uint8Array(v.data)).tokenAccount, payout_destination: toHex(traderToken),
|
|
78
|
+
}, 12));
|
|
79
|
+
}
|
|
80
|
+
built.push(...authorizeSession({
|
|
81
|
+
owner: toHex(me), delegateKey: toHex(key.publicKey), delegate: toHex(delegatePda(me).address), traderToken: toHex(traderToken),
|
|
82
|
+
config: toHex(configPda().address), restrictions: 0, allowance: plan.allowance, maxCollateral: maxStake,
|
|
83
|
+
// The SPL allowance is what bounds the session. The program also asks the spend window to admit
|
|
84
|
+
// at least one maximum stake, so the window is the larger of the two.
|
|
85
|
+
terms: {
|
|
86
|
+
durationS: plan.seconds, windowSeconds: Math.max(60, Math.min(plan.seconds, MAX_DELEGATE_WINDOW_S)),
|
|
87
|
+
windowLimit: plan.allowance > maxStake ? plan.allowance : maxStake,
|
|
88
|
+
},
|
|
89
|
+
}));
|
|
90
|
+
const bundle = bundleOf(built);
|
|
91
|
+
bundle.instructions.push(SystemProgram.transfer({ fromPubkey: me, toPubkey: key.publicKey, lamports: Math.round(plan.fuelSol * 1e9) }));
|
|
92
|
+
if (send) {
|
|
93
|
+
mkdirSync(join(path, '..'), { recursive: true, mode: 0o700 });
|
|
94
|
+
writeFileSync(path, JSON.stringify(Array.from(key.secretKey)), { mode: 0o600, flag: 'wx' });
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
const sent = await transact(s, bundle, send);
|
|
98
|
+
return { session: key.publicKey.toBase58(), owner: me.toBase58(), allowance: plan.allowance, expiresInS: plan.seconds, fuelSol: plan.fuelSol, signature: sent.signature, units: sent.units, keyFile: send ? path : null };
|
|
99
|
+
}
|
|
100
|
+
catch (e) {
|
|
101
|
+
// Remove the key only on a decoded refusal: a send that may have landed keeps it.
|
|
102
|
+
if (send && e instanceof Refusal && e.category === 'venue')
|
|
103
|
+
rmSync(path, { force: true });
|
|
104
|
+
throw e;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Where a session stands, from the chain. */
|
|
108
|
+
export async function sessionStatus(rpc, owner, key) {
|
|
109
|
+
const [d, t, k, w] = await rpc.conn.getMultipleAccountsInfo([delegatePda(owner).address, ata(owner, USDC_MINT), CLOCK, key ?? owner], 'confirmed');
|
|
110
|
+
const delegate = d === null ? null : decodeTradeDelegate(new Uint8Array(d.data));
|
|
111
|
+
const nowUnix = Buffer.from(k.data).readBigInt64LE(32);
|
|
112
|
+
const s = sessionStanding({ delegate, tokenAccount: t === null ? null : new Uint8Array(t.data), nowUnix });
|
|
113
|
+
return {
|
|
114
|
+
state: s.kind, action: s.action, headline: s.headline,
|
|
115
|
+
session: delegate === null ? null : toBase58(delegate.delegate),
|
|
116
|
+
keyMatches: key === null || delegate === null ? null : toBase58(delegate.delegate) === key.toBase58(),
|
|
117
|
+
remaining: s.session?.remaining ?? null, expiresInS: s.session?.expiresInS ?? null,
|
|
118
|
+
keySol: key === null ? null : (w?.lamports ?? 0) / 1e9,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/** End a session: the owner closes the delegate and drops the allowance; the key's SOL comes back. */
|
|
122
|
+
export async function sessionEnd(s, owner, key, path, send) {
|
|
123
|
+
const me = owner;
|
|
124
|
+
const [d, w] = await s.rpc.conn.getMultipleAccountsInfo([delegatePda(me).address, key?.publicKey ?? me], 'confirmed');
|
|
125
|
+
if (d === null)
|
|
126
|
+
throw new Refusal('session', 'NO_SESSION', 'the owner has no session to end');
|
|
127
|
+
const delegate = decodeTradeDelegate(new Uint8Array(d.data));
|
|
128
|
+
const bundle = bundleOf(endSession({ owner: toHex(me), delegate: toHex(delegatePda(me).address), traderToken: delegate.tokenAccount }));
|
|
129
|
+
const fuel = key === null ? 0 : (w?.lamports ?? 0);
|
|
130
|
+
if (key !== null && fuel > 0)
|
|
131
|
+
bundle.instructions.push(SystemProgram.transfer({ fromPubkey: key.publicKey, toPubkey: me, lamports: fuel }));
|
|
132
|
+
const sent = await transact({ ...s, cosigners: key === null || fuel === 0 ? [] : [key] }, bundle, send);
|
|
133
|
+
if (send && key !== null)
|
|
134
|
+
rmSync(path, { force: true });
|
|
135
|
+
return { ended: toBase58(delegate.delegate), returnedSol: fuel / 1e9, signature: sent.signature, units: sent.units };
|
|
136
|
+
}
|
|
137
|
+
/** Settled transactions on disk, one JSON line each, so a restart reads none of them twice. */
|
|
138
|
+
export function fileStore(dir) {
|
|
139
|
+
const file = join(dir, 'transactions.jsonl');
|
|
140
|
+
const memory = new Map();
|
|
141
|
+
if (existsSync(file)) {
|
|
142
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
143
|
+
if (line === '')
|
|
144
|
+
continue;
|
|
145
|
+
try {
|
|
146
|
+
const [signature, tx] = JSON.parse(line);
|
|
147
|
+
memory.set(signature, tx);
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
// a torn last line: that one transaction is read again
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
get: (signature) => memory.get(signature),
|
|
156
|
+
set: (signature, tx) => {
|
|
157
|
+
memory.set(signature, tx);
|
|
158
|
+
mkdirSync(dir, { recursive: true });
|
|
159
|
+
appendFileSync(file, `${JSON.stringify([signature, tx])}\n`);
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// wheelman: Wheelman, the Rekt trading bot and CLI. `wheelman help` lists the commands.
|
|
3
|
+
// With `-o json` every command prints one line: { ok: true, data } or { ok: false, error }.
|
|
4
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import * as cmd from "./commands.js";
|
|
7
|
+
import { Refusal, envelopeOf, toJson } from "./errors.js";
|
|
8
|
+
import { logToStderr, redact } from "./journal.js";
|
|
9
|
+
import { serve } from "./mcp.js";
|
|
10
|
+
import { setup } from "./setup.js";
|
|
11
|
+
const HELP = `wheelman <command> [arguments] [flags]
|
|
12
|
+
|
|
13
|
+
markets every market: open or not, stake bounds, fees, side room
|
|
14
|
+
preview <market> <long|short> <usd> what an open costs and pays, after every fee
|
|
15
|
+
open <market> <long|short> <usd> open a position (--minute: a Minute round)
|
|
16
|
+
close <id> ask the venue to close a position
|
|
17
|
+
positions open positions, rounds, balances, today's result
|
|
18
|
+
run [strategy] run the bot (STRATEGY and PARAM_* from the environment)
|
|
19
|
+
setup write .env and a wallet (--yes: answers from the environment)
|
|
20
|
+
session start|status|end a session key for an agent (--allowance, --expires, --fuel)
|
|
21
|
+
mcp a stdio MCP server with the same commands as tools
|
|
22
|
+
|
|
23
|
+
flags
|
|
24
|
+
-o json print one JSON envelope
|
|
25
|
+
--paper simulated fills; sends nothing (open, close, positions, run, mcp)
|
|
26
|
+
--dry-run build and simulate on mainnet; sends nothing (open, close, run, session)
|
|
27
|
+
--target <x> take-profit as a multiple of the stake (2 or more)
|
|
28
|
+
--timer <s> the position's own timer in seconds (26 or more)
|
|
29
|
+
--minute a Minute round instead of a Knockout position
|
|
30
|
+
--market <m> the market of a paper close or paper positions
|
|
31
|
+
--allowance <usd> session: the most it may spend --expires <time> session: 30m, 24h, 7d
|
|
32
|
+
--fuel <sol> session: SOL for its fees (0.01) --env <file> load this file, not .env
|
|
33
|
+
--yes, --force setup: no prompts; replace .env`;
|
|
34
|
+
const BOOLEAN = new Set(['paper', 'dry-run', 'minute', 'yes', 'force', 'help']);
|
|
35
|
+
const VALUE = new Set(['output', 'env', 'target', 'timer', 'market', 'allowance', 'expires', 'fuel']);
|
|
36
|
+
export function parseArgs(argv) {
|
|
37
|
+
const words = [];
|
|
38
|
+
const flags = {};
|
|
39
|
+
for (let i = 0; i < argv.length; i++) {
|
|
40
|
+
const a = argv[i];
|
|
41
|
+
if (a === '-o') {
|
|
42
|
+
flags.output = argv[++i] ?? '';
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (!a.startsWith('--')) {
|
|
46
|
+
words.push(a);
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
const [name, inline] = a.slice(2).split('=', 2);
|
|
50
|
+
if (BOOLEAN.has(name))
|
|
51
|
+
flags[name] = true;
|
|
52
|
+
else if (VALUE.has(name))
|
|
53
|
+
flags[name] = inline ?? argv[++i] ?? '';
|
|
54
|
+
else
|
|
55
|
+
throw new Refusal('config', 'BAD_ARGUMENT', `unknown flag --${name}`);
|
|
56
|
+
}
|
|
57
|
+
if (flags.output !== undefined && flags.output !== 'json' && flags.output !== 'text')
|
|
58
|
+
throw new Refusal('config', 'BAD_ARGUMENT', '-o takes json or text');
|
|
59
|
+
return { words, flags };
|
|
60
|
+
}
|
|
61
|
+
const numberFlag = (f, name) => {
|
|
62
|
+
if (f[name] === undefined)
|
|
63
|
+
return undefined;
|
|
64
|
+
const n = Number(f[name]);
|
|
65
|
+
if (!Number.isFinite(n))
|
|
66
|
+
throw new Refusal('config', 'BAD_ARGUMENT', `--${name} takes a number`);
|
|
67
|
+
return n;
|
|
68
|
+
};
|
|
69
|
+
/** Run one command and return its envelope. `signal` stops a running bot. */
|
|
70
|
+
export async function execute(p, ctx, signal) {
|
|
71
|
+
const f = p.flags;
|
|
72
|
+
const [command, ...rest] = p.words;
|
|
73
|
+
const args = {
|
|
74
|
+
paper: f.paper === true, dryRun: f['dry-run'] === true, minute: f.minute === true,
|
|
75
|
+
target: numberFlag(f, 'target'), timer: numberFlag(f, 'timer'), fuel: numberFlag(f, 'fuel'),
|
|
76
|
+
market: typeof f.market === 'string' ? f.market : undefined,
|
|
77
|
+
allowance: typeof f.allowance === 'string' ? f.allowance : undefined, expires: typeof f.expires === 'string' ? f.expires : undefined,
|
|
78
|
+
};
|
|
79
|
+
try {
|
|
80
|
+
const data = await (async () => {
|
|
81
|
+
switch (command) {
|
|
82
|
+
case 'markets': return cmd.markets(ctx);
|
|
83
|
+
case 'preview': return cmd.preview(ctx, { ...args, market: rest[0], side: rest[1], usd: rest[2] });
|
|
84
|
+
case 'open': return cmd.open(ctx, { ...args, market: rest[0], side: rest[1], usd: rest[2] });
|
|
85
|
+
case 'close': return cmd.close(ctx, { ...args, id: rest[0] });
|
|
86
|
+
case 'positions': return cmd.positions(ctx, args);
|
|
87
|
+
case 'run': return cmd.run(ctx, { ...args, strategy: rest[0] }, signal);
|
|
88
|
+
case 'setup': return setup({ yes: f.yes === true, force: f.force === true, say: (l) => (f.output === 'json' ? console.error(l) : console.log(l)) });
|
|
89
|
+
case 'session':
|
|
90
|
+
if (rest[0] === 'start')
|
|
91
|
+
return cmd.sessionStartCommand(ctx, args);
|
|
92
|
+
if (rest[0] === 'status')
|
|
93
|
+
return cmd.sessionStatusCommand(ctx);
|
|
94
|
+
if (rest[0] === 'end')
|
|
95
|
+
return cmd.sessionEndCommand(ctx, args);
|
|
96
|
+
throw new Refusal('config', 'BAD_ARGUMENT', 'session takes start, status or end');
|
|
97
|
+
default:
|
|
98
|
+
throw new Refusal('config', 'UNKNOWN_COMMAND', `unknown command ${command ?? '(none)'}: run wheelman help`);
|
|
99
|
+
}
|
|
100
|
+
})();
|
|
101
|
+
return { ok: true, data };
|
|
102
|
+
}
|
|
103
|
+
catch (e) {
|
|
104
|
+
return envelopeOf(e);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Plain text for people: one `key: value` a line, nested values indented. */
|
|
108
|
+
export function text(value, indent = '') {
|
|
109
|
+
if (Array.isArray(value))
|
|
110
|
+
return value.map((v) => (typeof v === 'object' && v !== null ? `${indent}-\n${text(v, `${indent} `)}` : `${indent}- ${String(v)}`)).join('\n');
|
|
111
|
+
if (typeof value === 'object' && value !== null) {
|
|
112
|
+
return Object.entries(value).map(([k, v]) => typeof v === 'object' && v !== null ? `${indent}${k}:\n${text(v, `${indent} `)}` : `${indent}${k}: ${typeof v === 'bigint' ? v.toString() : String(v)}`).join('\n');
|
|
113
|
+
}
|
|
114
|
+
return `${indent}${String(value)}`;
|
|
115
|
+
}
|
|
116
|
+
async function main(argv) {
|
|
117
|
+
let p;
|
|
118
|
+
try {
|
|
119
|
+
p = parseArgs(argv);
|
|
120
|
+
}
|
|
121
|
+
catch (e) {
|
|
122
|
+
console.log(toJson(envelopeOf(e)));
|
|
123
|
+
return 2;
|
|
124
|
+
}
|
|
125
|
+
const json = p.flags.output === 'json';
|
|
126
|
+
if (p.flags.help === true || p.words[0] === 'help' || p.words.length === 0) {
|
|
127
|
+
console.log(json ? toJson({ ok: true, data: { usage: HELP } }) : HELP);
|
|
128
|
+
return 0;
|
|
129
|
+
}
|
|
130
|
+
try {
|
|
131
|
+
if (typeof p.flags.env === 'string')
|
|
132
|
+
process.loadEnvFile(p.flags.env);
|
|
133
|
+
else if (existsSync('.env'))
|
|
134
|
+
process.loadEnvFile('.env');
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
console.log(toJson(envelopeOf(new Refusal('config', 'BAD_CONFIG', `${String(p.flags.env)} could not be read`))));
|
|
138
|
+
return 1;
|
|
139
|
+
}
|
|
140
|
+
const ctx = await cmd.makeCtx(process.env, p.words[0] === 'mcp');
|
|
141
|
+
if (p.words[0] === 'mcp') {
|
|
142
|
+
logToStderr(true);
|
|
143
|
+
await serve(ctx, { paper: p.flags.paper === true });
|
|
144
|
+
return 0;
|
|
145
|
+
}
|
|
146
|
+
logToStderr(json);
|
|
147
|
+
const abort = new AbortController();
|
|
148
|
+
for (const s of ['SIGINT', 'SIGTERM'])
|
|
149
|
+
process.on(s, () => abort.abort());
|
|
150
|
+
const out = await execute(p, ctx, abort.signal);
|
|
151
|
+
if (json)
|
|
152
|
+
console.log(redact(toJson(out)));
|
|
153
|
+
else if (out.ok)
|
|
154
|
+
console.log(redact(text(out.data)));
|
|
155
|
+
else
|
|
156
|
+
console.error(redact(`${out.error.category} ${out.error.code}: ${out.error.message}${out.error.retryable ? ' (retryable)' : ''}`));
|
|
157
|
+
return out.ok ? 0 : 1;
|
|
158
|
+
}
|
|
159
|
+
// Run when started as a program (also through the `wheelman` link npm makes), not when imported.
|
|
160
|
+
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
|
|
161
|
+
// Exit once stdout is written: an idle keep-alive socket must not hold a one-shot command open.
|
|
162
|
+
main(process.argv.slice(2)).then((code) => process.stdout.write('', () => process.exit(code)));
|
|
163
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// createKnockoutClient: the Knockout client the SDK is to ship, written here with the same method
|
|
2
|
+
// names and result shapes. When the SDK publishes it, this file is deleted and the import changes.
|
|
3
|
+
// market(symbol) facts about a market preview(order) what an open costs and pays
|
|
4
|
+
// open(order) { seq, seqs, signature } positions() the wallet's open positions
|
|
5
|
+
// close(seq) { signature } settlement(seq) what a closed position paid
|
|
6
|
+
// history() settled positions build.open/close the same, as unsigned instructions
|
|
7
|
+
// A refusal is thrown as a Refusal with `retryable`. Money is bigint USDC base units.
|
|
8
|
+
import { PublicKey } from '@solana/web3.js';
|
|
9
|
+
import { MICRO_PER_BP, assetId, barrierMicroBps, closableFromSlotOf, commitOpen, computeUnitLimit, configPda, connectionReader, decodeConfig, decodeFeeTermsTable, decodeMarket, decodeTraderAccount, decodeVault, delegatePda, exitFeeBpsFor, feeTermsTablePda, findBySeq, heldPositions, inEventWindow, ix, levels, marketPda, memoReader, newRules, openFeeTerms, openTenorS, ourInstruction, parseUsdc, phase, priceAccountsFor, readTradeHistory, receiptOf, sideRoom, sizeForTotal, toBase58, toHex, traderPda, vaultPda, venueEventsNamed, } from '@rekt-trading/1000x';
|
|
10
|
+
import { MARKETS } from "./config.js";
|
|
11
|
+
import { Refusal } from "./errors.js";
|
|
12
|
+
import { payoutAt, scaled, termsFor } from "./paper.js";
|
|
13
|
+
import { CLOCK, transact } from "./rpc.js";
|
|
14
|
+
const TOKEN_PROGRAM = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
|
|
15
|
+
const ATA_PROGRAM = new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');
|
|
16
|
+
export const ata = (owner, mint) => PublicKey.findProgramAddressSync([owner.toBytes(), TOKEN_PROGRAM.toBytes(), mint.toBytes()], ATA_PROGRAM)[0];
|
|
17
|
+
export const tokenAmount = (data) => (data == null || data.length < 72 ? 0n : Buffer.from(data).readBigUInt64LE(64));
|
|
18
|
+
const clockOf = (data) => ({ slot: Buffer.from(data).readBigUInt64LE(0), unix: Buffer.from(data).readBigInt64LE(32) });
|
|
19
|
+
const symbolOf = new Map(MARKETS.map((s) => [toHex(marketPda(assetId(s)).address), s]));
|
|
20
|
+
export const marketSymbol = (hex) => symbolOf.get(hex) ?? toBase58(hex);
|
|
21
|
+
const price = (v, expo) => Number(v) * 10 ** expo;
|
|
22
|
+
const sideOf = (direction) => (direction === 0 ? 'long' : 'short');
|
|
23
|
+
export function createKnockoutClient(o) {
|
|
24
|
+
const owner = o.owner;
|
|
25
|
+
const book = traderPda(owner).address;
|
|
26
|
+
const session = o.signer !== null && !o.signer.publicKey.equals(owner);
|
|
27
|
+
const authority = o.signer?.publicKey ?? owner;
|
|
28
|
+
const sender = { rpc: o.rpc, payer: authority, signer: o.signer, maxPriorityFee: o.maxPriorityFee ?? 100_000, tip: o.tip ?? null };
|
|
29
|
+
const reader = memoReader(connectionReader(o.rpc.conn), o.store === undefined ? {} : { store: o.store });
|
|
30
|
+
let vaultToken = null;
|
|
31
|
+
/** The vault's token account and the USDC mint: fixed, read once. */
|
|
32
|
+
const vaultTokenOf = (vault) => (vaultToken ??= (async () => {
|
|
33
|
+
const address = new PublicKey(toBase58(vault.tokenAccount));
|
|
34
|
+
const info = await o.rpc.conn.getAccountInfo(address, 'confirmed');
|
|
35
|
+
if (info === null)
|
|
36
|
+
throw new Refusal('venue', 'VAULT_MISSING', 'the vault token account is missing');
|
|
37
|
+
return { address, mint: new PublicKey(info.data.subarray(0, 32)) };
|
|
38
|
+
})());
|
|
39
|
+
/** One read: the config, the vault, a market and its fee terms, the wallet's book, the clock. */
|
|
40
|
+
async function read(symbol) {
|
|
41
|
+
const market = marketPda(assetId(symbol)).address;
|
|
42
|
+
const [c, v, m, f, b, k] = await o.rpc.conn.getMultipleAccountsInfo([configPda().address, vaultPda().address, market, feeTermsTablePda(market).address, book, CLOCK], 'confirmed');
|
|
43
|
+
if (c === null || v === null)
|
|
44
|
+
throw new Refusal('config', 'VENUE_MISSING', 'the venue config is missing: is RPC_URL a mainnet endpoint?');
|
|
45
|
+
if (m === null)
|
|
46
|
+
throw new Refusal('config', 'NO_SUCH_MARKET', `${symbol} is not listed on the venue`);
|
|
47
|
+
return {
|
|
48
|
+
address: market, config: decodeConfig(new Uint8Array(c.data)), vault: decodeVault(new Uint8Array(v.data)),
|
|
49
|
+
market: decodeMarket(new Uint8Array(m.data)), feeTable: f === null ? null : decodeFeeTermsTable(new Uint8Array(f.data)),
|
|
50
|
+
book: b === null ? null : decodeTraderAccount(new Uint8Array(b.data)), clock: clockOf(new Uint8Array(k.data)),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** Why the market takes no open now, or null. */
|
|
54
|
+
function closedWhy(config, market, nowUnix) {
|
|
55
|
+
if (config.paused)
|
|
56
|
+
return 'the venue is paused';
|
|
57
|
+
if (!commitOpen(config))
|
|
58
|
+
return 'the venue takes no orders now';
|
|
59
|
+
if (config.oracleFrozen || config.settlesDisabled)
|
|
60
|
+
return 'the venue is stopped';
|
|
61
|
+
if (market.paused)
|
|
62
|
+
return 'the market is paused';
|
|
63
|
+
if (inEventWindow(market, nowUnix))
|
|
64
|
+
return 'a scheduled event window';
|
|
65
|
+
const t = openTenorS(config, market, nowUnix);
|
|
66
|
+
return t.ok ? null : t.reason === 'closed' ? 'outside trading hours' : 'too close to the session close';
|
|
67
|
+
}
|
|
68
|
+
async function market(symbol) {
|
|
69
|
+
const r = await read(symbol);
|
|
70
|
+
const vt = await vaultTokenOf(r.vault);
|
|
71
|
+
const balance = await o.rpc.conn.getAccountInfo(vt.address, 'confirmed');
|
|
72
|
+
const terms = openFeeTerms(r.config, r.market, r.feeTable);
|
|
73
|
+
const flat = Number(exitFeeBpsFor(BigInt(r.market.exitFeeBps), r.config.params.exitFeeBps));
|
|
74
|
+
const room = (side) => {
|
|
75
|
+
const s = sideRoom(side, r.market, r.vault, tokenAmount(balance?.data), newRules(r.config));
|
|
76
|
+
return s.limit === null ? null : s.room; // no limit set: no room to report
|
|
77
|
+
};
|
|
78
|
+
const why = closedWhy(r.config, r.market, r.clock.unix);
|
|
79
|
+
return {
|
|
80
|
+
symbol, address: r.address.toBase58(), open: why === null, why, minute: r.market.minuteEnabled, leverage: Number(r.market.tier),
|
|
81
|
+
stake: { min: r.config.params.minCollateral, max: r.config.params.maxCollateral },
|
|
82
|
+
fees: {
|
|
83
|
+
entryBps: Number(r.config.params.entryFeeBps),
|
|
84
|
+
exitWinBps: terms.kind === 'terms' ? terms.entry.winBps : flat,
|
|
85
|
+
exitLossBps: terms.kind === 'terms' ? terms.entry.lossBps : flat,
|
|
86
|
+
keptBps: terms.kind === 'terms'
|
|
87
|
+
? terms.entry.haircutMoveTenthBp.slice(0, terms.entry.haircutCount).map((m, i) => ({ moveBp: m / 10, keptBps: terms.entry.haircutKeptBps[i] }))
|
|
88
|
+
: [],
|
|
89
|
+
},
|
|
90
|
+
sideRoom: { long: room('long'), short: room('short') },
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
async function preview(order) {
|
|
94
|
+
const r = await read(order.market);
|
|
95
|
+
const debit = typeof order.usd === 'bigint' ? order.usd : parseUsdc(order.usd);
|
|
96
|
+
const t = termsFor({ config: r.config, market: r.market, feeTable: r.feeTable, minute: null, nowUnix: r.clock.unix }, 'knockout', order.side, debit, order.target ?? 0, order.timer ?? 0);
|
|
97
|
+
// Priced at a reference entry of 1: both ends are distances from the entry, so any entry gives the same payouts.
|
|
98
|
+
const at = { ...t, engine: { ...t.engine, entryPrice: scaled(1) } };
|
|
99
|
+
const micro = Number(MICRO_PER_BP);
|
|
100
|
+
return {
|
|
101
|
+
market: order.market, side: order.side, debit, stake: t.engine.collateral, leverage: Number(t.engine.tier),
|
|
102
|
+
barrierBps: Number(barrierMicroBps(t.engine.tier, t.engine.muBps)) / micro,
|
|
103
|
+
target: order.target ? order.target : null, targetBps: order.target ? Number(t.engine.takeProfit) / micro : null,
|
|
104
|
+
timer: order.timer ?? 0, payoutAtTarget: order.target ? payoutAt(at, 1, 'takeProfit') : null, payoutAtBarrier: payoutAt(at, 1, 'knockout'),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** One transaction for every order given: the book is created first when the wallet has none. */
|
|
108
|
+
async function buildOpen(orders) {
|
|
109
|
+
const list = Array.isArray(orders) ? orders : [orders];
|
|
110
|
+
const r = await read(list[0].market);
|
|
111
|
+
const why = closedWhy(r.config, r.market, r.clock.unix);
|
|
112
|
+
if (why !== null)
|
|
113
|
+
throw new Refusal('venue', 'MARKET_CLOSED', `${list[0].market}: ${why}`, true, 60_000);
|
|
114
|
+
const vt = await vaultTokenOf(r.vault);
|
|
115
|
+
const traderToken = toHex(ata(owner, vt.mint));
|
|
116
|
+
const built = [];
|
|
117
|
+
if (r.book === null) {
|
|
118
|
+
if (session)
|
|
119
|
+
throw new Refusal('session', 'NO_BOOK', 'the owner has no book yet: `wheelman session start` creates it');
|
|
120
|
+
built.push(ix.initTraderAccount({
|
|
121
|
+
trader: toHex(owner), payer: toHex(owner), positions: toHex(book), vault: toHex(vaultPda().address),
|
|
122
|
+
vault_token: r.vault.tokenAccount, payout_destination: traderToken,
|
|
123
|
+
}, 12));
|
|
124
|
+
}
|
|
125
|
+
list.forEach((order, n) => {
|
|
126
|
+
const debit = typeof order.usd === 'bigint' ? order.usd : parseUsdc(order.usd);
|
|
127
|
+
const size = sizeForTotal(debit, r.config.params);
|
|
128
|
+
if (size.refusal !== null)
|
|
129
|
+
throw new Refusal('venue', size.refusal.id, `${size.refusal.label}: ${size.refusal.detail}`);
|
|
130
|
+
built.push(ix.open({
|
|
131
|
+
authority: toHex(authority), trader_token: traderToken, config: toHex(configPda().address), market: toHex(marketPda(assetId(order.market)).address),
|
|
132
|
+
vault: toHex(vaultPda().address), vault_token: r.vault.tokenAccount, protocol_token: r.config.treasury, positions: toHex(book),
|
|
133
|
+
delegate: session ? toHex(delegatePda(owner).address) : null,
|
|
134
|
+
}, {
|
|
135
|
+
budget: debit, direction: order.side === 'long' ? 0 : 1, rung_bps: Math.round((order.target ?? 0) * 10_000), user_timer_s: order.timer ?? 0,
|
|
136
|
+
min_collateral_out: size.collateral, referrer: null, tier: 0, opener_tag: BigInt(Date.now()) * 100n + BigInt(n + 1),
|
|
137
|
+
}, priceAccountsFor(r.market, r.config, 'open')));
|
|
138
|
+
});
|
|
139
|
+
return bundleOf(built);
|
|
140
|
+
}
|
|
141
|
+
async function buildClose(seq) {
|
|
142
|
+
const [c, b, k] = await o.rpc.conn.getMultipleAccountsInfo([configPda().address, book, CLOCK], 'confirmed');
|
|
143
|
+
const p = b === null ? null : findBySeq(decodeTraderAccount(new Uint8Array(b.data)), seq);
|
|
144
|
+
if (p === null)
|
|
145
|
+
throw new Refusal('venue', 'PositionNotFound', `no open position has seq ${seq}`);
|
|
146
|
+
const marketAddress = new PublicKey(toBase58(p.market));
|
|
147
|
+
const m = await o.rpc.conn.getAccountInfo(marketAddress, 'confirmed');
|
|
148
|
+
const from = closableFromSlotOf(p, decodeConfig(new Uint8Array(c.data)), decodeMarket(new Uint8Array(m.data)));
|
|
149
|
+
if (from === null || from > clockOf(new Uint8Array(k.data)).slot) {
|
|
150
|
+
throw new Refusal('venue', 'CLOSE_NOT_YET', `position ${seq} cannot be closed yet (an order, or inside the minimum hold)`, true, 5_000);
|
|
151
|
+
}
|
|
152
|
+
return bundleOf([ix.requestClose({
|
|
153
|
+
authority: toHex(authority), config: toHex(configPda().address), market: toHex(marketAddress), positions: toHex(book),
|
|
154
|
+
delegate: session ? toHex(delegatePda(owner).address) : null,
|
|
155
|
+
}, seq)]);
|
|
156
|
+
}
|
|
157
|
+
async function positions() {
|
|
158
|
+
const markets = MARKETS.map((s) => marketPda(assetId(s)).address);
|
|
159
|
+
const [b, k, c, ...m] = await o.rpc.conn.getMultipleAccountsInfo([book, CLOCK, configPda().address, ...markets], 'confirmed');
|
|
160
|
+
if (b === null)
|
|
161
|
+
return [];
|
|
162
|
+
const clock = clockOf(new Uint8Array(k.data));
|
|
163
|
+
const config = decodeConfig(new Uint8Array(c.data));
|
|
164
|
+
const marketOf = new Map(markets.map((a, i) => [toHex(a), m[i] == null ? null : decodeMarket(new Uint8Array(m[i].data))]));
|
|
165
|
+
return heldPositions(owner.toBase58(), decodeTraderAccount(new Uint8Array(b.data))).map(({ position: p }) => {
|
|
166
|
+
const filled = p.entryPrice !== 0n;
|
|
167
|
+
const l = filled ? levels(p) : null;
|
|
168
|
+
const mk = marketOf.get(p.market) ?? null;
|
|
169
|
+
return {
|
|
170
|
+
seq: p.seq, market: marketSymbol(p.market), side: sideOf(p.direction), stake: p.collateral,
|
|
171
|
+
entryPrice: filled ? price(p.entryPrice, p.entryExpo) : null,
|
|
172
|
+
barrierPrice: l === null ? null : price(l.barrierPrice, p.entryExpo),
|
|
173
|
+
targetPrice: l?.takeProfitPrice == null ? null : price(l.takeProfitPrice, p.entryExpo),
|
|
174
|
+
state: phase(p, clock.slot), openedAt: Number(p.openedAt),
|
|
175
|
+
timerEndsAt: p.userTimerS === null ? null : Number(p.openedAt) + p.userTimerS,
|
|
176
|
+
closableFromSlot: mk === null ? null : closableFromSlotOf(p, config, mk),
|
|
177
|
+
};
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
const settlementOf = (t) => ({
|
|
181
|
+
seq: t.seq, market: marketSymbol(t.market), side: t.direction, stake: t.stake, payout: t.pnl.payout, pnl: t.pnl.payout - t.stake,
|
|
182
|
+
reason: t.reason, settledAt: t.settledAt, signature: t.signature,
|
|
183
|
+
});
|
|
184
|
+
/** Settled positions, newest first. `since` (unix seconds) reads only that far back. */
|
|
185
|
+
async function history(opts = {}) {
|
|
186
|
+
let limit = opts.limit ?? 100;
|
|
187
|
+
if (opts.since !== undefined) {
|
|
188
|
+
const sigs = await o.rpc.conn.getSignaturesForAddress(book, { limit: 1000 }, 'confirmed');
|
|
189
|
+
limit = sigs.filter((s) => (s.blockTime ?? 0) >= opts.since).length;
|
|
190
|
+
if (limit === 0)
|
|
191
|
+
return [];
|
|
192
|
+
}
|
|
193
|
+
const config = decodeConfig(new Uint8Array((await o.rpc.conn.getAccountInfo(configPda().address, 'confirmed')).data));
|
|
194
|
+
const h = await readTradeHistory(reader, owner, config, { limit });
|
|
195
|
+
return h.trades.filter((t) => opts.since === undefined || (t.settledAt ?? 0) >= opts.since).map(settlementOf);
|
|
196
|
+
}
|
|
197
|
+
/** What a closed position paid, or null while it is open or not found yet. */
|
|
198
|
+
async function settlement(seq) {
|
|
199
|
+
const config = decodeConfig(new Uint8Array((await o.rpc.conn.getAccountInfo(configPda().address, 'confirmed')).data));
|
|
200
|
+
const h = await readTradeHistory(reader, owner, config, { limit: 25 });
|
|
201
|
+
const t = h.trades.find((x) => x.seq === seq);
|
|
202
|
+
if (t !== undefined)
|
|
203
|
+
return settlementOf(t);
|
|
204
|
+
const v = h.voidedOpens.find((x) => x.seq === seq);
|
|
205
|
+
return v === undefined ? null : {
|
|
206
|
+
seq, market: marketSymbol(v.market), side: null, stake: v.stake, payout: v.stakeReturned, pnl: v.stakeReturned - v.stake,
|
|
207
|
+
reason: `returned (${v.reason})`, settledAt: v.blockTime, signature: v.signature,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
return {
|
|
211
|
+
owner,
|
|
212
|
+
market,
|
|
213
|
+
preview,
|
|
214
|
+
positions,
|
|
215
|
+
history,
|
|
216
|
+
settlement,
|
|
217
|
+
async open(orders) {
|
|
218
|
+
const sent = await transact(sender, await buildOpen(orders), true);
|
|
219
|
+
// The positions this transaction opened: the SDK's receipt keeps only events the venue's own frames emitted.
|
|
220
|
+
const receipt = receiptOf({
|
|
221
|
+
signature: sent.signature, slot: 0, blockTime: null, err: null, logMessages: sent.logs,
|
|
222
|
+
preTokenBalances: null, postTokenBalances: null, feePayer: null, computeUnits: null, returnData: null,
|
|
223
|
+
});
|
|
224
|
+
const seqs = venueEventsNamed(receipt, 'PositionOpened').map((e) => e.seq);
|
|
225
|
+
return { seq: seqs[0], seqs, signature: sent.signature };
|
|
226
|
+
},
|
|
227
|
+
async close(seq) {
|
|
228
|
+
return { signature: (await transact(sender, await buildClose(seq), true)).signature };
|
|
229
|
+
},
|
|
230
|
+
build: { open: buildOpen, close: buildClose },
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
/** Instructions with the compute units the SDK measured for each. */
|
|
234
|
+
export function bundleOf(built, unmeasured = 200_000) {
|
|
235
|
+
const units = (name) => {
|
|
236
|
+
try {
|
|
237
|
+
return computeUnitLimit(name);
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
return unmeasured; // the runtime's default for an instruction the SDK does not measure
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
const instructions = built.map(ourInstruction);
|
|
244
|
+
return { instructions, computeUnits: built.reduce((s, b) => s + units(b.name), 0) };
|
|
245
|
+
}
|