@degenly/agent 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.
package/dist/client.js ADDED
@@ -0,0 +1,213 @@
1
+ /**
2
+ * DGAJ15: the `/v1/*` client of the live mode + the API key file.
3
+ *
4
+ * - Base `https://degenly.app`. `DEGENLY_API_BASE` may change it ONLY to another `https://` origin (no user
5
+ * info, no path, no query); any other scheme / shape → BAD_API_BASE before any request.
6
+ * - Every request is signed by the agent wallet (./sign.ts, server rule degenly/src/edge/botApi.ts:286-312):
7
+ * x-degenly-key = the plain API key, x-degenly-ts, x-degenly-sig. The signed path is exactly what the server
8
+ * reads (`url.pathname + url.search`); a path that would be rewritten by URL parsing is refused (BAD_PATH).
9
+ * - `redirect: "error"`: a redirect never carries the key or a signature to another place.
10
+ * - Server refusals come back as is: the server's stable `error` code (SPEND_LIMIT, SPEND_LIMIT_NOT_SET,
11
+ * TOKEN_BLOCKED, API_BUDGET_EXHAUSTED, API_SEATS_FULL, KEY_INVALID, …) + its scalar fields (scope,
12
+ * limitLamports, …) + Retry-After. 404 = the Bot API is off: "Live trading is not available yet."
13
+ * - API key file `~/.degenly/credentials.json` (POSIX 0600, dir 0700). The key is never printed; only its first
14
+ * 12 chars (the server's own display prefix, apiConstants.ts:26, not enough to use the key).
15
+ * No telemetry: the only requests are the ones a command asks for.
16
+ */
17
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { degenlyDir } from "./keys.js";
20
+ import { cleanText } from "./sanitize.js";
21
+ import { API_KEY_HEADER, API_SIG_HEADER, API_TS_HEADER, signApiRequest } from "./sign.js";
22
+ export const DEFAULT_API_BASE = "https://degenly.app";
23
+ export const LIVE_REQUEST_TIMEOUT_MS = 20_000;
24
+ export const CREDENTIALS_FILE_NAME = "credentials.json";
25
+ export const CREDENTIALS_PATH_TEXT = "~/.degenly/credentials.json";
26
+ /** The server answers every `/v1/*` path 404 while the Bot API is off (botApi.ts:627). Do not promise more. */
27
+ export const LIVE_NOT_AVAILABLE = "Live trading is not available yet.";
28
+ /** Must equal `API_KEY_PREFIX` / `API_KEY_DISPLAY_CHARS` in degenly/src/config/apiConstants.ts:23, :26. */
29
+ export const API_KEY_PREFIX = "dgk_";
30
+ export const API_KEY_DISPLAY_CHARS = 12;
31
+ /** A pasted key file / stdin larger than this is not a key. */
32
+ export const KEY_INPUT_MAX_BYTES = 4096;
33
+ const POSIX = process.platform !== "win32";
34
+ const CODE_RE = /^[A-Z][A-Z0-9_]{0,39}$/;
35
+ const FIELD_RE = /^[A-Za-z][A-Za-z0-9_]{0,39}$/;
36
+ const RESERVED = new Set(["ok", "mode", "note", "error", "hint", "status", "retryAfterMs"]);
37
+ // ---- API base ----------------------------------------------------------------------------------
38
+ export function resolveApiBase(env) {
39
+ const v = env.DEGENLY_API_BASE;
40
+ if (v === undefined || v === "")
41
+ return { ok: true, base: DEFAULT_API_BASE };
42
+ let u;
43
+ try {
44
+ u = new URL(v);
45
+ }
46
+ catch {
47
+ return { ok: false, error: "BAD_API_BASE" };
48
+ }
49
+ if (u.protocol !== "https:" || u.username !== "" || u.password !== "" || u.search !== "" || u.hash !== "" || (u.pathname !== "/" && u.pathname !== "")) {
50
+ return { ok: false, error: "BAD_API_BASE" };
51
+ }
52
+ return { ok: true, base: u.origin };
53
+ }
54
+ // ---- API key file ------------------------------------------------------------------------------
55
+ /** Same shape check as the server (degenly/src/api/keyStore.ts:122-124). */
56
+ export function plausibleApiKey(text) {
57
+ return text.startsWith(API_KEY_PREFIX) && text.length >= API_KEY_PREFIX.length + 40 && text.length <= API_KEY_PREFIX.length + 50 && /^[1-9A-HJ-NP-Za-km-z]+$/.test(text.slice(API_KEY_PREFIX.length));
58
+ }
59
+ export function credentialsPath(home) {
60
+ return join(degenlyDir(home), CREDENTIALS_FILE_NAME);
61
+ }
62
+ /** `login`: stores the key (replaces an older one: the wallet file is what must never be overwritten). */
63
+ export function saveCredentials(home, apiKey) {
64
+ try {
65
+ mkdirSync(degenlyDir(home), { recursive: true, mode: 0o700 });
66
+ if (POSIX)
67
+ chmodSync(degenlyDir(home), 0o700);
68
+ writeFileSync(credentialsPath(home), JSON.stringify({ v: 1, apiKey }), { mode: 0o600 });
69
+ if (POSIX)
70
+ chmodSync(credentialsPath(home), 0o600);
71
+ return true;
72
+ }
73
+ catch {
74
+ return false;
75
+ }
76
+ }
77
+ export function loadCredentials(home) {
78
+ const file = credentialsPath(home);
79
+ if (!existsSync(file))
80
+ return { ok: false, error: "NOT_LOGGED_IN" };
81
+ try {
82
+ const v = JSON.parse(readFileSync(file, "utf8"));
83
+ if (typeof v === "object" && v !== null && !Array.isArray(v)) {
84
+ const k = v.apiKey;
85
+ if (typeof k === "string" && plausibleApiKey(k))
86
+ return { ok: true, apiKey: k };
87
+ }
88
+ }
89
+ catch {
90
+ // fall through
91
+ }
92
+ return { ok: false, error: "CREDENTIALS_CORRUPT" };
93
+ }
94
+ function isObj(v) {
95
+ return typeof v === "object" && v !== null && !Array.isArray(v);
96
+ }
97
+ function retryAfterMs(r) {
98
+ const h = r.headers.get("retry-after");
99
+ if (h === null)
100
+ return undefined;
101
+ const s = Number(h);
102
+ return Number.isFinite(s) && s >= 0 ? Math.round(s * 1000) : undefined;
103
+ }
104
+ /** The server's scalar fields (scope, limitLamports, reason, …), cleaned; nested values are dropped. */
105
+ function scalarFields(body) {
106
+ const out = {};
107
+ for (const [k, v] of Object.entries(body)) {
108
+ if (RESERVED.has(k) || !FIELD_RE.test(k))
109
+ continue;
110
+ if (typeof v === "string")
111
+ out[k] = cleanText(v, 200);
112
+ else if ((typeof v === "number" && Number.isFinite(v)) || typeof v === "boolean")
113
+ out[k] = v;
114
+ }
115
+ return out;
116
+ }
117
+ const fail = (error, status, fields = {}, after) => ({
118
+ ok: false,
119
+ error,
120
+ status,
121
+ fields,
122
+ ...(after !== undefined ? { retryAfterMs: after } : {}),
123
+ });
124
+ export function createLiveClient(deps) {
125
+ return {
126
+ async request(method, pathWithQuery, body) {
127
+ if (!pathWithQuery.startsWith("/v1/"))
128
+ return fail("BAD_PATH", 0);
129
+ let url;
130
+ try {
131
+ url = new URL(pathWithQuery, deps.base);
132
+ }
133
+ catch {
134
+ return fail("BAD_PATH", 0);
135
+ }
136
+ // what is signed must be what the server reads: same origin, no rewrite by the URL parser
137
+ if (url.origin !== deps.base || url.pathname + url.search !== pathWithQuery || url.hash !== "")
138
+ return fail("BAD_PATH", 0);
139
+ const bytes = new TextEncoder().encode(body ?? "");
140
+ const s = signApiRequest(deps.signer, method, pathWithQuery, bytes, deps.now());
141
+ const headers = { [API_KEY_HEADER]: deps.apiKey, [API_TS_HEADER]: s.ts, [API_SIG_HEADER]: s.sig, accept: "application/json" };
142
+ if (body !== undefined)
143
+ headers["content-type"] = "application/json";
144
+ let res;
145
+ try {
146
+ res = await deps.fetch(url.href, {
147
+ method,
148
+ headers,
149
+ redirect: "error",
150
+ signal: AbortSignal.timeout(LIVE_REQUEST_TIMEOUT_MS),
151
+ ...(body !== undefined ? { body } : {}),
152
+ });
153
+ }
154
+ catch {
155
+ return fail("NETWORK", 0);
156
+ }
157
+ let parsed;
158
+ try {
159
+ parsed = await res.json();
160
+ }
161
+ catch {
162
+ parsed = undefined;
163
+ }
164
+ const after = retryAfterMs(res);
165
+ if (res.status === 404)
166
+ return fail("NOT_FOUND", 404, {}, after);
167
+ if (res.ok && isObj(parsed) && parsed.ok === true)
168
+ return { ok: true, status: res.status, data: parsed };
169
+ if (!isObj(parsed))
170
+ return fail(res.ok ? "BAD_RESPONSE" : `HTTP_${res.status}`, res.status, {}, after);
171
+ const code = typeof parsed.error === "string" && CODE_RE.test(parsed.error) ? parsed.error : res.ok ? "BAD_RESPONSE" : `HTTP_${res.status}`;
172
+ return fail(code, res.status, scalarFields(parsed), after);
173
+ },
174
+ };
175
+ }
176
+ // ---- hints (package text, English) ----------------------------------------------------------------
177
+ export const LIVE_HINTS = {
178
+ NOT_FOUND: LIVE_NOT_AVAILABLE,
179
+ BAD_API_BASE: "DEGENLY_API_BASE must be an https:// origin (no path, no query). Unset it to use https://degenly.app.",
180
+ BAD_DEGENLY_HOME: "DEGENLY_HOME must be an absolute path outside the current working directory. Unset it to use your home directory.",
181
+ BAD_PATH: "Only /v1/ paths of the Degenly Bot API are sent.",
182
+ BAD_OWNER: "Pass your main wallet address: setup --owner <Solana address>. It is the wallet you sign in with on degenly.app.",
183
+ WALLET_EXISTS: "An agent wallet already exists and is never overwritten. For a new pairing code run: degenly pair --owner <main wallet address>",
184
+ WALLET_CORRUPT: "~/.degenly/agent-wallet.json is not a valid wallet file. It was left as is. Restore it from your backup; do not delete it if it holds funds.",
185
+ WALLET_WRITE_FAILED: "Could not write ~/.degenly/agent-wallet.json. Check disk space and permissions.",
186
+ NO_WALLET: "No agent wallet on this computer. Run: degenly setup --owner <main wallet address>",
187
+ NOT_LOGGED_IN: "No API key stored. After pairing on degenly.app/bot, run: degenly login (paste the key on stdin) or degenly login --key-file <path>",
188
+ CREDENTIALS_CORRUPT: "~/.degenly/credentials.json is not readable. Run degenly login again.",
189
+ CREDENTIALS_WRITE_FAILED: "Could not write ~/.degenly/credentials.json. Check disk space and permissions.",
190
+ KEY_ARG_REFUSED: "The API key is never taken as a command argument (it would stay in shell history). Pipe it on stdin: degenly login < key.txt, or use: degenly login --key-file <path>",
191
+ NO_KEY_INPUT: "No API key on stdin. Pipe it in (degenly login < key.txt) or use: degenly login --key-file <path>",
192
+ KEY_FILE_UNREADABLE: "Could not read the --key-file path.",
193
+ KEY_FORMAT: "That is not a Degenly API key (it starts with dgk_). Copy the key shown once on degenly.app/bot after pairing.",
194
+ KEY_WALLET_MISMATCH: "This API key belongs to another wallet than the agent wallet on this computer. Pair this agent wallet on degenly.app/bot and log in with its key.",
195
+ NETWORK: "Could not reach Degenly. Check the connection and retry.",
196
+ BAD_RESPONSE: "Degenly answered something unexpected. Retry later.",
197
+ SPEND_LIMIT: "Refused by the spending limit set on degenly.app/bot (per trade or per day). Only the wallet owner can change it there.",
198
+ SPEND_LIMIT_NOT_SET: "This agent wallet has no spending limit row. Pair it again on degenly.app/bot.",
199
+ TOKEN_BLOCKED: "Degenly does not allow buying this token through the API (see reason). Selling is never blocked.",
200
+ API_BUDGET_EXHAUSTED: "The monthly API budget of all agents is used up. Retry after retryAfterMs.",
201
+ API_SEATS_FULL: "All agent seats are taken. Retry later.",
202
+ KEY_REQUIRED: "Degenly did not receive an API key. Run: degenly login",
203
+ KEY_INVALID: "Degenly does not know this API key, or it was revoked. Pair again on degenly.app/bot and run degenly login.",
204
+ SIGNATURE_REQUIRED: "Degenly did not receive a signature.",
205
+ SIGNATURE_INVALID: "Degenly could not verify the request signature with this agent wallet.",
206
+ TS_SKEW: "This computer's clock is more than 30 s off. Fix the system time and retry.",
207
+ REPLAY: "This exact signed request was already used. Retry (a new signature is made each time).",
208
+ API_TERMS_REQUIRED: "The API Terms changed. Pair again on degenly.app/bot to accept the current version.",
209
+ RATE_LIMITED: "Wait retryAfterMs, then retry.",
210
+ };
211
+ export function liveHint(code) {
212
+ return LIVE_HINTS[code] ?? `Degenly answered ${code}. Retry later.`;
213
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * DGAJD1: one demo fill — the SAME pure bigint function as the site's `demoFill`
3
+ * (degenly/src/demo/fill.ts, DGDEMO1 spec §4.2), over the local record and a live price-only quote
4
+ * (`/api/swap/quote` without a taker). Nothing here talks to the network or a wallet.
5
+ *
6
+ * - The Degenly fee is already inside `outAmount` → it is NOT taken again; `feeUsd` / `feeBps` are kept for display.
7
+ * - Network = `networkAndPriorityLamports − rentLamports` (rent comes back on a full sell), at least 0.
8
+ * - No slippage model: the fill is the quote's `outAmount`; `minOutAmount` is not used.
9
+ * - Amounts are decimal strings; math is bigint. No float touches a balance.
10
+ */
11
+ import { DEMO_TRADES_MAX } from "./store.js";
12
+ /** Same value as the site (`QUOTE_MAX_AGE_MS`, degenly/src/config/constants.ts). */
13
+ export const QUOTE_MAX_AGE_MS = 15_000;
14
+ export const SOL_MINT = "So11111111111111111111111111111111111111112";
15
+ export const SOL_DECIMALS = 9;
16
+ const UINT = /^\d+$/;
17
+ function big(v) {
18
+ return UINT.test(v) ? BigInt(v) : undefined;
19
+ }
20
+ function lamportsOf(v) {
21
+ return v !== undefined && Number.isFinite(v) && v > 0 ? BigInt(Math.floor(v)) : 0n;
22
+ }
23
+ function max0(v) {
24
+ return v < 0n ? 0n : v;
25
+ }
26
+ /** Charged network part of a quote (signature + priority, rent excluded), lamports ≥ 0. */
27
+ export function demoNetworkLamports(q) {
28
+ return max0(lamportsOf(q.cost.networkAndPriorityLamports) - lamportsOf(q.cost.rentLamports));
29
+ }
30
+ export function demoFill(s, q, meta, now) {
31
+ if (now - q.receivedAt > QUOTE_MAX_AGE_MS)
32
+ return { ok: false, error: "STALE_QUOTE" };
33
+ const side = q.side;
34
+ if (side !== "buy" && side !== "sell")
35
+ return { ok: false, error: "BAD_QUOTE" };
36
+ if (side === "buy" ? q.inputMint !== SOL_MINT : q.outputMint !== SOL_MINT)
37
+ return { ok: false, error: "BAD_QUOTE" };
38
+ const inAmount = big(q.inAmount);
39
+ const outAmount = big(q.outAmount);
40
+ const balance = big(s.balanceLamports);
41
+ if (inAmount === undefined || outAmount === undefined || balance === undefined)
42
+ return { ok: false, error: "BAD_QUOTE" };
43
+ if (inAmount <= 0n || outAmount <= 0n)
44
+ return { ok: false, error: "BAD_QUOTE" };
45
+ const mint = side === "buy" ? q.outputMint : q.inputMint;
46
+ const net = demoNetworkLamports(q);
47
+ const realized = BigInt(s.realizedLamports);
48
+ const positions = { ...s.positions };
49
+ const prev = positions[mint];
50
+ let nextBalance;
51
+ let nextRealized = realized;
52
+ let tradeRealized;
53
+ if (side === "buy") {
54
+ const spend = inAmount + net;
55
+ if (spend > balance)
56
+ return { ok: false, error: "LOW_SOL" };
57
+ nextBalance = balance - spend;
58
+ const raw = (prev ? BigInt(prev.raw) : 0n) + outAmount;
59
+ const cost = (prev ? BigInt(prev.costLamports) : 0n) + spend;
60
+ const iconUrl = prev?.iconUrl ?? meta.iconUrl;
61
+ positions[mint] = {
62
+ mint,
63
+ symbol: prev?.symbol ?? meta.symbol,
64
+ decimals: prev?.decimals ?? meta.decimals,
65
+ ...(iconUrl !== undefined ? { iconUrl } : {}),
66
+ raw: raw.toString(),
67
+ costLamports: cost.toString(),
68
+ openedAt: prev?.openedAt ?? now,
69
+ };
70
+ }
71
+ else {
72
+ const held = prev ? BigInt(prev.raw) : 0n;
73
+ if (!prev || held <= 0n || inAmount > held)
74
+ return { ok: false, error: "NO_HOLD" };
75
+ const cost = BigInt(prev.costLamports);
76
+ const proceeds = max0(outAmount - net);
77
+ const released = (cost * inAmount) / held; // bigint floor division
78
+ const pnl = proceeds - released;
79
+ nextBalance = balance + proceeds;
80
+ nextRealized = realized + pnl;
81
+ tradeRealized = pnl.toString();
82
+ const rest = held - inAmount;
83
+ if (rest === 0n)
84
+ delete positions[mint];
85
+ else
86
+ positions[mint] = { ...prev, raw: rest.toString(), costLamports: (cost - released).toString() };
87
+ }
88
+ const n = s.trades.filter((x) => x.at === now).length;
89
+ const trade = {
90
+ id: `${now}-${n}`,
91
+ at: now,
92
+ mint,
93
+ symbol: prev?.symbol ?? meta.symbol,
94
+ side,
95
+ inAmount: inAmount.toString(),
96
+ outAmount: outAmount.toString(),
97
+ outDecimals: q.outDecimals,
98
+ networkLamports: net.toString(),
99
+ feeUsd: q.cost.degenlyFeeUsd,
100
+ feeBps: q.cost.degenlyFeeBps,
101
+ ...(tradeRealized !== undefined ? { realizedLamports: tradeRealized } : {}),
102
+ };
103
+ const state = {
104
+ ...s,
105
+ touchedAt: now,
106
+ balanceLamports: nextBalance.toString(),
107
+ realizedLamports: nextRealized.toString(),
108
+ positions,
109
+ trades: [trade, ...s.trades].slice(0, DEMO_TRADES_MAX),
110
+ funnel: s.funnel.firstTradeAt === undefined ? { ...s.funnel, firstTradeAt: now } : s.funnel,
111
+ };
112
+ return { ok: true, state, trade };
113
+ }
114
+ // ---- exact decimal <-> raw units (no float) -------------------------------------------------
115
+ const DECIMAL = /^(\d+)(?:\.(\d+))?$/;
116
+ /** Decimal string with up to `decimals` fraction digits → raw units (> 0), else undefined. */
117
+ export function parseUnits(v, decimals) {
118
+ const m = DECIMAL.exec(v.trim());
119
+ if (!m)
120
+ return undefined;
121
+ const whole = m[1] ?? "0";
122
+ const frac = m[2] ?? "";
123
+ if (frac.length > decimals)
124
+ return undefined;
125
+ const raw = BigInt(whole + frac.padEnd(decimals, "0"));
126
+ return raw > 0n ? raw : undefined;
127
+ }
128
+ /** SOL as a decimal string ("0.1") → lamports, else undefined. */
129
+ export function parseSol(v) {
130
+ return parseUnits(v, SOL_DECIMALS);
131
+ }
132
+ /** Raw units (bigint or signed decimal string) → exact decimal string, trailing zeros trimmed. */
133
+ export function formatUnits(raw, decimals) {
134
+ const v = typeof raw === "bigint" ? raw : BigInt(raw);
135
+ const neg = v < 0n;
136
+ const abs = (neg ? -v : v).toString();
137
+ if (decimals === 0)
138
+ return (neg ? "-" : "") + abs;
139
+ const padded = abs.padStart(decimals + 1, "0");
140
+ const whole = padded.slice(0, padded.length - decimals);
141
+ const frac = padded.slice(padded.length - decimals).replace(/0+$/, "");
142
+ return (neg ? "-" : "") + whole + (frac ? `.${frac}` : "");
143
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * DGAJD1: the demo record. Lives ONLY on this computer, in `~/.degenly/demo.json` (the user's home directory,
3
+ * never the working directory). Nothing of it is sent anywhere: no balance, no position, no trade
4
+ * (same rule as the site's demo, degenly/src/demo/store.ts).
5
+ *
6
+ * Shape = the site's `DemoStateV1` (same field names, same validation), so the two stay comparable.
7
+ * Amounts are decimal strings (lamports / token raw units can exceed 2^53); math is bigint (`./fill`).
8
+ * A corrupt / incompatible file is renamed to `demo.json.corrupt-<ms>` and a fresh 10 SOL record starts (no crash).
9
+ */
10
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ export const DEMO_DIR_NAME = ".degenly";
13
+ export const DEMO_FILE_NAME = "demo.json";
14
+ /** degenly.app demo start balance (site `DEMO_MAIN_START_LAMPORTS`): 10 SOL. */
15
+ export const DEMO_START_LAMPORTS = 10000000000n;
16
+ export const DEMO_TRADES_MAX = 200; // oldest drops
17
+ // ---- validation (same rules as the site's parseDemo; the site-only `pinnedCard` is ignored if present) ----
18
+ const UINT = /^\d+$/;
19
+ const INT = /^-?\d+$/;
20
+ function isObj(v) {
21
+ return typeof v === "object" && v !== null && !Array.isArray(v);
22
+ }
23
+ function isNum(v) {
24
+ return typeof v === "number" && Number.isFinite(v);
25
+ }
26
+ function isUint(v) {
27
+ return typeof v === "string" && UINT.test(v);
28
+ }
29
+ function isInt(v) {
30
+ return typeof v === "string" && INT.test(v);
31
+ }
32
+ function validPosition(key, v) {
33
+ return (isObj(v) &&
34
+ v.mint === key &&
35
+ typeof v.symbol === "string" &&
36
+ isNum(v.decimals) &&
37
+ (v.iconUrl === undefined || typeof v.iconUrl === "string") &&
38
+ isUint(v.raw) &&
39
+ isUint(v.costLamports) &&
40
+ isNum(v.openedAt));
41
+ }
42
+ function validTrade(v) {
43
+ return (isObj(v) &&
44
+ typeof v.id === "string" &&
45
+ isNum(v.at) &&
46
+ typeof v.mint === "string" &&
47
+ typeof v.symbol === "string" &&
48
+ (v.side === "buy" || v.side === "sell") &&
49
+ isUint(v.inAmount) &&
50
+ isUint(v.outAmount) &&
51
+ isNum(v.outDecimals) &&
52
+ isUint(v.networkLamports) &&
53
+ isNum(v.feeUsd) &&
54
+ isNum(v.feeBps) &&
55
+ (v.realizedLamports === undefined || isInt(v.realizedLamports)));
56
+ }
57
+ /** Shape check only: a stored value we can trust, or undefined. */
58
+ export function parseDemo(raw) {
59
+ if (raw === "")
60
+ return undefined;
61
+ let v;
62
+ try {
63
+ v = JSON.parse(raw);
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ if (!isObj(v) || v.v !== 1)
69
+ return undefined;
70
+ if (!isNum(v.startedAt) || !isNum(v.touchedAt) || typeof v.active !== "boolean" || typeof v.startedSignedOut !== "boolean")
71
+ return undefined;
72
+ if (!isUint(v.balanceLamports) || !isInt(v.realizedLamports))
73
+ return undefined;
74
+ if (!isObj(v.positions) || !Object.entries(v.positions).every(([k, p]) => validPosition(k, p)))
75
+ return undefined;
76
+ if (!Array.isArray(v.trades) || !v.trades.every(validTrade))
77
+ return undefined;
78
+ const f = v.funnel;
79
+ if (!isObj(f) || (f.firstTradeAt !== undefined && !isNum(f.firstTradeAt)) || (f.goLiveAt !== undefined && !isNum(f.goLiveAt)))
80
+ return undefined;
81
+ if (v.base !== undefined && !isUint(v.base))
82
+ return undefined;
83
+ return v;
84
+ }
85
+ // ---- record API ---------------------------------------------------------------------------------
86
+ /** A fresh 10 SOL record. `startedSignedOut` is true: the package never has a wallet in demo mode. */
87
+ export function newDemo(now) {
88
+ const start = DEMO_START_LAMPORTS.toString();
89
+ return {
90
+ v: 1,
91
+ startedAt: now,
92
+ touchedAt: now,
93
+ active: true,
94
+ startedSignedOut: true,
95
+ balanceLamports: start,
96
+ realizedLamports: "0",
97
+ positions: {},
98
+ trades: [],
99
+ funnel: {},
100
+ base: start,
101
+ };
102
+ }
103
+ /** Reset: a fresh 10 SOL record; `startedAt`, `startedSignedOut` and `funnel` kept (site `resetDemo` rule). */
104
+ export function resetDemo(prev, now) {
105
+ return { ...newDemo(now), startedSignedOut: prev.startedSignedOut, startedAt: prev.startedAt, funnel: { ...prev.funnel } };
106
+ }
107
+ export function demoDir(home) {
108
+ return join(home, DEMO_DIR_NAME);
109
+ }
110
+ export function demoPath(home) {
111
+ return join(demoDir(home), DEMO_FILE_NAME);
112
+ }
113
+ /** The stored record; none → a fresh 10 SOL one is written; corrupt → backed up + fresh. Never throws on bad content. */
114
+ export function loadDemo(home, now) {
115
+ const file = demoPath(home);
116
+ if (existsSync(file)) {
117
+ const raw = readFileSync(file, "utf8");
118
+ const s = parseDemo(raw);
119
+ if (s)
120
+ return { state: s, created: false };
121
+ const backup = `${file}.corrupt-${now}`;
122
+ renameSync(file, backup);
123
+ const fresh = newDemo(now);
124
+ saveDemo(home, fresh);
125
+ return { state: fresh, created: true, recoveredFrom: backup };
126
+ }
127
+ const fresh = newDemo(now);
128
+ saveDemo(home, fresh);
129
+ return { state: fresh, created: true };
130
+ }
131
+ /** One write of the full record via a temp file + rename (no half-written file). false = the disk refused. */
132
+ export function saveDemo(home, s) {
133
+ try {
134
+ mkdirSync(demoDir(home), { recursive: true, mode: 0o700 });
135
+ const file = demoPath(home);
136
+ const tmp = `${file}.tmp`;
137
+ writeFileSync(tmp, JSON.stringify(s), { mode: 0o600 });
138
+ renameSync(tmp, file);
139
+ return true;
140
+ }
141
+ catch {
142
+ return false;
143
+ }
144
+ }
package/dist/keys.js ADDED
@@ -0,0 +1,138 @@
1
+ /**
2
+ * DGAJ15 (DGAJ-S A3 + A4 "Tavanin siniri"): the agent wallet, created and kept ON THIS COMPUTER.
3
+ *
4
+ * - Ed25519 key pair from Node's built-in `crypto`; Solana address = base58(32-byte public key).
5
+ * - File `~/.degenly/agent-wallet.json` = the Solana CLI keypair format (JSON array of 64 bytes: seed ‖ public key).
6
+ * Home directory, NEVER the working directory. POSIX: file 0600, directory 0700. Windows: under the user
7
+ * profile (no POSIX modes there; the OS profile ACL applies).
8
+ * - An existing file is NEVER overwritten (WALLET_EXISTS: a new key for a funded address = lost funds).
9
+ * A corrupt file is an error (WALLET_CORRUPT): never deleted, never regenerated.
10
+ * - The key is read for one thing in this card: signing (request + pairing). It is never printed, logged,
11
+ * returned, put in an error, or sent: the `Signer` keeps the KeyObject in a closure, its fields are the
12
+ * public address and a `sign` function only.
13
+ * - `--keychain` (OS credential store) is NOT offered: not measured on the three OSes (DGAJ-S A4 madde 3).
14
+ */
15
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
16
+ import { createPrivateKey, createPublicKey, generateKeyPairSync, sign as edSign } from "node:crypto";
17
+ import { isAbsolute, join, relative, resolve } from "node:path";
18
+ import { base58Encode } from "./sign.js";
19
+ export const DEGENLY_DIR_NAME = ".degenly";
20
+ export const WALLET_FILE_NAME = "agent-wallet.json";
21
+ export const WALLET_PATH_TEXT = "~/.degenly/agent-wallet.json";
22
+ /**
23
+ * DGAJ-S A4 madde 1: the SAME sentence in 3 places (`setup` output, `/bot` safety note, README).
24
+ * DGAJ17 README uses this constant. Do not reword.
25
+ */
26
+ export const AGENT_WALLET_WARNING = "Spending limits apply to trades made through Degenly. An agent that can read files on this computer could read the agent wallet key and move funds outside Degenly. Fund the agent wallet with only what you can afford to lose.";
27
+ /** PKCS#8 DER prefix of a raw 32-byte Ed25519 seed (RFC 8410). */
28
+ const PKCS8_ED25519_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
29
+ const POSIX = process.platform !== "win32";
30
+ export function degenlyDir(home) {
31
+ return join(home, DEGENLY_DIR_NAME);
32
+ }
33
+ export function walletPath(home) {
34
+ return join(degenlyDir(home), WALLET_FILE_NAME);
35
+ }
36
+ /**
37
+ * The home the live files live under: the OS home. `DEGENLY_HOME` (tests / isolated runs) is taken only as an
38
+ * ABSOLUTE path that is not the working directory or inside it (the key never lands in an agent's project).
39
+ */
40
+ export function resolveHome(env, osHome, cwd) {
41
+ const v = env.DEGENLY_HOME;
42
+ if (v === undefined || v === "")
43
+ return { ok: true, home: osHome };
44
+ if (!isAbsolute(v))
45
+ return { ok: false, error: "BAD_DEGENLY_HOME" };
46
+ const norm = (p) => (POSIX ? resolve(p) : resolve(p).toLowerCase());
47
+ const rel = relative(norm(cwd), norm(v));
48
+ if (rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)))
49
+ return { ok: false, error: "BAD_DEGENLY_HOME" };
50
+ return { ok: true, home: v };
51
+ }
52
+ function signerOf(key, publicKey) {
53
+ const address = base58Encode(publicKey);
54
+ return Object.freeze({
55
+ address,
56
+ sign: (message) => new Uint8Array(edSign(null, message, key)),
57
+ });
58
+ }
59
+ function publicKeyOf(key) {
60
+ const der = createPublicKey(key).export({ format: "der", type: "spki" });
61
+ return new Uint8Array(der.subarray(der.length - 32));
62
+ }
63
+ function privateKeyFromSeed(seed) {
64
+ return createPrivateKey({ key: Buffer.concat([PKCS8_ED25519_PREFIX, Buffer.from(seed)]), format: "der", type: "pkcs8" });
65
+ }
66
+ /** A signer from a 32-byte seed (tests: RFC 8032 vectors). */
67
+ export function signerFromSeed(seed) {
68
+ if (seed.length !== 32)
69
+ throw new Error("seed must be 32 bytes");
70
+ const key = privateKeyFromSeed(seed);
71
+ return signerOf(key, publicKeyOf(key));
72
+ }
73
+ function seedOf(key) {
74
+ const der = key.export({ format: "der", type: "pkcs8" });
75
+ return new Uint8Array(der.subarray(der.length - 32));
76
+ }
77
+ function ensureDir(home) {
78
+ const dir = degenlyDir(home);
79
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
80
+ if (POSIX)
81
+ chmodSync(dir, 0o700);
82
+ }
83
+ /** `setup`: a NEW wallet, only if no file exists. Never overwrites (flag `wx`). */
84
+ export function createWallet(home) {
85
+ const file = walletPath(home);
86
+ if (existsSync(file))
87
+ return { ok: false, error: "WALLET_EXISTS" };
88
+ const { privateKey } = generateKeyPairSync("ed25519");
89
+ const pub = publicKeyOf(privateKey);
90
+ const seed = seedOf(privateKey);
91
+ const content = JSON.stringify([...seed, ...pub]);
92
+ seed.fill(0);
93
+ try {
94
+ ensureDir(home);
95
+ writeFileSync(file, content, { mode: 0o600, flag: "wx" });
96
+ if (POSIX)
97
+ chmodSync(file, 0o600);
98
+ }
99
+ catch (e) {
100
+ if (typeof e === "object" && e !== null && e.code === "EEXIST")
101
+ return { ok: false, error: "WALLET_EXISTS" };
102
+ return { ok: false, error: "WALLET_WRITE_FAILED" };
103
+ }
104
+ return { ok: true, wallet: signerOf(privateKey, pub), path: file };
105
+ }
106
+ /** Reads the wallet. Missing → NO_WALLET; anything else than a valid 64-byte keypair → WALLET_CORRUPT (file untouched). */
107
+ export function loadWallet(home) {
108
+ const file = walletPath(home);
109
+ if (!existsSync(file))
110
+ return { ok: false, error: "NO_WALLET" };
111
+ let arr;
112
+ try {
113
+ arr = JSON.parse(readFileSync(file, "utf8"));
114
+ }
115
+ catch {
116
+ return { ok: false, error: "WALLET_CORRUPT" };
117
+ }
118
+ if (!Array.isArray(arr) || arr.length !== 64 || !arr.every((b) => typeof b === "number" && Number.isInteger(b) && b >= 0 && b <= 255)) {
119
+ return { ok: false, error: "WALLET_CORRUPT" };
120
+ }
121
+ const bytes = Uint8Array.from(arr);
122
+ const seed = bytes.slice(0, 32);
123
+ try {
124
+ const key = privateKeyFromSeed(seed);
125
+ const pub = publicKeyOf(key);
126
+ // the stored public half must be the one the seed gives (a hand-edited / truncated file is refused)
127
+ if (Buffer.compare(Buffer.from(pub), Buffer.from(bytes.subarray(32))) !== 0)
128
+ return { ok: false, error: "WALLET_CORRUPT" };
129
+ return { ok: true, wallet: signerOf(key, pub) };
130
+ }
131
+ catch {
132
+ return { ok: false, error: "WALLET_CORRUPT" };
133
+ }
134
+ finally {
135
+ seed.fill(0);
136
+ bytes.fill(0);
137
+ }
138
+ }