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.

Files changed (66) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/LICENSE +21 -0
  3. package/README.md +400 -2
  4. package/bin/candle-launch-bot +7 -0
  5. package/dist/alerts.d.ts +28 -0
  6. package/dist/alerts.js +82 -0
  7. package/dist/cli.d.ts +3 -0
  8. package/dist/cli.js +321 -0
  9. package/dist/config.d.ts +88 -0
  10. package/dist/config.js +244 -0
  11. package/dist/detect/detector.d.ts +111 -0
  12. package/dist/detect/detector.js +348 -0
  13. package/dist/engine.d.ts +103 -0
  14. package/dist/engine.js +585 -0
  15. package/dist/exec/executor.d.ts +149 -0
  16. package/dist/exec/executor.js +859 -0
  17. package/dist/exec/fills.d.ts +25 -0
  18. package/dist/exec/fills.js +53 -0
  19. package/dist/exec/trader.d.ts +109 -0
  20. package/dist/exec/trader.js +310 -0
  21. package/dist/filters.d.ts +26 -0
  22. package/dist/filters.js +92 -0
  23. package/dist/index.d.ts +5 -0
  24. package/dist/index.js +2 -0
  25. package/dist/init.d.ts +23 -0
  26. package/dist/init.js +192 -0
  27. package/dist/ledger.d.ts +189 -0
  28. package/dist/ledger.js +243 -0
  29. package/dist/log.d.ts +22 -0
  30. package/dist/log.js +40 -0
  31. package/dist/market/curve.d.ts +80 -0
  32. package/dist/market/curve.js +168 -0
  33. package/dist/market/reader.d.ts +37 -0
  34. package/dist/market/reader.js +106 -0
  35. package/dist/redact.d.ts +20 -0
  36. package/dist/redact.js +111 -0
  37. package/dist/solana/base58.d.ts +4 -0
  38. package/dist/solana/base58.js +45 -0
  39. package/dist/solana/logs-ws.d.ts +25 -0
  40. package/dist/solana/logs-ws.js +116 -0
  41. package/dist/solana/pda.d.ts +12 -0
  42. package/dist/solana/pda.js +70 -0
  43. package/dist/solana/rpc.d.ts +29 -0
  44. package/dist/solana/rpc.js +96 -0
  45. package/dist/strategies/hold.d.ts +3 -0
  46. package/dist/strategies/hold.js +6 -0
  47. package/dist/strategies/ladder.d.ts +8 -0
  48. package/dist/strategies/ladder.js +51 -0
  49. package/dist/strategies/load.d.ts +5 -0
  50. package/dist/strategies/load.js +44 -0
  51. package/dist/strategies/preGrad.d.ts +10 -0
  52. package/dist/strategies/preGrad.js +32 -0
  53. package/dist/strategies/time.d.ts +6 -0
  54. package/dist/strategies/time.js +16 -0
  55. package/dist/strategies/tpsl.d.ts +8 -0
  56. package/dist/strategies/tpsl.js +30 -0
  57. package/dist/strategies/types.d.ts +55 -0
  58. package/dist/strategies/types.js +31 -0
  59. package/examples/dry.json +32 -0
  60. package/examples/live-embedded.json +14 -0
  61. package/examples/live-linked.json +15 -0
  62. package/examples/strategies/breakeven-stop.js +22 -0
  63. package/examples/strategies/stale-coin.js +18 -0
  64. package/examples/strategies/timeboxed-tp.js +18 -0
  65. package/package.json +60 -4
  66. package/skills/candle-launch-bot/SKILL.md +71 -0
package/dist/log.js ADDED
@@ -0,0 +1,40 @@
1
+ import { appendFileSync } from "node:fs";
2
+ import { redact } from "./redact.js";
3
+ const ORDER = { debug: 10, info: 20, warn: 30, error: 40 };
4
+ function json(v) {
5
+ return JSON.stringify(v, (_k, x) => (typeof x === "bigint" ? x.toString() : x));
6
+ }
7
+ /** JSON lines to stdout and (optionally) a file; every line is redacted before it leaves the process. */
8
+ export function makeLogger(opts = {}) {
9
+ const min = ORDER[opts.level ?? "info"];
10
+ const now = opts.now ?? Date.now;
11
+ const log = (level, event, fields = {}) => {
12
+ if (ORDER[level] < min)
13
+ return;
14
+ const line = redact(json({ t: new Date(now()).toISOString(), level, event, ...fields }));
15
+ if (opts.stdout !== false)
16
+ process.stdout.write(line + "\n");
17
+ if (opts.file) {
18
+ try {
19
+ appendFileSync(opts.file, line + "\n");
20
+ }
21
+ catch {
22
+ /* the log file must never stop the bot */
23
+ }
24
+ }
25
+ };
26
+ return {
27
+ log,
28
+ info: (e, f) => log("info", e, f),
29
+ warn: (e, f) => log("warn", e, f),
30
+ error: (e, f) => log("error", e, f),
31
+ };
32
+ }
33
+ /** A logger that keeps lines in memory (tests). */
34
+ export function memoryLogger() {
35
+ const lines = [];
36
+ const log = (level, event, fields = {}) => {
37
+ lines.push(JSON.parse(redact(json({ level, event, ...fields }))));
38
+ };
39
+ return { lines, log, info: (e, f) => log("info", e, f), warn: (e, f) => log("warn", e, f), error: (e, f) => log("error", e, f) };
40
+ }
@@ -0,0 +1,80 @@
1
+ /** A getAccountInfo / getMultipleAccounts value with base64 data. */
2
+ export interface AccountValue {
3
+ owner: string;
4
+ data: [string, string] | string[];
5
+ lamports?: number;
6
+ }
7
+ export declare class DecodeError extends Error {
8
+ }
9
+ export interface CandleCurve {
10
+ authority: string;
11
+ baseMint: string;
12
+ quoteMint: string;
13
+ quoteReserve: bigint;
14
+ baseReserve: bigint;
15
+ migrationThreshold: bigint;
16
+ migrated: boolean;
17
+ feeBps: number;
18
+ sqrtPrice: bigint;
19
+ segments: Array<{
20
+ target: bigint;
21
+ liquidity: bigint;
22
+ }>;
23
+ /** Byte @225: 1 on the one `exclusive` launch seen (LEOPOLD), 0 on every other mode. Observed, not from the IDL. */
24
+ flag225: number;
25
+ /** u128 @285: the same on every curve of one preset (likely the start sqrt price). Observed, not from the IDL. */
26
+ presetSqrt: bigint;
27
+ }
28
+ export declare function decodeCandleCurve(v: AccountValue | null | undefined): CandleCurve;
29
+ export type CurveClass = "open";
30
+ /**
31
+ * The SOL `open` preset, read from every SOL-quoted open launch on mainnet at the time of writing (18, every one identical, no exp launch
32
+ * matching): migration threshold, fee, both liquidity segments, and the preset sqrt at @285.
33
+ */
34
+ export declare const OPEN_PRESET: {
35
+ migrationThreshold: bigint;
36
+ feeBps: number;
37
+ flag225: number;
38
+ presetSqrt: bigint;
39
+ segments: {
40
+ target: bigint;
41
+ liquidity: bigint;
42
+ }[];
43
+ };
44
+ /**
45
+ * Launch mode from the curve account alone, for a launch seen on chain before Candle's list has it: `open` only on a
46
+ * full match of the open preset. An exp-custom curve can take any threshold, so nothing short of the whole preset
47
+ * proves open; anything else (exclusive and every exp mode included) returns null and waits for Candle's `tier`.
48
+ */
49
+ export declare function curveClass(c: CandleCurve): CurveClass | null;
50
+ /** Quote per whole token from a Q64.64 sqrt price. */
51
+ export declare function priceFromSqrt(sqrt: bigint, decimals: number, quoteDecimals?: number): number;
52
+ /** Graduation progress 0..1: quote_reserve / migration_threshold, 1 once migrated. */
53
+ export declare function curveProgress(c: CandleCurve): number;
54
+ export interface BuyImpact {
55
+ /** Average price over spot, minus 1 (after the curve fee is taken from the input). */
56
+ impact: number;
57
+ impactBps: number;
58
+ /** The curve's own fee, bps of the input. */
59
+ feeBps: number;
60
+ /** Tokens out (raw) the curve math gives for this size, before slippage. */
61
+ expectedOutRaw: bigint;
62
+ }
63
+ /**
64
+ * Price impact of buying `lamports` of quote on the curve now. Constant-liquidity segments in sqrt price:
65
+ * delta quote = L * delta s / 2^128 (Q64.64), across segments as needed. Throws `buy_past_graduation`
66
+ * when the buy would complete the curve (the remainder would fill on another venue at another price).
67
+ */
68
+ export declare function buyImpact(c: CandleCurve, lamports: bigint): BuyImpact;
69
+ export interface DammPool {
70
+ tokenA: string;
71
+ tokenB: string;
72
+ sqrtMinPrice: bigint;
73
+ sqrtPrice: bigint;
74
+ creator: string;
75
+ }
76
+ export declare function decodeDamm(v: AccountValue | null | undefined): DammPool;
77
+ /** Quote per whole coin from a DAMM v2 pool, whichever side the coin is on. */
78
+ export declare function dammPrice(p: DammPool, mint: string, decimals: number, quoteDecimals?: number): number;
79
+ /** How far a DAMM v2 pool sits above its floor (sqrt_min_price): price/floor - 1. At ~0 nothing can be sold. */
80
+ export declare function dammRoomAboveFloor(p: DammPool): number | null;
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Candle launch-curve and DAMM v2 pool decoding. Pure, no I/O.
3
+ *
4
+ * Candle curve (program 6wXTwJ…dssG, account `Pool`): discriminator 8, authority 32 @8, base_mint @40,
5
+ * quote_mint @72, base_vault @104, quote_vault @136, quote_reserve u64 @168, base_reserve u64 @176,
6
+ * migration_threshold u64 @184, is_migrated bool @192, fee_bps u16 @227, sqrt_price u128 Q64.64 @269,
7
+ * two liquidity segments (target sqrt u128, liquidity u128) @301/@317 and @333/@349. 365 bytes.
8
+ * Spot price (quote per token) = sqrt^2 / 2^128 * 10^(base decimals - quote decimals).
9
+ *
10
+ * DAMM v2 (cp-amm 1.3.4 `Pool`): token_a_mint @168, token_b_mint @200, token_a_vault @232, token_b_vault @264,
11
+ * sqrt_min_price u128 @424, sqrt_price u128 @456, creator @648. Price comes from sqrt_price, never from the
12
+ * vaults (they also hold fees). sqrt_price is token B per token A; the coin may be either side.
13
+ */
14
+ import { b58encode } from "../solana/base58.js";
15
+ import { CANDLE_CURVE_PROGRAM, DAMM_V2_PROGRAM } from "../solana/pda.js";
16
+ /** Anchor discriminator of `account:Pool` (shared with pump-amm's Pool). */
17
+ const POOL_DISCRIMINATOR = Uint8Array.from([0xf1, 0x9a, 0x6d, 0x04, 0x11, 0xb1, 0x6d, 0xbc]);
18
+ const CURVE_LEN = 365;
19
+ const DAMM_MIN_LEN = 680;
20
+ const Q128 = 2n ** 128n;
21
+ export class DecodeError extends Error {
22
+ }
23
+ function bytesOf(v, owner, minLen, what) {
24
+ if (!v)
25
+ throw new DecodeError(`${what}_missing`);
26
+ if (v.owner !== owner)
27
+ throw new DecodeError(`${what}_owner`);
28
+ const d = v.data;
29
+ if (!Array.isArray(d) || d[1] !== "base64" || typeof d[0] !== "string")
30
+ throw new DecodeError(`${what}_layout`);
31
+ const b = new Uint8Array(Buffer.from(d[0], "base64"));
32
+ if (b.length < minLen)
33
+ throw new DecodeError(`${what}_layout`);
34
+ return b;
35
+ }
36
+ function u64(b, at) {
37
+ return new DataView(b.buffer, b.byteOffset).getBigUint64(at, true);
38
+ }
39
+ function u128(b, at) {
40
+ return u64(b, at) | (u64(b, at + 8) << 64n);
41
+ }
42
+ function u16(b, at) {
43
+ return new DataView(b.buffer, b.byteOffset).getUint16(at, true);
44
+ }
45
+ function key(b, at) {
46
+ return b58encode(b.subarray(at, at + 32));
47
+ }
48
+ export function decodeCandleCurve(v) {
49
+ const b = bytesOf(v, CANDLE_CURVE_PROGRAM, CURVE_LEN, "curve");
50
+ for (let i = 0; i < 8; i++)
51
+ if (b[i] !== POOL_DISCRIMINATOR[i])
52
+ throw new DecodeError("curve_layout");
53
+ return {
54
+ authority: key(b, 8),
55
+ baseMint: key(b, 40),
56
+ quoteMint: key(b, 72),
57
+ quoteReserve: u64(b, 168),
58
+ baseReserve: u64(b, 176),
59
+ migrationThreshold: u64(b, 184),
60
+ migrated: b[192] !== 0,
61
+ feeBps: u16(b, 227),
62
+ sqrtPrice: u128(b, 269),
63
+ segments: [
64
+ { target: u128(b, 301), liquidity: u128(b, 317) },
65
+ { target: u128(b, 333), liquidity: u128(b, 349) },
66
+ ],
67
+ flag225: b[225],
68
+ presetSqrt: u128(b, 285),
69
+ };
70
+ }
71
+ /**
72
+ * The SOL `open` preset, read from every SOL-quoted open launch on mainnet at the time of writing (18, every one identical, no exp launch
73
+ * matching): migration threshold, fee, both liquidity segments, and the preset sqrt at @285.
74
+ */
75
+ export const OPEN_PRESET = {
76
+ migrationThreshold: 80000000000n,
77
+ feeBps: 100,
78
+ flag225: 0,
79
+ presetSqrt: 91862415507570671n,
80
+ segments: [
81
+ { target: 218935341325369486n, liquidity: 117494894994231126086956521739130n },
82
+ { target: 521787756357285822n, liquidity: 40600059905644895696950032446463n },
83
+ ],
84
+ };
85
+ /**
86
+ * Launch mode from the curve account alone, for a launch seen on chain before Candle's list has it: `open` only on a
87
+ * full match of the open preset. An exp-custom curve can take any threshold, so nothing short of the whole preset
88
+ * proves open; anything else (exclusive and every exp mode included) returns null and waits for Candle's `tier`.
89
+ */
90
+ export function curveClass(c) {
91
+ const p = OPEN_PRESET;
92
+ const same = c.migrationThreshold === p.migrationThreshold && c.feeBps === p.feeBps && c.flag225 === p.flag225 && c.presetSqrt === p.presetSqrt &&
93
+ c.segments.length === 2 && c.segments.every((s, i) => s.target === p.segments[i].target && s.liquidity === p.segments[i].liquidity);
94
+ return same ? "open" : null;
95
+ }
96
+ /** Quote per whole token from a Q64.64 sqrt price. */
97
+ export function priceFromSqrt(sqrt, decimals, quoteDecimals = 9) {
98
+ return (Number(sqrt * sqrt) / Number(Q128)) * 10 ** (decimals - quoteDecimals);
99
+ }
100
+ /** Graduation progress 0..1: quote_reserve / migration_threshold, 1 once migrated. */
101
+ export function curveProgress(c) {
102
+ if (c.migrated)
103
+ return 1;
104
+ if (c.migrationThreshold === 0n)
105
+ throw new DecodeError("curve_layout");
106
+ return Math.min(1, Number(c.quoteReserve) / Number(c.migrationThreshold));
107
+ }
108
+ /**
109
+ * Price impact of buying `lamports` of quote on the curve now. Constant-liquidity segments in sqrt price:
110
+ * delta quote = L * delta s / 2^128 (Q64.64), across segments as needed. Throws `buy_past_graduation`
111
+ * when the buy would complete the curve (the remainder would fill on another venue at another price).
112
+ */
113
+ export function buyImpact(c, lamports) {
114
+ if (c.migrated)
115
+ throw new DecodeError("curve_complete");
116
+ let left = (lamports * BigInt(10_000 - c.feeBps)) / 10000n;
117
+ if (c.quoteReserve + left >= c.migrationThreshold)
118
+ throw new DecodeError("buy_past_graduation");
119
+ const s0 = c.sqrtPrice;
120
+ if (s0 === 0n)
121
+ throw new DecodeError("curve_reserves");
122
+ let s = s0;
123
+ let out = 0n;
124
+ for (const { target, liquidity } of c.segments) {
125
+ if (left <= 0n || liquidity === 0n || s >= target)
126
+ continue;
127
+ const room = (liquidity * (target - s)) / Q128;
128
+ const step = left < room ? left : room;
129
+ const s1 = s + (step * Q128) / liquidity;
130
+ // With quote = L * ds / 2^128, the matching base side is L * (s1 - s) / (s * s1).
131
+ out += (liquidity * (s1 - s)) / (s * s1);
132
+ s = s1;
133
+ left -= step;
134
+ }
135
+ if (left > 0n)
136
+ throw new DecodeError("buy_past_graduation");
137
+ const impact = Number(s) / Number(s0) - 1;
138
+ return { impact, impactBps: Math.round(impact * 10_000), feeBps: c.feeBps, expectedOutRaw: out };
139
+ }
140
+ export function decodeDamm(v) {
141
+ const b = bytesOf(v, DAMM_V2_PROGRAM, DAMM_MIN_LEN, "pool");
142
+ return {
143
+ tokenA: key(b, 168),
144
+ tokenB: key(b, 200),
145
+ sqrtMinPrice: u128(b, 424),
146
+ sqrtPrice: u128(b, 456),
147
+ creator: key(b, 648),
148
+ };
149
+ }
150
+ /** Quote per whole coin from a DAMM v2 pool, whichever side the coin is on. */
151
+ export function dammPrice(p, mint, decimals, quoteDecimals = 9) {
152
+ if (p.sqrtPrice === 0n)
153
+ throw new DecodeError("pool_reserves");
154
+ if (p.tokenA === mint)
155
+ return priceFromSqrt(p.sqrtPrice, decimals, quoteDecimals);
156
+ if (p.tokenB === mint) {
157
+ const ab = priceFromSqrt(p.sqrtPrice, quoteDecimals, decimals); // quote per coin inverted
158
+ return 1 / ab;
159
+ }
160
+ throw new DecodeError("pool_mismatch");
161
+ }
162
+ /** How far a DAMM v2 pool sits above its floor (sqrt_min_price): price/floor - 1. At ~0 nothing can be sold. */
163
+ export function dammRoomAboveFloor(p) {
164
+ if (p.sqrtMinPrice === 0n)
165
+ return null;
166
+ const r = Number(p.sqrtPrice) / Number(p.sqrtMinPrice);
167
+ return r * r - 1;
168
+ }
@@ -0,0 +1,37 @@
1
+ import { type Rpc } from "../solana/rpc.ts";
2
+ import { type CandleCurve } from "./curve.ts";
3
+ import type { MarketView } from "../strategies/types.ts";
4
+ import type { DryPricer } from "../exec/executor.ts";
5
+ export interface MarketRead extends MarketView {
6
+ mint: string;
7
+ curve: CandleCurve | null;
8
+ roomAboveFloor: number | null;
9
+ problem?: string;
10
+ }
11
+ export interface CoinRef {
12
+ mint: string;
13
+ decimals: number;
14
+ }
15
+ export declare function readMarkets(rpc: Rpc, coins: CoinRef[], nowMs: number): Promise<Map<string, MarketRead>>;
16
+ export declare function impactBps(curve: CandleCurve, lamports: bigint): {
17
+ bps: number;
18
+ expectedOutRaw: bigint;
19
+ } | {
20
+ error: string;
21
+ };
22
+ export interface QuoteSource {
23
+ getQuote(chain: "solana", mint: string, q: {
24
+ side: "buy" | "sell";
25
+ amountIn: string;
26
+ slippageBps?: number;
27
+ }): Promise<{
28
+ quote: {
29
+ amountOut: string;
30
+ };
31
+ }>;
32
+ }
33
+ /**
34
+ * Dry-run fills: Candle's public curve quote (exact integers) while the coin is on the curve; the on-chain
35
+ * curve math as a fallback; for a migrated coin, the pool price less 2 % (labelled dry in the ledger).
36
+ */
37
+ export declare function dryPricer(rpc: Rpc, quotes: QuoteSource | null, decimalsOf: (mint: string) => number): DryPricer;
@@ -0,0 +1,106 @@
1
+ /** Market reads for a set of coins in one RPC round trip: the Candle curve, and the DAMM v2 pool once migrated. */
2
+ import { candleCurve, dammPool } from "../solana/pda.js";
3
+ import { getAccounts } from "../solana/rpc.js";
4
+ import { buyImpact, curveProgress, dammPrice, dammRoomAboveFloor, decodeCandleCurve, decodeDamm, priceFromSqrt } from "./curve.js";
5
+ const pdaCache = new Map();
6
+ function pdas(mint) {
7
+ let p = pdaCache.get(mint);
8
+ if (!p) {
9
+ p = { curve: candleCurve(mint), pool: dammPool(mint) };
10
+ pdaCache.set(mint, p);
11
+ }
12
+ return p;
13
+ }
14
+ export async function readMarkets(rpc, coins, nowMs) {
15
+ const out = new Map();
16
+ if (!coins.length)
17
+ return out;
18
+ const keys = [];
19
+ for (const c of coins)
20
+ keys.push(pdas(c.mint).curve, pdas(c.mint).pool);
21
+ const vals = await getAccounts(rpc, keys);
22
+ coins.forEach((c, i) => {
23
+ const cv = vals[2 * i];
24
+ const pv = vals[2 * i + 1];
25
+ const base = { mint: c.mint, priceSol: null, progress: null, migrated: false, venue: "unknown", nowMs, curve: null, roomAboveFloor: null };
26
+ try {
27
+ const curve = decodeCandleCurve(cv);
28
+ if (curve.baseMint !== c.mint)
29
+ throw new Error("curve_mismatch");
30
+ base.curve = curve;
31
+ base.progress = curveProgress(curve);
32
+ base.migrated = curve.migrated;
33
+ if (!curve.migrated && base.progress >= 1) {
34
+ // Full but not flagged migrated yet: the graduating swap is done and the pool is not there. Hold.
35
+ base.problem = "migrating";
36
+ }
37
+ else if (!curve.migrated) {
38
+ base.venue = "curve";
39
+ base.priceSol = curve.sqrtPrice ? priceFromSqrt(curve.sqrtPrice, c.decimals) : null;
40
+ }
41
+ else if (pv) {
42
+ const pool = decodeDamm(pv);
43
+ if (pool.creator !== curve.authority)
44
+ throw new Error("pool_mismatch");
45
+ base.venue = "damm";
46
+ base.priceSol = dammPrice(pool, c.mint, c.decimals);
47
+ base.roomAboveFloor = dammRoomAboveFloor(pool);
48
+ }
49
+ else {
50
+ base.problem = "migrating";
51
+ }
52
+ }
53
+ catch (e) {
54
+ base.problem = e.message;
55
+ }
56
+ out.set(c.mint, base);
57
+ });
58
+ return out;
59
+ }
60
+ export function impactBps(curve, lamports) {
61
+ try {
62
+ const r = buyImpact(curve, lamports);
63
+ return { bps: r.impactBps, expectedOutRaw: r.expectedOutRaw };
64
+ }
65
+ catch (e) {
66
+ return { error: e.message };
67
+ }
68
+ }
69
+ /**
70
+ * Dry-run fills: Candle's public curve quote (exact integers) while the coin is on the curve; the on-chain
71
+ * curve math as a fallback; for a migrated coin, the pool price less 2 % (labelled dry in the ledger).
72
+ */
73
+ export function dryPricer(rpc, quotes, decimalsOf) {
74
+ return {
75
+ async buyOut(mint, lamports) {
76
+ if (quotes) {
77
+ try {
78
+ const q = await quotes.getQuote("solana", mint, { side: "buy", amountIn: lamports.toString() });
79
+ return BigInt(q.quote.amountOut);
80
+ }
81
+ catch {
82
+ /* fall back to the curve */
83
+ }
84
+ }
85
+ const m = (await readMarkets(rpc, [{ mint, decimals: decimalsOf(mint) }], Date.now())).get(mint);
86
+ if (!m.curve)
87
+ throw Object.assign(new Error("no curve"), { code: "NO_MARKET" });
88
+ return buyImpact(m.curve, lamports).expectedOutRaw;
89
+ },
90
+ async sellOut(mint, raw, decimals) {
91
+ if (quotes) {
92
+ try {
93
+ const q = await quotes.getQuote("solana", mint, { side: "sell", amountIn: raw.toString() });
94
+ return BigInt(q.quote.amountOut);
95
+ }
96
+ catch {
97
+ /* graduated or unavailable: mark to market */
98
+ }
99
+ }
100
+ const m = (await readMarkets(rpc, [{ mint, decimals }], Date.now())).get(mint);
101
+ if (m.priceSol === null)
102
+ throw Object.assign(new Error("no price"), { code: "NO_MARKET" });
103
+ return BigInt(Math.floor((Number(raw) / 10 ** decimals) * m.priceSol * 1e9 * 0.98));
104
+ },
105
+ };
106
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Secret redaction for every outbound path (logs, ledger error rows, status.json, stdout).
3
+ *
4
+ * Two passes, value first:
5
+ * 1. By value: the literal value of every environment variable whose NAME looks like a secret, plus any
6
+ * value registered explicitly (the API key, an RPC URL with a key in it). Values shorter than 8 chars are
7
+ * skipped so ordinary words are never scrubbed. For a URL-valued variable only its query string and
8
+ * userinfo are treated as secret, so the bare host still reads.
9
+ * 2. By pattern: bearer tokens, keyed query strings, webhook URLs, vendor-prefixed keys, PEM blocks.
10
+ * Callers truncate AFTER redacting, never before (a cut can leave a key's head behind as plain text).
11
+ */
12
+ /** Register a value that must never appear in output (e.g. the resolved API key or RPC URL). */
13
+ export declare function addSecret(value: string | undefined | null): void;
14
+ export declare function redact(text: string, env?: NodeJS.ProcessEnv): string;
15
+ /** Redact, then truncate: the only safe order. */
16
+ export declare function redactTruncate(text: string, max: number, env?: NodeJS.ProcessEnv): string;
17
+ /** Deep-redact any JSON-able value (strings inside objects and arrays). */
18
+ export declare function redactDeep<T>(value: T, env?: NodeJS.ProcessEnv): T;
19
+ /** Stringify an error with code/data, redacted. Never just the (truncated, maybe credential-bearing) message. */
20
+ export declare function errorJson(err: unknown, env?: NodeJS.ProcessEnv): string;
package/dist/redact.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Secret redaction for every outbound path (logs, ledger error rows, status.json, stdout).
3
+ *
4
+ * Two passes, value first:
5
+ * 1. By value: the literal value of every environment variable whose NAME looks like a secret, plus any
6
+ * value registered explicitly (the API key, an RPC URL with a key in it). Values shorter than 8 chars are
7
+ * skipped so ordinary words are never scrubbed. For a URL-valued variable only its query string and
8
+ * userinfo are treated as secret, so the bare host still reads.
9
+ * 2. By pattern: bearer tokens, keyed query strings, webhook URLs, vendor-prefixed keys, PEM blocks.
10
+ * Callers truncate AFTER redacting, never before (a cut can leave a key's head behind as plain text).
11
+ */
12
+ const SECRET_NAME = /KEY|TOKEN|SECRET|PASSPHRASE|PASSWORD|WEBHOOK|CREDENTIAL|AUTH|PRIVATE|PEM|RPC/i;
13
+ const MIN_LEN = 8;
14
+ const extra = new Set();
15
+ /** Register a value that must never appear in output (e.g. the resolved API key or RPC URL). */
16
+ export function addSecret(value) {
17
+ if (!value || value.length < MIN_LEN)
18
+ return;
19
+ for (const v of secretParts(value))
20
+ extra.add(v);
21
+ }
22
+ function secretParts(value) {
23
+ if (/^(https?|wss?):\/\//i.test(value)) {
24
+ const out = [];
25
+ try {
26
+ const u = new URL(value);
27
+ if (u.search.length > 1)
28
+ out.push(u.search.slice(1));
29
+ for (const [, v] of u.searchParams)
30
+ if (v.length >= MIN_LEN)
31
+ out.push(v);
32
+ if (u.password)
33
+ out.push(u.password);
34
+ if (u.username && u.username.length >= MIN_LEN)
35
+ out.push(u.username);
36
+ // Path segments that look like keys (Helius/QuickNode style /<key>/)
37
+ for (const seg of u.pathname.split("/"))
38
+ if (seg.length >= 24 && /^[A-Za-z0-9_-]+$/.test(seg))
39
+ out.push(seg);
40
+ }
41
+ catch {
42
+ /* not a URL after all */
43
+ }
44
+ return out;
45
+ }
46
+ return [value];
47
+ }
48
+ function envSecrets(env) {
49
+ const out = [];
50
+ for (const [name, value] of Object.entries(env)) {
51
+ if (!value || value.length < MIN_LEN || !SECRET_NAME.test(name))
52
+ continue;
53
+ out.push(...secretParts(value));
54
+ }
55
+ return out;
56
+ }
57
+ const PATTERNS = [
58
+ [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----|$)/g, "[REDACTED_PEM]"],
59
+ [/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 [REDACTED]"],
60
+ [/\bcndl_(live|test)_[A-Za-z0-9_-]{6,}/g, "cndl_$1_[REDACTED]"],
61
+ [/([?&](api[-_]?key|key|token|access[-_]?token|secret|auth|signature|sig)=)[^&\s"'#]+/gi, "$1[REDACTED]"],
62
+ [/https:\/\/(discord(app)?\.com\/api\/webhooks|hooks\.slack\.com\/services)\/[^\s"']+/gi, "https://$1/[REDACTED]"],
63
+ [/\b(sk|pk|rk)_(live|test)_[A-Za-z0-9]{8,}/g, "$1_$2_[REDACTED]"],
64
+ [/\bx-api-key["']?\s*[:=]\s*["']?[A-Za-z0-9._-]{8,}/gi, "x-api-key: [REDACTED]"],
65
+ ];
66
+ export function redact(text, env = process.env) {
67
+ let s = text;
68
+ const values = [...envSecrets(env), ...extra].sort((a, b) => b.length - a.length);
69
+ for (const v of values)
70
+ if (v && s.includes(v))
71
+ s = s.split(v).join("[REDACTED]");
72
+ for (const [re, rep] of PATTERNS)
73
+ s = s.replace(re, rep);
74
+ return s;
75
+ }
76
+ /** Redact, then truncate: the only safe order. */
77
+ export function redactTruncate(text, max, env = process.env) {
78
+ const s = redact(text, env);
79
+ return s.length > max ? s.slice(0, max) + "…" : s;
80
+ }
81
+ /** Deep-redact any JSON-able value (strings inside objects and arrays). */
82
+ export function redactDeep(value, env = process.env) {
83
+ if (typeof value === "string")
84
+ return redact(value, env);
85
+ if (Array.isArray(value))
86
+ return value.map((v) => redactDeep(v, env));
87
+ if (value && typeof value === "object") {
88
+ const out = {};
89
+ for (const [k, v] of Object.entries(value))
90
+ out[k] = redactDeep(v, env);
91
+ return out;
92
+ }
93
+ return value;
94
+ }
95
+ /** Stringify an error with code/data, redacted. Never just the (truncated, maybe credential-bearing) message. */
96
+ export function errorJson(err, env = process.env) {
97
+ return redact(JSON.stringify(err, (_k, v) => {
98
+ if (typeof v === "bigint")
99
+ return v.toString();
100
+ if (v instanceof Error) {
101
+ const o = { name: v.name, message: v.message };
102
+ for (const k of Object.getOwnPropertyNames(v))
103
+ if (k !== "stack")
104
+ o[k] = v[k];
105
+ if (v.cause)
106
+ o.cause = v.cause;
107
+ return o;
108
+ }
109
+ return v;
110
+ }), env);
111
+ }
@@ -0,0 +1,4 @@
1
+ export declare function b58encode(bytes: Uint8Array): string;
2
+ export declare function b58decode(s: string): Uint8Array;
3
+ /** A 32-byte Solana address in base58, or null. */
4
+ export declare function asAddress(s: unknown): string | null;
@@ -0,0 +1,45 @@
1
+ const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
2
+ const INDEX = new Map([...ALPHABET].map((c, i) => [c, i]));
3
+ export function b58encode(bytes) {
4
+ let n = 0n;
5
+ for (const b of bytes)
6
+ n = (n << 8n) | BigInt(b);
7
+ let s = "";
8
+ while (n > 0n) {
9
+ s = ALPHABET[Number(n % 58n)] + s;
10
+ n /= 58n;
11
+ }
12
+ let lead = 0;
13
+ while (lead < bytes.length && bytes[lead] === 0)
14
+ lead++;
15
+ return "1".repeat(lead) + s;
16
+ }
17
+ export function b58decode(s) {
18
+ let n = 0n;
19
+ for (const c of s) {
20
+ const i = INDEX.get(c);
21
+ if (i === undefined)
22
+ throw new Error(`not base58: ${JSON.stringify(c)}`);
23
+ n = n * 58n + BigInt(i);
24
+ }
25
+ const body = [];
26
+ while (n > 0n) {
27
+ body.unshift(Number(n & 0xffn));
28
+ n >>= 8n;
29
+ }
30
+ let lead = 0;
31
+ while (lead < s.length && s[lead] === "1")
32
+ lead++;
33
+ return Uint8Array.from([...new Array(lead).fill(0), ...body]);
34
+ }
35
+ /** A 32-byte Solana address in base58, or null. */
36
+ export function asAddress(s) {
37
+ if (typeof s !== "string" || s.length < 32 || s.length > 44)
38
+ return null;
39
+ try {
40
+ return b58decode(s).length === 32 ? s : null;
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * logsSubscribe over a websocket (Node's global WebSocket), mentioning one program. Reconnects with backoff;
3
+ * reports up/down so the caller can lean on signature polling while it is down.
4
+ */
5
+ export interface LogsEvent {
6
+ signature: string;
7
+ err: unknown;
8
+ logs: string[];
9
+ slot: number;
10
+ }
11
+ export interface LogsSocket {
12
+ close(): void;
13
+ isUp(): boolean;
14
+ }
15
+ export declare function wsUrlFor(httpUrl: string): string;
16
+ export declare function subscribeLogs(url: string, program: string, handlers: {
17
+ onLogs: (e: LogsEvent) => void;
18
+ onState?: (up: boolean, why?: string) => void;
19
+ }, opts?: {
20
+ WebSocketImpl?: typeof WebSocket;
21
+ maxBackoffMs?: number;
22
+ pingMs?: number;
23
+ stallMs?: number;
24
+ now?: () => number;
25
+ }): LogsSocket;