candle-launch-bot 0.0.0-stage → 0.1.0
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.
Potentially problematic release.
This version of candle-launch-bot might be problematic. Click here for more details.
- package/CHANGELOG.md +14 -0
- package/LICENSE +21 -0
- package/README.md +400 -2
- package/bin/candle-launch-bot +7 -0
- package/dist/alerts.d.ts +28 -0
- package/dist/alerts.js +82 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +321 -0
- package/dist/config.d.ts +88 -0
- package/dist/config.js +244 -0
- package/dist/detect/detector.d.ts +111 -0
- package/dist/detect/detector.js +348 -0
- package/dist/engine.d.ts +103 -0
- package/dist/engine.js +585 -0
- package/dist/exec/executor.d.ts +149 -0
- package/dist/exec/executor.js +859 -0
- package/dist/exec/fills.d.ts +25 -0
- package/dist/exec/fills.js +53 -0
- package/dist/exec/trader.d.ts +109 -0
- package/dist/exec/trader.js +310 -0
- package/dist/filters.d.ts +26 -0
- package/dist/filters.js +92 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +2 -0
- package/dist/init.d.ts +23 -0
- package/dist/init.js +192 -0
- package/dist/ledger.d.ts +189 -0
- package/dist/ledger.js +243 -0
- package/dist/log.d.ts +22 -0
- package/dist/log.js +40 -0
- package/dist/market/curve.d.ts +80 -0
- package/dist/market/curve.js +168 -0
- package/dist/market/reader.d.ts +37 -0
- package/dist/market/reader.js +106 -0
- package/dist/redact.d.ts +20 -0
- package/dist/redact.js +111 -0
- package/dist/solana/base58.d.ts +4 -0
- package/dist/solana/base58.js +45 -0
- package/dist/solana/logs-ws.d.ts +25 -0
- package/dist/solana/logs-ws.js +116 -0
- package/dist/solana/pda.d.ts +12 -0
- package/dist/solana/pda.js +70 -0
- package/dist/solana/rpc.d.ts +29 -0
- package/dist/solana/rpc.js +96 -0
- package/dist/strategies/hold.d.ts +3 -0
- package/dist/strategies/hold.js +6 -0
- package/dist/strategies/ladder.d.ts +8 -0
- package/dist/strategies/ladder.js +51 -0
- package/dist/strategies/load.d.ts +5 -0
- package/dist/strategies/load.js +44 -0
- package/dist/strategies/preGrad.d.ts +10 -0
- package/dist/strategies/preGrad.js +32 -0
- package/dist/strategies/time.d.ts +6 -0
- package/dist/strategies/time.js +16 -0
- package/dist/strategies/tpsl.d.ts +8 -0
- package/dist/strategies/tpsl.js +30 -0
- package/dist/strategies/types.d.ts +55 -0
- package/dist/strategies/types.js +31 -0
- package/examples/dry.json +32 -0
- package/examples/live-embedded.json +14 -0
- package/examples/live-linked.json +15 -0
- package/examples/strategies/breakeven-stop.js +22 -0
- package/examples/strategies/stale-coin.js +18 -0
- package/examples/strategies/timeboxed-tp.js +18 -0
- package/package.json +60 -4
- package/skills/candle-launch-bot/SKILL.md +71 -0
|
@@ -0,0 +1,859 @@
|
|
|
1
|
+
import { errorJson } from "../redact.js";
|
|
2
|
+
import { blockhashValid, getTransaction, signatureStatus, tokenAccounts, tokenBalance } from "../solana/rpc.js";
|
|
3
|
+
import { candleCurve, WSOL } from "../solana/pda.js";
|
|
4
|
+
import { buyImpact, decodeCandleCurve } from "../market/curve.js";
|
|
5
|
+
import { fillFromTx } from "./fills.js";
|
|
6
|
+
import { blockhashOfSigned, signatureOfSigned } from "./trader.js";
|
|
7
|
+
/** Lease while an attempt runs: longer than every timeout inside one attempt put together. */
|
|
8
|
+
export const LEASE_MS = 180_000;
|
|
9
|
+
/** Failed reads of a landed transaction before the bot books from Candle's numbers instead (and alerts). */
|
|
10
|
+
export const TX_READ_CAP = 6;
|
|
11
|
+
/** Never judge a signature dead sooner than this after signing, whatever the chain says (clock skew, RPC lag). */
|
|
12
|
+
export const SIGNATURE_MIN_AGE_MS = 20_000;
|
|
13
|
+
/** Re-scans of the wallet for an ending buy's tokens that are there but not yet explained (RPC lag), on the backoff. */
|
|
14
|
+
export const ADOPT_SCAN_CAP = 10;
|
|
15
|
+
/** Pages of token-account history read per scan (100 signatures each), stopping at the order's creation. */
|
|
16
|
+
export const ADOPT_PAGES = 10;
|
|
17
|
+
/** An ending buy scans at least this long (the balance and history may lag a trade that just landed). */
|
|
18
|
+
export const ENDING_MIN_MS = 120_000;
|
|
19
|
+
/** A transaction of an attempt can land up to this long after the attempt's call ended (its blockhash life, with margin). */
|
|
20
|
+
export const ATTEMPT_LAND_SEC = 150;
|
|
21
|
+
function logsOf(x) {
|
|
22
|
+
for (const c of [x?.data?.logs, x?.logs, x?.data?.err?.logs, x?.discovery?.logs, x?.coverage?.logs])
|
|
23
|
+
if (Array.isArray(c))
|
|
24
|
+
return c.map(String);
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
/** Transport-level codes (Node fetch/undici, sockets, DNS): the request may or may not have arrived. */
|
|
28
|
+
const TRANSPORT = /^(E[A-Z]+|UND_ERR_[A-Z_]+|ABORT_ERR|ERR_[A-Z_]+)$/;
|
|
29
|
+
/** Read an error's structure. Only a CandleApiError can be a definite refusal; everything else is retryable. */
|
|
30
|
+
export function errorInfo(e) {
|
|
31
|
+
const x = e;
|
|
32
|
+
if (x && typeof x.code === "string" && typeof x.status === "number") {
|
|
33
|
+
// Timeouts and rate limits are never refusals, whatever the envelope says (a bare proxy 429 has no envelope at all).
|
|
34
|
+
const busy = x.status >= 500 || x.status === 408 || x.status === 425 || x.status === 429;
|
|
35
|
+
return { code: x.code, candle: true, status: x.status, retryable: !!x.retryable || busy, stage: x.stage, reason: x.reason, signature: x.signature, recorded: x.recorded, retryAfter: x.retryAfter, logs: logsOf(x) };
|
|
36
|
+
}
|
|
37
|
+
if (x?.name === "TimeoutError" || x?.name === "AbortError")
|
|
38
|
+
return { code: "TIMEOUT", candle: false, retryable: true };
|
|
39
|
+
if (x && typeof x.code === "string" && TRANSPORT.test(x.code))
|
|
40
|
+
return { code: `NET_${x.code}`, candle: false, retryable: true };
|
|
41
|
+
if (x && typeof x.code === "number")
|
|
42
|
+
return { code: `RPC_${x.code}`, candle: false, retryable: true, logs: logsOf(x) };
|
|
43
|
+
if (x?.cause) {
|
|
44
|
+
const c = errorInfo(x.cause);
|
|
45
|
+
return { ...c, logs: c.logs ?? logsOf(x) };
|
|
46
|
+
}
|
|
47
|
+
return { code: typeof x?.code === "string" ? `X_${x.code}` : "UNKNOWN", candle: false, retryable: true, logs: logsOf(x) };
|
|
48
|
+
}
|
|
49
|
+
export class Executor {
|
|
50
|
+
d;
|
|
51
|
+
now;
|
|
52
|
+
random;
|
|
53
|
+
constructor(d) {
|
|
54
|
+
this.d = d;
|
|
55
|
+
this.now = d.now ?? Date.now;
|
|
56
|
+
this.random = d.random ?? Math.random;
|
|
57
|
+
}
|
|
58
|
+
backoffMs(attempts) {
|
|
59
|
+
const { baseDelayMs, maxDelayMs } = this.d.cfg.retry;
|
|
60
|
+
const exp = Math.min(maxDelayMs, baseDelayMs * 2 ** Math.max(0, attempts - 1));
|
|
61
|
+
return Math.round(exp * (0.5 + this.random() * 0.5));
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Run one attempt for each due order, sells first, claiming ONE order at a time (so no claimed order waits behind
|
|
65
|
+
* others while its lease runs), until `limit` orders, the time budget, or a stop request. Never throws.
|
|
66
|
+
*/
|
|
67
|
+
async sweep(limit = 5, opts = {}) {
|
|
68
|
+
const start = this.now();
|
|
69
|
+
const budget = opts.budgetMs ?? LEASE_MS / 3;
|
|
70
|
+
const ran = [];
|
|
71
|
+
for (let i = 0; i < limit; i++) {
|
|
72
|
+
if (opts.shouldStop?.() || this.now() - start > budget)
|
|
73
|
+
return;
|
|
74
|
+
// Without a trade rail (dry), live orders are never claimed: they wait for a live process. An order runs at
|
|
75
|
+
// most once per sweep (a settle-only hand-back stays due for the build step, but is not re-claimed here).
|
|
76
|
+
const due = this.d.ledger.claimDue(this.now(), LEASE_MS, 1, { dryOnly: !this.d.rail, onlyIds: opts.onlyIds, excludeIds: ran, side: opts.side, reconcileOnly: opts.reconcileOnly });
|
|
77
|
+
if (!due.length)
|
|
78
|
+
return;
|
|
79
|
+
ran.push(due[0].id);
|
|
80
|
+
await this.runOne(due[0], !!opts.reconcileOnly);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async runOne(o, reconcileOnly = false) {
|
|
84
|
+
{
|
|
85
|
+
try {
|
|
86
|
+
await this.attempt(o, reconcileOnly);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
catch (e) {
|
|
90
|
+
// Last-resort guard: count the attempt and reschedule. Never terminal while a signature may still land.
|
|
91
|
+
const ord = this.d.ledger.order(o.id);
|
|
92
|
+
const attempts = ord.attempts + (ord.attempts === o.attempts ? 1 : 0);
|
|
93
|
+
this.d.ledger.updateOrder(o.id, { attempts, status: "pending", next_attempt_at: this.now() + this.backoffMs(attempts), lease_until: 0, last_error_code: "INTERNAL", last_error: errorJson(e), updated_at: this.now() });
|
|
94
|
+
this.d.log.error("order_internal_error", { order: o.id, error: errorJson(e) });
|
|
95
|
+
const k = (ord.internal_errors ?? 0) + 1;
|
|
96
|
+
this.d.ledger.updateOrder(o.id, { internal_errors: k });
|
|
97
|
+
this.alert(`order:${o.id}:internal_error:${k >= 20 ? "20+" : k >= 5 ? "5+" : "1"}`, `order ${o.id} ${ord.side}: ${k} internal errors (last ${String(e?.message ?? e).slice(0, 200)})`);
|
|
98
|
+
// Never ended here while something may be live: a signature, a conflict, an ending buy, or a main-payer build.
|
|
99
|
+
const maybeLive = !!ord.signature || ord.last_error_code === "IDEMPOTENCY_CONFLICT" || !!ord.ending || (this.d.rail?.payer?.type === "main" && ord.ever_signed === 1);
|
|
100
|
+
if (attempts >= ord.max_attempts && !maybeLive)
|
|
101
|
+
this.terminal(this.d.ledger.order(o.id), "failed", "INTERNAL");
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async attempt(o, reconcileOnly = false) {
|
|
106
|
+
const pos = this.d.ledger.position(o.position_id);
|
|
107
|
+
if (pos.dry)
|
|
108
|
+
return this.dryAttempt(o, pos);
|
|
109
|
+
if (!this.d.rail) {
|
|
110
|
+
// Never reached (claims skip live orders without a rail); if it is, hand the order back untouched.
|
|
111
|
+
this.d.ledger.updateOrder(o.id, { status: "pending", lease_until: 0 });
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const main = this.d.rail.payer?.type === "main";
|
|
115
|
+
// 1. An earlier attempt signed something: settle it on chain before anything else.
|
|
116
|
+
if (o.signature) {
|
|
117
|
+
const r = await this.reconcileSignature(o, pos);
|
|
118
|
+
if (r)
|
|
119
|
+
return this.apply(o, pos, r);
|
|
120
|
+
}
|
|
121
|
+
// 2. The order has history: ask Candle's ledger what it knows before building again, or deciding anything.
|
|
122
|
+
let job = null;
|
|
123
|
+
if (o.attempts > 0 || o.ever_signed === 1) {
|
|
124
|
+
try {
|
|
125
|
+
job = await this.d.rail.job(o.client_trade_id);
|
|
126
|
+
}
|
|
127
|
+
catch (e) {
|
|
128
|
+
return this.apply(o, pos, this.readFailed(o, pos, errorInfo(e).code, "job read failed"), e);
|
|
129
|
+
}
|
|
130
|
+
if (o.read_failures)
|
|
131
|
+
this.d.ledger.updateOrder(o.id, { read_failures: 0 });
|
|
132
|
+
if (job?.status === "confirmed" && job.signature) {
|
|
133
|
+
// Candle says it landed. Book it from its transaction, read again until the RPC serves it; never clear it.
|
|
134
|
+
this.d.ledger.updateOrder(o.id, { signature: job.signature, signed_at: o.signed_at ?? this.now(), ever_signed: 1, candle_confirmed: 1 });
|
|
135
|
+
return this.apply(o, pos, await this.landed(this.d.ledger.order(o.id), pos, job.signature, null));
|
|
136
|
+
}
|
|
137
|
+
if (job?.status === "failed" && job.errorCode === "TRADE_REVERTED")
|
|
138
|
+
return this.apply(o, pos, await this.revertedOutcome(pos, job.signature ?? null));
|
|
139
|
+
// IDEMPOTENCY_CONFLICT for this id, or payer main with a build that may be executing: Candle's job decides.
|
|
140
|
+
// While it is built (or confirmed without a signature yet), nothing is rebuilt and nothing ends the order:
|
|
141
|
+
// no deadline, no PAUSE_BUYS, no impact recheck, no attempt cap.
|
|
142
|
+
const unsettled = job && job.status !== "failed";
|
|
143
|
+
if (unsettled && (o.last_error_code === "IDEMPOTENCY_CONFLICT" || (main && o.ever_signed === 1))) {
|
|
144
|
+
// A main job stuck at built: once, after builtProbeMs, a same-id build asks Candle for its signature (a
|
|
145
|
+
// replay of a landed id returns it; one still in flight answers IDEMPOTENCY_CONFLICT). Never a new trade.
|
|
146
|
+
if (main && job.status === "built") {
|
|
147
|
+
const seen = o.built_seen_at ?? this.now();
|
|
148
|
+
if (o.built_seen_at === null)
|
|
149
|
+
this.d.ledger.updateOrder(o.id, { built_seen_at: seen });
|
|
150
|
+
// A same-id build of a buy can execute it anew if the old job died: only while the buy itself would still
|
|
151
|
+
// be placed (before its deadline, buys not paused, the impact recheck passing).
|
|
152
|
+
if (!o.probed && this.now() - seen >= this.d.cfg.retry.builtProbeMs && !reconcileOnly && !o.ending && (await this.buyStillGood(o, pos))) {
|
|
153
|
+
this.d.ledger.updateOrder(o.id, { probed: 1 });
|
|
154
|
+
return this.probe(o, pos);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
// A stale buy whose job stays built past builtHoldMs: Candle never sent it (its blockhash is long dead). End it
|
|
158
|
+
// after the wallet/tx scan, so it stops holding a slot and the lifetime cap. Alerted.
|
|
159
|
+
if (main && o.side === "buy" && job.status === "built" && o.built_seen_at !== null) {
|
|
160
|
+
const stale = o.deadline_at !== null && this.now() > o.deadline_at;
|
|
161
|
+
if (o.ending || (stale && this.now() - o.built_seen_at >= this.d.cfg.retry.builtHoldMs)) {
|
|
162
|
+
if (!o.ending)
|
|
163
|
+
this.alert(`order:${o.id}:built_held`, `order ${o.id} buy ${pos.mint}: Candle's job stayed built ${Math.round((this.now() - o.built_seen_at) / 3_600_000 * 10) / 10} h past the buy's deadline; ending it after a wallet scan`);
|
|
164
|
+
return this.endBuy(o, pos, { status: "failed", code: "BUILT_HELD" });
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const n = o.read_failures + 1;
|
|
168
|
+
this.d.ledger.updateOrder(o.id, { read_failures: n });
|
|
169
|
+
this.alert(`order:${o.id}:job_unsettled:${n >= 20 ? "20+" : n >= 5 ? "5+" : "1"}`, `order ${o.id} ${o.side} ${pos.mint}: Candle's job is ${job.status}; waiting for it to settle`);
|
|
170
|
+
return this.apply(o, pos, { kind: "wait", untilMs: this.now() + this.backoffMs(Math.min(n, 30)), why: `job ${job.status}` });
|
|
171
|
+
}
|
|
172
|
+
if (o.last_error_code === "IDEMPOTENCY_CONFLICT") {
|
|
173
|
+
this.d.ledger.updateOrder(o.id, { last_error_code: null });
|
|
174
|
+
o = { ...o, last_error_code: null };
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
// A buy that is already ending (its tokens not yet explained): only the wallet/tx scan runs, never a new build.
|
|
178
|
+
if (o.side === "buy" && o.ending)
|
|
179
|
+
return this.endBuy(o, pos, JSON.parse(o.ending));
|
|
180
|
+
// Payer main and a build that may have executed, with a job that says failed (not a revert): the SDK's word is
|
|
181
|
+
// that it may still be on chain. Before ending such an order, the wallet must not hold tokens we can't account for.
|
|
182
|
+
const failedMain = main && o.ever_signed === 1 && o.attempts > 0 && (job === null || job?.status === "failed");
|
|
183
|
+
const stopBuy = async (code, detail) => {
|
|
184
|
+
if (failedMain && o.side === "buy")
|
|
185
|
+
return this.endBuy(o, pos, { status: "rejected", code, detail });
|
|
186
|
+
return this.terminal(o, "rejected", code, detail);
|
|
187
|
+
};
|
|
188
|
+
// 3. Out of attempts: terminal. (Checked after reconciliation, so a landed trade is never marked failed.)
|
|
189
|
+
const pastDeadline = o.side === "buy" && o.deadline_at !== null && this.now() > o.deadline_at;
|
|
190
|
+
let finalCheck = false;
|
|
191
|
+
if (o.attempts >= o.max_attempts) {
|
|
192
|
+
// A failed main job at the cap: one same-id build is the check (Candle replays a landed id, or answers
|
|
193
|
+
// IDEMPOTENCY_CONFLICT for one in flight). Never for a stale buy, where a rebuild could buy anew.
|
|
194
|
+
if (failedMain && job?.status === "failed" && !o.final_check && (await this.buyStillGood(o, pos))) {
|
|
195
|
+
// The check is a build: a settle-only sweep hands the order back without using it up.
|
|
196
|
+
if (reconcileOnly) {
|
|
197
|
+
this.d.ledger.updateOrder(o.id, { status: "pending", lease_until: 0 });
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
this.d.ledger.updateOrder(o.id, { final_check: 1 });
|
|
201
|
+
finalCheck = true;
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
if (failedMain && o.side === "buy")
|
|
205
|
+
return this.endBuy(o, pos, { status: "failed", code: o.last_error_code ?? "MAX_ATTEMPTS" });
|
|
206
|
+
return this.terminal(o, "failed", o.last_error_code ?? "MAX_ATTEMPTS");
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
// Everything that could be live under this order was settled above, so a stale, paused or chasing buy stops here.
|
|
210
|
+
if (o.side === "buy" && !finalCheck) {
|
|
211
|
+
if (pastDeadline)
|
|
212
|
+
return stopBuy("DEADLINE", "the entry decision is stale");
|
|
213
|
+
if (this.d.buysPaused?.())
|
|
214
|
+
return stopBuy("PAUSE_BUYS", "buys paused before this attempt");
|
|
215
|
+
if (o.attempts > 0) {
|
|
216
|
+
const stop = await this.recheckBuy(o, pos);
|
|
217
|
+
if (stop)
|
|
218
|
+
return stop.kind === "rejected" ? stopBuy(stop.code, stop.detail) : this.apply(o, pos, stop);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
// A settle-only sweep (outside the cycle budget) never starts a new build: hand the order back as it was.
|
|
222
|
+
if (reconcileOnly) {
|
|
223
|
+
this.d.ledger.updateOrder(o.id, { status: "pending", lease_until: 0 });
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
// 4. A fresh attempt. Count it first: a throw anywhere below has already cost it.
|
|
227
|
+
const n = o.attempts + 1;
|
|
228
|
+
// Payer main executes inside the build: mark it possibly spent BEFORE the call, so a crash mid-build cannot
|
|
229
|
+
// leave an order that the caps and the reconciliation think never ran.
|
|
230
|
+
this.d.ledger.updateOrder(o.id, { attempts: n, updated_at: this.now(), ...(main ? { ever_signed: 1 } : {}) });
|
|
231
|
+
const att = this.d.ledger.startAttempt(o.id, n, this.now());
|
|
232
|
+
const cfg = this.d.cfg;
|
|
233
|
+
const prio = o.side === "buy" ? cfg.buy.maxPriorityFeeLamports : cfg.sell.maxPriorityFeeLamports;
|
|
234
|
+
let phase = "build";
|
|
235
|
+
try {
|
|
236
|
+
const built = await this.d.rail.build({
|
|
237
|
+
clientTradeId: o.client_trade_id,
|
|
238
|
+
mint: pos.mint,
|
|
239
|
+
side: o.side,
|
|
240
|
+
amountRaw: o.amount_raw,
|
|
241
|
+
payer: this.d.rail.payer ?? { type: "linked", linkedWalletId: this.d.linkedWalletId ?? "" },
|
|
242
|
+
maxSlippageBps: o.slippage_bps,
|
|
243
|
+
...(prio !== undefined ? { maxPriorityFeeLamports: prio } : {}),
|
|
244
|
+
});
|
|
245
|
+
if (built.status === "executed") {
|
|
246
|
+
// Payer main: Candle signed and sent it inside this call. Linked: an idempotent replay of a landed id.
|
|
247
|
+
this.d.ledger.updateOrder(o.id, { signature: built.signature, signed_at: o.signed_at ?? this.now(), ever_signed: 1, fee_bps: Number(built.fee?.bps ?? 0), min_out_raw: String(built.amounts?.minOutRaw ?? "") });
|
|
248
|
+
const r = await this.landed(this.d.ledger.order(o.id), pos, built.signature, built);
|
|
249
|
+
this.d.ledger.endAttempt(att, this.now(), "replay", null, null);
|
|
250
|
+
return this.apply(o, pos, r);
|
|
251
|
+
}
|
|
252
|
+
this.d.ledger.updateOrder(o.id, { ...(built.expectedOutRaw ? { expected_out_raw: String(built.expectedOutRaw) } : {}), min_out_raw: String(built.minOutRaw ?? ""), fee_bps: Number(built.fee?.bps ?? 0) });
|
|
253
|
+
if (this.d.rail.payer?.type === "main") {
|
|
254
|
+
// A main-payer build executes inline; an unsigned "built" answer spent nothing and is not ours to sign.
|
|
255
|
+
this.d.ledger.endAttempt(att, this.now(), "rejected", "MAIN_NOT_EXECUTED", null);
|
|
256
|
+
return this.apply(o, pos, { kind: "rejected", code: "MAIN_NOT_EXECUTED", detail: "payer main answered built" });
|
|
257
|
+
}
|
|
258
|
+
if (built.chain !== "solana")
|
|
259
|
+
throw Object.assign(new Error("built for another chain"), { code: "WRONG_CHAIN", status: 400 });
|
|
260
|
+
if (built.walletAddress !== cfg.wallet) {
|
|
261
|
+
this.d.ledger.endAttempt(att, this.now(), "rejected", "WRONG_WALLET", JSON.stringify({ walletAddress: built.walletAddress }));
|
|
262
|
+
return this.apply(o, pos, { kind: "rejected", code: "WRONG_WALLET", detail: `build names ${built.walletAddress}` });
|
|
263
|
+
}
|
|
264
|
+
phase = "sign";
|
|
265
|
+
const signed = await this.d.rail.sign(built.artifacts.transactionBase64);
|
|
266
|
+
const sig = signatureOfSigned(signed);
|
|
267
|
+
this.d.ledger.updateOrder(o.id, { signature: sig, signed_at: this.now(), blockhash: blockhashOfSigned(signed), ever_signed: 1, updated_at: this.now() });
|
|
268
|
+
phase = "submit";
|
|
269
|
+
const res = await this.d.rail.submit(o.client_trade_id, signed);
|
|
270
|
+
const r = await this.landed(this.d.ledger.order(o.id), pos, res.signature ?? sig, res);
|
|
271
|
+
this.d.ledger.endAttempt(att, this.now(), r.kind, null, null);
|
|
272
|
+
return this.apply(o, pos, r);
|
|
273
|
+
}
|
|
274
|
+
catch (e) {
|
|
275
|
+
const info = errorInfo(e);
|
|
276
|
+
const ej = errorJson(e);
|
|
277
|
+
this.d.ledger.endAttempt(att, this.now(), "error:" + phase, info.code, ej);
|
|
278
|
+
this.d.ledger.updateOrder(o.id, { last_error_code: info.code, last_error: ej, updated_at: this.now() });
|
|
279
|
+
this.d.log.warn("order_attempt_error", { order: o.id, side: o.side, mint: pos.mint, attempt: n, phase, code: info.code, status: info.status, stage: info.stage, reason: info.reason, logs: info.logs });
|
|
280
|
+
const fresh = this.d.ledger.order(o.id);
|
|
281
|
+
return this.apply(fresh, pos, await this.classify(fresh, pos, info, phase, n), e);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
/** Would this order still be placed now? Sells always; a buy only before its deadline, unpaused, impact passing. */
|
|
285
|
+
async buyStillGood(o, pos) {
|
|
286
|
+
if (o.side !== "buy")
|
|
287
|
+
return true;
|
|
288
|
+
if (o.deadline_at !== null && this.now() > o.deadline_at)
|
|
289
|
+
return false;
|
|
290
|
+
if (this.d.buysPaused?.())
|
|
291
|
+
return false;
|
|
292
|
+
return (await this.recheckBuy(o, pos)) === null;
|
|
293
|
+
}
|
|
294
|
+
/** End a buy that may have executed: book our tx or adopt its tokens if found, re-scan while unexplained, else end. */
|
|
295
|
+
async endBuy(o, pos, end) {
|
|
296
|
+
const r = await this.unexplainedTokens(o, pos, end);
|
|
297
|
+
if (r)
|
|
298
|
+
return this.apply(o, pos, r);
|
|
299
|
+
return this.terminal(this.d.ledger.order(o.id), end.status, end.code, end.detail);
|
|
300
|
+
}
|
|
301
|
+
/** The one same-id probe of a long-built main job: only its answer is used (a signature to reconcile, or a wait). */
|
|
302
|
+
async probe(o, pos) {
|
|
303
|
+
const prio = o.side === "buy" ? this.d.cfg.buy.maxPriorityFeeLamports : this.d.cfg.sell.maxPriorityFeeLamports;
|
|
304
|
+
const att = this.d.ledger.startAttempt(o.id, o.attempts, this.now());
|
|
305
|
+
try {
|
|
306
|
+
const r = await this.d.rail.build({ clientTradeId: o.client_trade_id, mint: pos.mint, side: o.side, amountRaw: o.amount_raw, payer: this.d.rail.payer, maxSlippageBps: o.slippage_bps, ...(prio !== undefined ? { maxPriorityFeeLamports: prio } : {}) });
|
|
307
|
+
this.d.ledger.endAttempt(att, this.now(), "probe:" + String(r?.status ?? "?"), null, null);
|
|
308
|
+
if (r?.status === "executed" && r.signature) {
|
|
309
|
+
this.d.ledger.updateOrder(o.id, { signature: r.signature, signed_at: o.signed_at ?? this.now() });
|
|
310
|
+
return this.apply(o, pos, await this.landed(this.d.ledger.order(o.id), pos, r.signature, r));
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
catch (e) {
|
|
314
|
+
const info = errorInfo(e);
|
|
315
|
+
this.d.ledger.endAttempt(att, this.now(), "probe:error", info.code, errorJson(e));
|
|
316
|
+
if (info.signature)
|
|
317
|
+
this.d.ledger.updateOrder(o.id, { signature: info.signature, signed_at: o.signed_at ?? this.now() });
|
|
318
|
+
this.d.log.info("built_probe", { order: o.id, code: info.code, stage: info.stage, signature: info.signature ?? null });
|
|
319
|
+
}
|
|
320
|
+
this.alert(`order:${o.id}:built_probe`, `order ${o.id} ${o.side} ${pos.mint}: Candle's job stayed built; probed once under the same id`);
|
|
321
|
+
return this.apply(o, pos, { kind: "wait", untilMs: this.now() + 30_000, why: "probed a long-built job" });
|
|
322
|
+
}
|
|
323
|
+
/** Before rebuilding a buy, the market must still be the one the filter approved (no chasing a pump). */
|
|
324
|
+
async recheckBuy(o, pos) {
|
|
325
|
+
let v;
|
|
326
|
+
try {
|
|
327
|
+
v = (await this.d.rpc.call("getAccountInfo", [candleCurve(pos.mint), { encoding: "base64", commitment: "confirmed" }]))?.value;
|
|
328
|
+
}
|
|
329
|
+
catch (e) {
|
|
330
|
+
return this.readFailed(o, pos, errorInfo(e).code, "curve read failed");
|
|
331
|
+
}
|
|
332
|
+
try {
|
|
333
|
+
const c = decodeCandleCurve(v);
|
|
334
|
+
if (c.quoteMint !== WSOL)
|
|
335
|
+
return { kind: "rejected", code: "QUOTE_MINT", detail: "curve is not SOL-quoted" };
|
|
336
|
+
const bps = buyImpact(c, BigInt(o.amount_raw)).impactBps;
|
|
337
|
+
if (bps > this.d.cfg.filters.maxImpactBps)
|
|
338
|
+
return { kind: "rejected", code: "IMPACT", detail: `impact ${bps} bps on retry` };
|
|
339
|
+
return null;
|
|
340
|
+
}
|
|
341
|
+
catch (e) {
|
|
342
|
+
return { kind: "rejected", code: "CURVE", detail: String(e.message) };
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
async classify(o, pos, info, phase, n) {
|
|
346
|
+
const back = this.backoffMs(n);
|
|
347
|
+
if (info.stage === "executed" || info.reason === "prior_attempt_on_chain") {
|
|
348
|
+
const sig = info.signature ?? o.signature;
|
|
349
|
+
if (sig) {
|
|
350
|
+
this.d.ledger.updateOrder(o.id, { signature: sig, signed_at: o.signed_at ?? this.now(), ever_signed: 1 });
|
|
351
|
+
return this.landed(this.d.ledger.order(o.id), pos, sig, null);
|
|
352
|
+
}
|
|
353
|
+
// On chain per Candle but no signature in hand: Candle's job record has it; read it next sweep.
|
|
354
|
+
return { kind: "wait", untilMs: this.now() + 5_000, why: "landed per Candle; reading its job" };
|
|
355
|
+
}
|
|
356
|
+
if (info.stage === "reverted" || info.code === "TRADE_REVERTED")
|
|
357
|
+
return this.revertedOutcome(pos, info.signature ?? o.signature);
|
|
358
|
+
if (info.code === "IDEMPOTENCY_CONFLICT") {
|
|
359
|
+
// Something was built or signed under this id and may be on chain (unconfirmed, in flight, unprovable):
|
|
360
|
+
// never fail it, never rebuild over it. Reconcile the signature and Candle's job until it settles.
|
|
361
|
+
if (info.signature && !o.signature)
|
|
362
|
+
this.d.ledger.updateOrder(o.id, { signature: info.signature, signed_at: this.now(), ever_signed: 1 });
|
|
363
|
+
const after = info.retryAfter ? Math.max(0, info.retryAfter - this.now()) : 0;
|
|
364
|
+
return { kind: "wait", untilMs: this.now() + Math.max(back, after, 10_000), why: `idempotency conflict (${info.stage ?? info.reason ?? "?"})` };
|
|
365
|
+
}
|
|
366
|
+
if (info.code === "RATE_LIMITED" || info.code === "DAILY_CAP_REACHED") {
|
|
367
|
+
const after = info.retryAfter ? Math.max(0, info.retryAfter - this.now()) : back;
|
|
368
|
+
return { kind: "retry", code: info.code, detail: "rate limited", afterMs: Math.max(after, back) };
|
|
369
|
+
}
|
|
370
|
+
if (this.d.rail?.payer?.type === "main" && phase === "build") {
|
|
371
|
+
// Payer main executes inside build, so a failed build may have spent. Candle's own non-retryable 4xx (no stage)
|
|
372
|
+
// is a refusal before execution. Anything else may have executed: mark it possibly spent; the next attempt reads
|
|
373
|
+
// Candle's job first, and a same-id rebuild is Candle's replay of that trade, never a second one.
|
|
374
|
+
// A refusal only when it names nothing that ran: no signature, no stage, nothing recorded.
|
|
375
|
+
if (info.candle && !info.retryable && (info.status ?? 0) >= 400 && (info.status ?? 0) < 500 && !info.signature && !info.stage && info.recorded === undefined) {
|
|
376
|
+
// Proven unspent only when this was the first attempt (no earlier build could have run).
|
|
377
|
+
if (n === 1) {
|
|
378
|
+
this.d.ledger.updateOrder(o.id, { ever_signed: 0 });
|
|
379
|
+
return { kind: "rejected", code: info.code, detail: "build refused" };
|
|
380
|
+
}
|
|
381
|
+
// An earlier attempt may have executed: the same wallet/tx check as any ending buy; stays counted.
|
|
382
|
+
const detail = "build refused after an earlier attempt that may have run";
|
|
383
|
+
if (o.side === "buy") {
|
|
384
|
+
const adopt = await this.unexplainedTokens(o, pos, { status: "rejected", code: info.code, detail });
|
|
385
|
+
if (adopt)
|
|
386
|
+
return adopt;
|
|
387
|
+
}
|
|
388
|
+
return { kind: "rejected", code: info.code, detail };
|
|
389
|
+
}
|
|
390
|
+
if (info.signature) {
|
|
391
|
+
this.d.ledger.updateOrder(o.id, { signature: info.signature, signed_at: this.now() });
|
|
392
|
+
return { kind: "wait", untilMs: this.now() + 5_000, why: "main-payer error names a signature; reconciling" };
|
|
393
|
+
}
|
|
394
|
+
return { kind: "retry", code: info.code, detail: "main-payer build failed; reconciling", afterMs: back };
|
|
395
|
+
}
|
|
396
|
+
if (phase === "build" || phase === "sign") {
|
|
397
|
+
// Nothing of this attempt is on the wire. Only Candle's own non-retryable 4xx is a definite refusal.
|
|
398
|
+
if (info.candle && !info.retryable && (info.status ?? 0) >= 400 && (info.status ?? 0) < 500)
|
|
399
|
+
return { kind: "rejected", code: info.code, detail: `${phase} refused` };
|
|
400
|
+
return { kind: "retry", code: info.code, detail: `${phase} failed`, afterMs: back };
|
|
401
|
+
}
|
|
402
|
+
// submit: the transaction may have been broadcast (Candle's submit does not say whether its preflight ran).
|
|
403
|
+
// Wait, then reconcile the signature on chain and by blockhash expiry before any rebuild.
|
|
404
|
+
return { kind: "wait", untilMs: this.now() + Math.max(back, 10_000), why: `submit error ${info.code}` };
|
|
405
|
+
}
|
|
406
|
+
async revertedOutcome(pos, sig) {
|
|
407
|
+
// Book the fee the revert cost from its transaction when it can be read.
|
|
408
|
+
if (!sig)
|
|
409
|
+
return { kind: "reverted", fill: null };
|
|
410
|
+
const fill = await getTransaction(this.d.rpc, sig).then((tx) => (tx ? fillFromTx(tx, this.d.cfg.wallet, pos.mint) : null)).catch(() => null);
|
|
411
|
+
return { kind: "reverted", fill };
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* A possibly executed buy about to end: find what it did to the wallet before ending it. In order:
|
|
415
|
+
* 1. our transaction(s) in the token account's history since the order was made (buys of about the ticket that no
|
|
416
|
+
* order has booked): booked from the transaction; two or more (a double execution) are all booked, alerted
|
|
417
|
+
* 2. tokens received since the order in unbooked transactions, up to a loose cap on the order's expected fill
|
|
418
|
+
* 3. tokens in the wallet that nothing explains yet: the history or a transaction may lag behind the balance, so
|
|
419
|
+
* the order stays pending and the scan repeats on the backoff (bounded by ADOPT_SCAN_CAP, alerted)
|
|
420
|
+
* Returns null when the order can end with nothing adopted. From the first call on the order is `ending`: later
|
|
421
|
+
* attempts only scan, never build.
|
|
422
|
+
*/
|
|
423
|
+
async unexplainedTokens(o, pos, end) {
|
|
424
|
+
const cur = this.d.ledger.order(o.id)?.ending;
|
|
425
|
+
const endingAt = cur ? Number(JSON.parse(cur).at ?? 0) : this.now();
|
|
426
|
+
if (!cur)
|
|
427
|
+
this.d.ledger.updateOrder(o.id, { ending: JSON.stringify({ ...end, at: endingAt }) });
|
|
428
|
+
const scan = await this.scanSince(o, pos);
|
|
429
|
+
if ("kind" in scan)
|
|
430
|
+
return scan;
|
|
431
|
+
const { found, gained, incomplete } = scan;
|
|
432
|
+
if (found.length === 1) {
|
|
433
|
+
this.d.ledger.updateOrder(o.id, { signature: found[0].signature, signed_at: o.signed_at ?? this.now() });
|
|
434
|
+
this.alert(`order:${o.id}:found_tx`, `order ${o.id} buy ${pos.mint}: Candle's job is not confirmed, but its transaction ${found[0].signature} is on chain; booked from it`);
|
|
435
|
+
return { kind: "filled", fill: found[0], result: null, source: "onchain" };
|
|
436
|
+
}
|
|
437
|
+
if (found.length > 1) {
|
|
438
|
+
// Two or more of our buys under one order: book them all, so exits manage every token. Alerted.
|
|
439
|
+
const sum = (k) => found.reduce((t, f) => t + f[k], 0n);
|
|
440
|
+
const fill = { ...found[0], tokenDeltaRaw: sum("tokenDeltaRaw"), solDeltaLamports: sum("solDeltaLamports"), networkFeeLamports: sum("networkFeeLamports"), rentLamports: sum("rentLamports"), swapLamports: sum("swapLamports") };
|
|
441
|
+
const sigs = found.map((f) => f.signature);
|
|
442
|
+
this.d.ledger.updateOrder(o.id, { signature: sigs[0], signed_at: o.signed_at ?? this.now(), extra_signatures: JSON.stringify(sigs.slice(1)) });
|
|
443
|
+
this.alert(`order:${o.id}:double_execution`, `order ${o.id} buy ${pos.mint}: ${sigs.length} transactions of ours landed under one order (${sigs.join(", ")}); all booked`);
|
|
444
|
+
return { kind: "filled", fill, result: { signatures: sigs }, source: "onchain" };
|
|
445
|
+
}
|
|
446
|
+
// No transaction of ours: unexplained tokens received since the order, up to a loose cap on what this order could
|
|
447
|
+
// have received (its expected fill plus slippage, x1.5 for a better fill than at decision time), are adopted.
|
|
448
|
+
const bal = await tokenBalance(this.d.rpc, this.d.cfg.wallet, pos.mint);
|
|
449
|
+
if (bal === null)
|
|
450
|
+
return this.readFailed(o, pos, "BALANCE_UNREADABLE", "wallet balance unreadable before ending a possibly executed buy");
|
|
451
|
+
const others = this.d.ledger.positionsByStatus("opening", "open", "exit_stuck").filter((p) => p.mint === pos.mint && p.id !== pos.id && !!p.dry === !!pos.dry).reduce((s, p) => s + BigInt(p.remaining_raw), 0n);
|
|
452
|
+
const free = bal - others;
|
|
453
|
+
// Only what arrived after the order was made can be its fill: a bag already there is someone else's.
|
|
454
|
+
const extra = free < gained ? free : gained;
|
|
455
|
+
if (extra <= 0n) {
|
|
456
|
+
// Nothing to adopt. Scan again (bounded) when tokens are there that nothing explains (the history or the
|
|
457
|
+
// transaction may lag the balance), when the history could not be fully read, or while the ending is young
|
|
458
|
+
// (the balance itself may lag a trade that just landed).
|
|
459
|
+
const young = this.now() - endingAt < ENDING_MIN_MS;
|
|
460
|
+
if (free <= 0n && !incomplete && !young)
|
|
461
|
+
return null;
|
|
462
|
+
const n = (this.d.ledger.order(o.id)?.adopt_scans ?? 0) + 1;
|
|
463
|
+
if (n <= ADOPT_SCAN_CAP) {
|
|
464
|
+
this.d.ledger.updateOrder(o.id, { adopt_scans: n });
|
|
465
|
+
if (free > 0n || incomplete)
|
|
466
|
+
this.alert(`order:${o.id}:rescan`, `order ${o.id} buy ${pos.mint}: ${free > 0n ? `the wallet holds ${free} tokens of this coin no position explains` : "the token account history is incomplete"}; scanning again before ending the order`);
|
|
467
|
+
return { kind: "wait", untilMs: this.now() + this.backoffMs(n), why: `unexplained tokens, re-scan ${n}/${ADOPT_SCAN_CAP}` };
|
|
468
|
+
}
|
|
469
|
+
if (free > 0n || incomplete)
|
|
470
|
+
this.alert(`order:${o.id}:unexplained_tokens`, `order ${o.id} buy ${pos.mint}: ${free > 0n ? `the wallet holds ${free} tokens of this coin no position explains` : "the history stayed incomplete"}, none found received since the order after ${ADOPT_SCAN_CAP} scans; not adopted (\`sell\` reaches them)`);
|
|
471
|
+
return null;
|
|
472
|
+
}
|
|
473
|
+
const cap = this.adoptCap(o);
|
|
474
|
+
if (cap === null || extra > cap) {
|
|
475
|
+
this.alert(`order:${o.id}:unexplained_tokens`, `order ${o.id} buy ${pos.mint}: the wallet holds ${extra} unexplained tokens received since the order (cap ${cap ?? "unknown"}); not adopted (\`sell\` reaches them)`);
|
|
476
|
+
return null;
|
|
477
|
+
}
|
|
478
|
+
this.alert(`order:${o.id}:adopted`, `order ${o.id} buy ${pos.mint}: Candle's job is not confirmed and no transaction was found; adopted ${extra} unexplained tokens (within the order's cap ${cap})`);
|
|
479
|
+
return { kind: "filled", fill: null, result: { fallbackOut: extra.toString() }, source: "wallet" };
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* The token account history since the order was made: `found` are our buys of this order (about the ticket's SOL,
|
|
483
|
+
* landed inside one of the order's attempt windows, not booked by any order); `gained` is the net tokens received
|
|
484
|
+
* since the order in unbooked transactions that spent SOL (a transfer-in is not a fill). Paged back to the order's
|
|
485
|
+
* creation; `incomplete` when a transaction or its time could not be read. A read failure returns a wait outcome.
|
|
486
|
+
*/
|
|
487
|
+
async scanSince(o, pos) {
|
|
488
|
+
const accts = await tokenAccounts(this.d.rpc, this.d.cfg.wallet, pos.mint);
|
|
489
|
+
if (accts === null)
|
|
490
|
+
return this.readFailed(o, pos, "BALANCE_UNREADABLE", "token accounts unreadable before ending a possibly executed buy");
|
|
491
|
+
const booked = new Set(this.d.ledger.bookedSignatures());
|
|
492
|
+
const since = Math.floor(o.created_at / 1000) - 60;
|
|
493
|
+
const ticket = BigInt(o.amount_raw);
|
|
494
|
+
// A build of ours can land from its start until its blockhash dies after the call returned (or timed out).
|
|
495
|
+
const windows = this.d.ledger.attemptsFor(o.id).map((a) => [Math.floor(a.started_at / 1000) - 10, Math.ceil((a.ended_at ?? this.now()) / 1000) + ATTEMPT_LAND_SEC]);
|
|
496
|
+
const inWindow = (bt) => windows.some(([a, b]) => bt >= a && bt <= b);
|
|
497
|
+
const found = [];
|
|
498
|
+
const seen = new Set();
|
|
499
|
+
let gained = 0n;
|
|
500
|
+
let incomplete = false;
|
|
501
|
+
for (const a of accts) {
|
|
502
|
+
let before;
|
|
503
|
+
let done = false;
|
|
504
|
+
for (let page = 0; page < ADOPT_PAGES && !done; page++) {
|
|
505
|
+
let sigs = [];
|
|
506
|
+
try {
|
|
507
|
+
sigs = (await this.d.rpc.call("getSignaturesForAddress", [a, { limit: 100, commitment: "confirmed", ...(before ? { before } : {}) }])) ?? [];
|
|
508
|
+
}
|
|
509
|
+
catch (e) {
|
|
510
|
+
return this.readFailed(o, pos, errorInfo(e).code, "token account history unreadable");
|
|
511
|
+
}
|
|
512
|
+
if (sigs.length < 100)
|
|
513
|
+
done = true;
|
|
514
|
+
for (const s of sigs) {
|
|
515
|
+
if (!s?.signature)
|
|
516
|
+
continue;
|
|
517
|
+
before = s.signature;
|
|
518
|
+
if (typeof s.blockTime === "number" && s.blockTime < since) {
|
|
519
|
+
done = true; // newest first: everything after this is older still
|
|
520
|
+
break;
|
|
521
|
+
}
|
|
522
|
+
if (s.err || booked.has(s.signature) || seen.has(s.signature))
|
|
523
|
+
continue;
|
|
524
|
+
seen.add(s.signature);
|
|
525
|
+
const tx = await getTransaction(this.d.rpc, s.signature).catch(() => null);
|
|
526
|
+
if (!tx) {
|
|
527
|
+
incomplete = true;
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
530
|
+
const bt = typeof tx.blockTime === "number" ? tx.blockTime : typeof s.blockTime === "number" ? s.blockTime : null;
|
|
531
|
+
if (bt === null) {
|
|
532
|
+
incomplete = true; // no time to place it after the order: neither counted nor dropped for good
|
|
533
|
+
continue;
|
|
534
|
+
}
|
|
535
|
+
if (bt < since)
|
|
536
|
+
continue;
|
|
537
|
+
let f;
|
|
538
|
+
try {
|
|
539
|
+
f = fillFromTx(tx, this.d.cfg.wallet, pos.mint);
|
|
540
|
+
}
|
|
541
|
+
catch {
|
|
542
|
+
incomplete = true; // an unreadable transaction (no meta): it may be ours
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
if (f.err)
|
|
546
|
+
continue;
|
|
547
|
+
const spent = -f.swapLamports;
|
|
548
|
+
if (f.tokenDeltaRaw > 0n && spent <= 0n)
|
|
549
|
+
continue; // received without paying: a transfer or airdrop
|
|
550
|
+
gained += f.tokenDeltaRaw;
|
|
551
|
+
if (f.tokenDeltaRaw > 0n && spent >= ticket && spent <= (ticket * 1100n) / 1000n && inWindow(bt))
|
|
552
|
+
found.push(f);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
if (!done)
|
|
556
|
+
incomplete = true;
|
|
557
|
+
}
|
|
558
|
+
return { found, gained, incomplete };
|
|
559
|
+
}
|
|
560
|
+
/** The adoption cap: the order's expected fill plus slippage, x1.5 (a better fill than at decision time). */
|
|
561
|
+
adoptCap(o) {
|
|
562
|
+
const expected = o.expected_out_raw && /^\d+$/.test(o.expected_out_raw) ? BigInt(o.expected_out_raw) : null;
|
|
563
|
+
return expected === null ? null : (expected * BigInt(10_000 + o.slippage_bps) * 3n) / 20000n;
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* For `sell` on a coin whose buy ended failed or rejected: how many wallet tokens that buy can claim. Our own
|
|
567
|
+
* transaction(s) found in its attempt windows (their tokens, their cost), else tokens received since the order for SOL,
|
|
568
|
+
* up to the adoption cap (cost the ticket). Never a bag that was already there or arrived by transfer.
|
|
569
|
+
*/
|
|
570
|
+
async reopenable(orderId) {
|
|
571
|
+
const o = this.d.ledger.order(orderId);
|
|
572
|
+
const pos = o && this.d.ledger.position(o.position_id);
|
|
573
|
+
if (!o || !pos || o.side !== "buy")
|
|
574
|
+
return { why: "no such buy" };
|
|
575
|
+
const scan = await this.scanSince(o, pos);
|
|
576
|
+
if ("kind" in scan)
|
|
577
|
+
return { why: "token account history unreadable" };
|
|
578
|
+
const bal = await tokenBalance(this.d.rpc, this.d.cfg.wallet, pos.mint);
|
|
579
|
+
if (bal === null)
|
|
580
|
+
return { why: "wallet balance unreadable" };
|
|
581
|
+
const others = this.d.ledger.positionsByStatus("opening", "open", "exit_stuck").filter((p) => p.mint === pos.mint && p.id !== pos.id && !!p.dry === !!pos.dry).reduce((t, p) => t + BigInt(p.remaining_raw), 0n);
|
|
582
|
+
const free = bal - others;
|
|
583
|
+
const min = (a, b) => (a < b ? a : b);
|
|
584
|
+
if (scan.found.length) {
|
|
585
|
+
const tokens = scan.found.reduce((t, f) => t + f.tokenDeltaRaw, 0n);
|
|
586
|
+
const cost = scan.found.reduce((t, f) => t - f.swapLamports, 0n);
|
|
587
|
+
const amount = min(free, tokens);
|
|
588
|
+
return amount > 0n ? { amount, costLamports: cost, signatures: scan.found.map((f) => f.signature) } : { why: "the wallet holds none unexplained" };
|
|
589
|
+
}
|
|
590
|
+
const cap = this.adoptCap(o);
|
|
591
|
+
if (cap === null)
|
|
592
|
+
return { why: "the order has no expected fill to cap a claim" };
|
|
593
|
+
const amount = min(min(free, scan.gained), cap);
|
|
594
|
+
if (amount <= 0n)
|
|
595
|
+
return { why: free > 0n ? `the wallet's ${free} unexplained tokens were not received since the order` : "the wallet holds none unexplained" };
|
|
596
|
+
const ticket = BigInt(o.amount_raw);
|
|
597
|
+
return { amount, costLamports: ticket + (ticket * BigInt(o.fee_bps ?? 0)) / 10000n, signatures: [] };
|
|
598
|
+
}
|
|
599
|
+
/** A status or job read failed: no attempt is spent; reads are counted, alerted in buckets and backed off. */
|
|
600
|
+
readFailed(o, pos, code, why) {
|
|
601
|
+
const n = (this.d.ledger.order(o.id)?.read_failures ?? 0) + 1;
|
|
602
|
+
this.d.ledger.updateOrder(o.id, { read_failures: n });
|
|
603
|
+
const bucket = n >= 20 ? "20+" : n >= 5 ? "5+" : null;
|
|
604
|
+
if (bucket)
|
|
605
|
+
this.alert(`order:${o.id}:read_failures:${bucket}`, `order ${o.id} ${o.side} ${pos.mint}: ${n} failed reads (${why}, ${code})`);
|
|
606
|
+
return { kind: "wait", untilMs: this.now() + this.backoffMs(Math.min(n, 30)), why };
|
|
607
|
+
}
|
|
608
|
+
/** The signature landed: read its transaction once and book from it; if unreadable, come back later. */
|
|
609
|
+
async landed(o, pos, signature, result) {
|
|
610
|
+
let tx = null;
|
|
611
|
+
try {
|
|
612
|
+
tx = await getTransaction(this.d.rpc, signature);
|
|
613
|
+
}
|
|
614
|
+
catch {
|
|
615
|
+
tx = null;
|
|
616
|
+
}
|
|
617
|
+
if (tx) {
|
|
618
|
+
const fill = fillFromTx(tx, this.d.cfg.wallet, pos.mint);
|
|
619
|
+
if (fill.err)
|
|
620
|
+
return { kind: "reverted", fill };
|
|
621
|
+
return { kind: "filled", fill, result, source: "onchain" };
|
|
622
|
+
}
|
|
623
|
+
// It landed, so never conclude "nothing arrived". Read again later; after TX_READ_CAP failed reads book from
|
|
624
|
+
// Candle's numbers: actualOutRaw (from this result, or by replaying confirm), else the build's minOutRaw. Alerted.
|
|
625
|
+
const n = o.tx_read_failures + 1;
|
|
626
|
+
this.d.ledger.updateOrder(o.id, { tx_read_failures: n });
|
|
627
|
+
if (n < TX_READ_CAP)
|
|
628
|
+
return { kind: "wait", untilMs: this.now() + this.backoffMs(n), why: `transaction ${signature} unreadable (${n})` };
|
|
629
|
+
let actual = result?.amounts?.actualOutRaw;
|
|
630
|
+
if (!(typeof actual === "string" && /^\d+$/.test(actual)) && this.d.rail) {
|
|
631
|
+
try {
|
|
632
|
+
actual = (await this.d.rail.confirm(o.client_trade_id, signature))?.amounts?.actualOutRaw;
|
|
633
|
+
}
|
|
634
|
+
catch {
|
|
635
|
+
actual = undefined;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
const source = typeof actual === "string" && /^\d+$/.test(actual) ? "server" : "minout";
|
|
639
|
+
const out = source === "server" ? actual : result?.amounts?.minOutRaw ?? o.min_out_raw;
|
|
640
|
+
if (typeof out !== "string" || !/^\d+$/.test(out) || BigInt(out) <= 0n) {
|
|
641
|
+
this.alert(`order:${o.id}:qty_unknown`, `order ${o.id} landed (${signature}) but its fill cannot be read and Candle gave no amount`);
|
|
642
|
+
return { kind: "wait", untilMs: this.now() + this.d.cfg.retry.maxDelayMs, why: "fill unknown" };
|
|
643
|
+
}
|
|
644
|
+
this.alert(`qty_fallback:${o.id}`, `order ${o.id} booked from ${source}: transaction ${signature} unreadable`);
|
|
645
|
+
return { kind: "filled", fill: null, result: { fallbackOut: out, fee: result?.fee }, source };
|
|
646
|
+
}
|
|
647
|
+
/** Settle a persisted signature. Returns an outcome when it is decided, or null to go on building. */
|
|
648
|
+
async reconcileSignature(o, pos) {
|
|
649
|
+
let st;
|
|
650
|
+
try {
|
|
651
|
+
st = await signatureStatus(this.d.rpc, o.signature);
|
|
652
|
+
}
|
|
653
|
+
catch (e) {
|
|
654
|
+
return this.readFailed(o, pos, errorInfo(e).code, "status read failed");
|
|
655
|
+
}
|
|
656
|
+
if (o.read_failures)
|
|
657
|
+
this.d.ledger.updateOrder(o.id, { read_failures: 0 });
|
|
658
|
+
// Only confirmed or finalized counts as landed: a processed transaction can still drop.
|
|
659
|
+
if (st.found && st.confirmationStatus === "processed")
|
|
660
|
+
return { kind: "wait", untilMs: this.now() + 5_000, why: "processed, not yet confirmed" };
|
|
661
|
+
if (st.found && !st.err)
|
|
662
|
+
return this.landed(o, pos, o.signature, null);
|
|
663
|
+
if (st.found && st.err)
|
|
664
|
+
return this.revertedOutcome(pos, o.signature);
|
|
665
|
+
// Candle's job says this signature is confirmed: never clear it; read again until the RPC serves it.
|
|
666
|
+
if (o.candle_confirmed === 1)
|
|
667
|
+
return this.landed(o, pos, o.signature, null);
|
|
668
|
+
// Not on chain. It is dead only once its blockhash can no longer be used (judged by the chain's block height).
|
|
669
|
+
if (this.now() - (o.signed_at ?? 0) < SIGNATURE_MIN_AGE_MS)
|
|
670
|
+
return { kind: "wait", untilMs: (o.signed_at ?? this.now()) + SIGNATURE_MIN_AGE_MS, why: "signature may still land" };
|
|
671
|
+
if (!o.blockhash) {
|
|
672
|
+
// A signature learned from Candle (no transaction bytes here): wait the conservative maximum, then recheck.
|
|
673
|
+
if (this.now() - (o.signed_at ?? 0) < 180_000)
|
|
674
|
+
return { kind: "wait", untilMs: (o.signed_at ?? this.now()) + 180_000, why: "signature may still land" };
|
|
675
|
+
}
|
|
676
|
+
else {
|
|
677
|
+
let valid;
|
|
678
|
+
try {
|
|
679
|
+
valid = await blockhashValid(this.d.rpc, o.blockhash);
|
|
680
|
+
}
|
|
681
|
+
catch (e) {
|
|
682
|
+
return this.readFailed(o, pos, errorInfo(e).code, "blockhash check failed");
|
|
683
|
+
}
|
|
684
|
+
if (valid)
|
|
685
|
+
return { kind: "wait", untilMs: this.now() + 10_000, why: "blockhash still valid" };
|
|
686
|
+
}
|
|
687
|
+
// Expired: one last status check (it could have landed in the final slots), then clear it so the rebuild under
|
|
688
|
+
// the same clientTradeId is the only live transaction.
|
|
689
|
+
try {
|
|
690
|
+
const last = await signatureStatus(this.d.rpc, o.signature);
|
|
691
|
+
if (last.found)
|
|
692
|
+
return { kind: "wait", untilMs: this.now() + 2_000, why: "landed at the last moment" };
|
|
693
|
+
}
|
|
694
|
+
catch (e) {
|
|
695
|
+
return this.readFailed(o, pos, errorInfo(e).code, "status read failed");
|
|
696
|
+
}
|
|
697
|
+
this.d.ledger.updateOrder(o.id, { signature: null, signed_at: null, blockhash: null, tx_read_failures: 0 });
|
|
698
|
+
return null;
|
|
699
|
+
}
|
|
700
|
+
apply(o, pos, r, err) {
|
|
701
|
+
const now = this.now();
|
|
702
|
+
const fresh = this.d.ledger.order(o.id);
|
|
703
|
+
switch (r.kind) {
|
|
704
|
+
case "wait":
|
|
705
|
+
this.d.ledger.updateOrder(o.id, { status: "pending", next_attempt_at: r.untilMs, lease_until: 0, updated_at: now });
|
|
706
|
+
return;
|
|
707
|
+
case "retry": {
|
|
708
|
+
// Attempts are counted where they start (a build that may broadcast); reads that fail cost none.
|
|
709
|
+
const attempts = fresh.attempts;
|
|
710
|
+
this.d.ledger.updateOrder(o.id, { status: "pending", next_attempt_at: now + (r.afterMs ?? this.backoffMs(attempts)), lease_until: 0, last_error_code: r.code, updated_at: now, ...(err ? { last_error: errorJson(err) } : {}) });
|
|
711
|
+
const bucket = attempts >= fresh.max_attempts ? "max" : attempts >= 3 ? "3+" : String(attempts);
|
|
712
|
+
this.alert(`order:${o.id}:attempts:${bucket}`, `order ${o.id} ${o.side} ${pos.mint}: ${attempts}/${fresh.max_attempts} attempts, last ${r.code}`);
|
|
713
|
+
// Never terminal here while something may be live: a persisted signature, or a main-payer build that may have
|
|
714
|
+
// executed (step 3 decides after reading Candle's job).
|
|
715
|
+
const maybeLive = !!fresh.signature || (this.d.rail?.payer?.type === "main" && fresh.ever_signed === 1) || fresh.last_error_code === "IDEMPOTENCY_CONFLICT";
|
|
716
|
+
if (attempts >= fresh.max_attempts && !maybeLive)
|
|
717
|
+
this.terminal(this.d.ledger.order(o.id), "failed", r.code);
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
case "rejected":
|
|
721
|
+
this.terminal(fresh, "rejected", r.code, r.detail);
|
|
722
|
+
return;
|
|
723
|
+
case "reverted":
|
|
724
|
+
this.bookReverted(fresh, pos, r.fill);
|
|
725
|
+
return;
|
|
726
|
+
case "filled":
|
|
727
|
+
this.bookFill(fresh, pos, r.fill, r.result, r.source);
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
terminal(o, status, code, detail) {
|
|
732
|
+
this.d.ledger.tx(() => this.terminalTx(o, status, code, detail));
|
|
733
|
+
}
|
|
734
|
+
terminalTx(o, status, code, detail) {
|
|
735
|
+
const now = this.now();
|
|
736
|
+
this.d.ledger.updateOrder(o.id, { status, lease_until: 0, last_error_code: code, updated_at: now });
|
|
737
|
+
const pos = this.d.ledger.position(o.position_id);
|
|
738
|
+
this.d.log.warn("order_terminal", { order: o.id, side: o.side, mint: pos.mint, status, code, detail, attempts: o.attempts });
|
|
739
|
+
this.alert(`order:${o.id}:${status}`, `order ${o.id} ${o.side} ${pos.mint} ${status} (${code}) after ${o.attempts} attempts`);
|
|
740
|
+
if (o.side === "buy") {
|
|
741
|
+
// No spend landed (rejected / failed with no signature on chain) or only fees (reverted).
|
|
742
|
+
if (pos.status === "opening")
|
|
743
|
+
this.d.ledger.updatePosition(pos.id, { status: "failed", closed_at: now, note: `buy ${status}: ${code}` });
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
// Only a refusal or a revert says this exit cannot work. Running out of attempts on network errors, timeouts or
|
|
747
|
+
// 5xx does not: the engine mints the next exit on the position's backoff, with no limit.
|
|
748
|
+
if (status === "failed")
|
|
749
|
+
return;
|
|
750
|
+
const failed = pos.exit_orders_failed + 1;
|
|
751
|
+
const stuck = failed >= this.d.cfg.retry.maxExitOrders;
|
|
752
|
+
this.d.ledger.updatePosition(pos.id, { exit_orders_failed: failed, ...(stuck ? { status: "exit_stuck", note: `exit stuck after ${failed} refused orders (${code})` } : {}) });
|
|
753
|
+
if (stuck)
|
|
754
|
+
this.alert(`position:${pos.id}:exit_stuck`, `position ${pos.id} ${pos.mint}: exits refused ${failed} times; retrying every ${Math.round(this.d.cfg.retry.stuckRetryMs / 60000)} min, or run \`sell\` by hand`);
|
|
755
|
+
}
|
|
756
|
+
bookReverted(o, pos, fill) {
|
|
757
|
+
this.d.ledger.tx(() => {
|
|
758
|
+
const p = this.d.ledger.position(pos.id);
|
|
759
|
+
if (fill)
|
|
760
|
+
this.d.ledger.updatePosition(p.id, { network_fees_lamports: (BigInt(p.network_fees_lamports) + fill.networkFeeLamports).toString() });
|
|
761
|
+
this.d.ledger.updateOrder(o.id, { fill_json: fill ? JSON.stringify(fill, big) : null });
|
|
762
|
+
this.terminal(o, "reverted", "TRADE_REVERTED");
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
bookFill(o, pos, fill, result, source) {
|
|
766
|
+
this.d.ledger.tx(() => this.bookFillTx(o, this.d.ledger.position(pos.id), fill, result, source));
|
|
767
|
+
}
|
|
768
|
+
bookFillTx(o, pos, fill, result, source) {
|
|
769
|
+
const now = this.now();
|
|
770
|
+
const feeBps = BigInt(o.fee_bps ?? 0);
|
|
771
|
+
let tokenDelta;
|
|
772
|
+
let swapLamports;
|
|
773
|
+
let netFee = 0n;
|
|
774
|
+
let rent = 0n;
|
|
775
|
+
if (fill) {
|
|
776
|
+
tokenDelta = fill.tokenDeltaRaw;
|
|
777
|
+
swapLamports = fill.swapLamports;
|
|
778
|
+
netFee = fill.networkFeeLamports;
|
|
779
|
+
rent = fill.rentLamports;
|
|
780
|
+
}
|
|
781
|
+
else {
|
|
782
|
+
// Fallback (alerted): Candle's amount out. The platform fee rides on top of a buy, out of a sell's proceeds.
|
|
783
|
+
const out = BigInt(result.fallbackOut);
|
|
784
|
+
const amount = BigInt(o.amount_raw);
|
|
785
|
+
if (o.side === "buy") {
|
|
786
|
+
tokenDelta = out;
|
|
787
|
+
swapLamports = -(amount + (amount * feeBps) / 10000n);
|
|
788
|
+
}
|
|
789
|
+
else {
|
|
790
|
+
tokenDelta = -amount;
|
|
791
|
+
swapLamports = out - (out * feeBps) / 10000n;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
const fees = BigInt(pos.network_fees_lamports) + netFee;
|
|
795
|
+
const rentTotal = BigInt(pos.rent_lamports) + rent;
|
|
796
|
+
this.d.ledger.updateOrder(o.id, { status: "filled", qty_source: source, fill_json: JSON.stringify({ fill, result: result ?? null }, big), lease_until: 0, updated_at: now });
|
|
797
|
+
if (o.side === "buy") {
|
|
798
|
+
if (tokenDelta <= 0n && fill) {
|
|
799
|
+
// Read from the real transaction: it landed and the wallet gained nothing.
|
|
800
|
+
this.alert(`order:${o.id}:no_tokens`, `buy ${o.id} landed but the wallet gained no ${pos.mint}`);
|
|
801
|
+
this.d.ledger.updatePosition(pos.id, { status: "failed", closed_at: now, note: "buy landed with no token delta", cost_lamports: (-swapLamports).toString(), network_fees_lamports: fees.toString(), rent_lamports: rentTotal.toString() });
|
|
802
|
+
return;
|
|
803
|
+
}
|
|
804
|
+
const cost = -swapLamports;
|
|
805
|
+
const entry = Number(cost) / 1e9 / (Number(tokenDelta) / 10 ** pos.decimals);
|
|
806
|
+
this.d.ledger.updatePosition(pos.id, { status: "open", qty_raw: tokenDelta.toString(), qty_source: source, remaining_raw: tokenDelta.toString(), cost_lamports: cost.toString(), network_fees_lamports: fees.toString(), rent_lamports: rentTotal.toString(), peak_price: entry });
|
|
807
|
+
this.d.log.info("buy_filled", { position: pos.id, mint: pos.mint, qtyRaw: tokenDelta, costLamports: cost, qtySource: source, signature: fill?.signature ?? null });
|
|
808
|
+
if (source !== "onchain" && source !== "dry")
|
|
809
|
+
this.alert(`position:${pos.id}:qty_source:${source}`, `position ${pos.id} quantity booked from ${source}`);
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
const sold = -tokenDelta;
|
|
813
|
+
const remaining = BigInt(pos.remaining_raw) - (sold > 0n ? sold : 0n);
|
|
814
|
+
const proceeds = BigInt(pos.proceeds_lamports) + swapLamports;
|
|
815
|
+
const closed = remaining <= 0n;
|
|
816
|
+
this.d.ledger.updatePosition(pos.id, {
|
|
817
|
+
remaining_raw: (remaining > 0n ? remaining : 0n).toString(),
|
|
818
|
+
proceeds_lamports: proceeds.toString(),
|
|
819
|
+
network_fees_lamports: fees.toString(),
|
|
820
|
+
rent_lamports: rentTotal.toString(),
|
|
821
|
+
// A filled sell (manual or the slow exit_stuck retry) shows the exit works again: clear the count.
|
|
822
|
+
...(closed ? { status: "closed", closed_at: now } : { status: pos.status === "exit_stuck" ? "open" : pos.status }),
|
|
823
|
+
exit_orders_failed: 0,
|
|
824
|
+
});
|
|
825
|
+
this.d.log.info("sell_filled", { position: pos.id, mint: pos.mint, soldRaw: sold, proceedsLamports: swapLamports, remainingRaw: remaining > 0n ? remaining : 0n, closed, qtySource: source, signature: fill?.signature ?? null });
|
|
826
|
+
}
|
|
827
|
+
async dryAttempt(o, pos) {
|
|
828
|
+
const n = o.attempts + 1;
|
|
829
|
+
this.d.ledger.updateOrder(o.id, { attempts: n, updated_at: this.now() });
|
|
830
|
+
const att = this.d.ledger.startAttempt(o.id, n, this.now());
|
|
831
|
+
if (!this.d.dry)
|
|
832
|
+
throw new Error("dry order without a pricer");
|
|
833
|
+
try {
|
|
834
|
+
const amount = BigInt(o.amount_raw);
|
|
835
|
+
let fill;
|
|
836
|
+
if (o.side === "buy") {
|
|
837
|
+
const out = await this.d.dry.buyOut(pos.mint, amount);
|
|
838
|
+
fill = { signature: "dry", slot: null, blockTimeMs: this.now(), tokenDeltaRaw: out, solDeltaLamports: -amount, networkFeeLamports: 0n, rentLamports: 0n, swapLamports: -amount, err: null };
|
|
839
|
+
}
|
|
840
|
+
else {
|
|
841
|
+
const out = await this.d.dry.sellOut(pos.mint, amount, pos.decimals);
|
|
842
|
+
fill = { signature: "dry", slot: null, blockTimeMs: this.now(), tokenDeltaRaw: -amount, solDeltaLamports: out, networkFeeLamports: 0n, rentLamports: 0n, swapLamports: out, err: null };
|
|
843
|
+
}
|
|
844
|
+
this.d.ledger.endAttempt(att, this.now(), "filled", null, null);
|
|
845
|
+
this.bookFill(this.d.ledger.order(o.id), pos, fill, null, "dry");
|
|
846
|
+
}
|
|
847
|
+
catch (e) {
|
|
848
|
+
const info = errorInfo(e);
|
|
849
|
+
this.d.ledger.endAttempt(att, this.now(), "error:dry", info.code, errorJson(e));
|
|
850
|
+
this.apply(this.d.ledger.order(o.id), pos, n >= o.max_attempts ? { kind: "rejected", code: info.code, detail: "dry quote failed" } : { kind: "retry", code: info.code, detail: "dry quote failed", afterMs: this.backoffMs(n) }, e);
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
alert(key, message) {
|
|
854
|
+
this.d.alerter.raise(key, message);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
function big(_k, v) {
|
|
858
|
+
return typeof v === "bigint" ? v.toString() : v;
|
|
859
|
+
}
|