@vault77/summon 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Humble Digital, llc
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,192 @@
1
+ # summonTheWarlord — a VAULT77 🔐77 relic
2
+
3
+ ![Release](https://img.shields.io/github/v/release/monthviewsales/summonTheWarlord)
4
+ ![Node](https://img.shields.io/badge/node-%3E%3D18.x-brightgreen)
5
+ ![Platform](https://img.shields.io/badge/platform-macOS-blue)
6
+
7
+ **Version:** 2.0.1
8
+
9
+ > _Relic software unearthed from VAULT77.
10
+ > For trench operators only. macOS‑native. Handle with care._
11
+ > It executes trades with speed and precision — a lifeline to save our futures.
12
+
13
+ ---
14
+
15
+ ⚠️ **Operator notice:** summonTheWarlord executes live on‑chain swaps. Always verify token mints, amounts, and configuration values before execution. If you buy crap its your fault.
16
+
17
+ ## Requirements
18
+
19
+ - Node.js >= 18
20
+ - A [SolanaTracker.io](https://www.solanatracker.io/?ref=0NGJ5PPN) account
21
+ - macOS (required for native Keychain security and system notifications; other operating systems are not supported)
22
+
23
+ ---
24
+
25
+ ## 📡 Connect with VAULT77
26
+
27
+ - **VAULT77 Community:** https://x.com/i/communities/1962257350309650488
28
+ - **Telegram:** https://t.me/BurnWalletBroadcast
29
+
30
+ ---
31
+
32
+ # ⚡️ Step‑by‑Step Quickstart Guide
33
+
34
+ ### 1. Install from npm
35
+
36
+ ```bash
37
+ npm install -g @vault77/summon
38
+ ```
39
+
40
+ ### 2. First Run — Initialize Wallet + Permissions
41
+
42
+ ```bash
43
+ summon setup
44
+ ```
45
+
46
+ This:
47
+
48
+ - Creates/updates your config (RPC URL, slippage, priority fees, etc.)
49
+ - Stores your private key securely in macOS Keychain
50
+ - Prompts macOS notification permissions (optional)
51
+
52
+ ---
53
+
54
+ # ⚔️ Trading Examples
55
+
56
+ ### Buy with 0.1 SOL
57
+
58
+ ```bash
59
+ summon buy <TOKEN_MINT> 0.1
60
+ ```
61
+
62
+ ### Sell 50% of holdings
63
+
64
+ ```bash
65
+ summon sell <TOKEN_MINT> 50%
66
+ ```
67
+
68
+ ---
69
+
70
+ # 🧰 Local Development (optional)
71
+
72
+ ```bash
73
+ git clone https://github.com/monthviewsales/summonTheWarlord.git
74
+ cd summonTheWarlord
75
+ npm install
76
+ node summon-cli.js setup
77
+ ```
78
+
79
+ ---
80
+
81
+ # 🛠 Upgrading
82
+
83
+ ```bash
84
+ npm install -g @vault77/summon@latest
85
+ ```
86
+
87
+ ---
88
+
89
+ # 👁‍🗨 For Coding Agents & Contributors
90
+
91
+ See **AGENTS.md** for building conventions, coding rules, and automation guidance.
92
+
93
+ ---
94
+
95
+ # 🛡 Support
96
+
97
+ - **VAULT77 Community:** https://x.com/i/communities/1962257350309650488
98
+ - **Telegram:** https://t.me/BurnWalletBroadcast
99
+
100
+ ---
101
+
102
+ # ⚙️ Configuration
103
+
104
+ The CLI stores configuration in:
105
+
106
+ - `~/Library/Application Support/summonTheWarlord/config.json`
107
+
108
+ You can manage it with:
109
+
110
+ ```bash
111
+ summon config view
112
+ summon config edit
113
+ summon config set <key> <value>
114
+ summon config wizard
115
+ summon config list
116
+ ```
117
+
118
+ Tip: use `summon config wizard` for validated prompts and selector-based choices.
119
+
120
+ Key options:
121
+
122
+ - `rpcUrl` (the CLI will append `advancedTx=true` if missing)
123
+ - `slippage` (number or `"auto"`)
124
+ - `priorityFee` (number or `"auto"`)
125
+ - `priorityFeeLevel` (`min|low|medium|high|veryHigh`) — required when `priorityFee="auto"`
126
+ - `txVersion` (`v0` or `legacy`)
127
+ - `showQuoteDetails` (`true`/`false`)
128
+ - `DEBUG_MODE` (`true`/`false`)
129
+ - `notificationsEnabled` (`true`/`false`)
130
+ - `jito.enabled` (`true`/`false`)
131
+ - `jito.tip` (number, SOL)
132
+
133
+ If you want fewer popups, set `notificationsEnabled` to `false`.
134
+
135
+ Override config location (useful for CI or tests):
136
+
137
+ - `SUMMON_CONFIG_HOME=/custom/config/dir`
138
+ - `SUMMON_CONFIG_PATH=/custom/path/config.json`
139
+
140
+ Private keys are never stored in this file. Use:
141
+
142
+ ```bash
143
+ summon keychain store
144
+ summon keychain unlock
145
+ summon keychain delete
146
+ ```
147
+
148
+ ---
149
+
150
+ # 🧪 Testing & Linting
151
+
152
+ ```bash
153
+ npm test
154
+ npm run lint
155
+ ```
156
+
157
+ ---
158
+
159
+ # 🩺 Diagnostics
160
+
161
+ ```bash
162
+ summon doctor
163
+ ```
164
+
165
+ Runs checks for config, Keychain access, RPC reachability, swap API health, and macOS notifications (skipped when disabled).
166
+
167
+ ---
168
+
169
+ # 🫡 Open Source Thanks
170
+
171
+ This never would have been possible without Open Source Software and these contributions.
172
+
173
+ Dependencies:
174
+
175
+ - `@solana/web3.js` — [MIT](https://github.com/solana-foundation/solana-web3.js/blob/HEAD/LICENSE)
176
+ - `axios` — [MIT](https://github.com/axios/axios/blob/HEAD/LICENSE)
177
+ - `bs58` — [MIT](https://github.com/cryptocoinjs/bs58/blob/HEAD/LICENSE)
178
+ - `commander` — [MIT](https://github.com/tj/commander.js/blob/HEAD/LICENSE)
179
+ - `fs-extra` — [MIT](https://github.com/jprichardson/node-fs-extra/blob/HEAD/LICENSE)
180
+ - `keytar` — [MIT](https://github.com/atom/node-keytar/blob/HEAD/LICENSE)
181
+ - `npm` — [Artistic-2.0](https://github.com/npm/cli/blob/HEAD/LICENSE)
182
+ - `open` — [MIT](https://github.com/sindresorhus/open/blob/HEAD/LICENSE)
183
+ - `solana-swap` — [ISC](https://github.com/YZYLAB/solana-swap/blob/HEAD/LICENSE)
184
+
185
+ Tooling:
186
+
187
+ - `eslint` — [MIT](https://github.com/eslint/eslint/blob/HEAD/LICENSE)
188
+ - `eslint-config-standard` — [MIT](https://github.com/standard/eslint-config-standard/blob/HEAD/LICENSE)
189
+ - `eslint-plugin-import` — [MIT](https://github.com/import-js/eslint-plugin-import/blob/HEAD/LICENSE)
190
+ - `eslint-plugin-n` — [MIT](https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/LICENSE)
191
+ - `eslint-plugin-promise` — [ISC](https://github.com/eslint-community/eslint-plugin-promise/blob/HEAD/LICENSE)
192
+ - `jest` — [MIT](https://github.com/jestjs/jest/blob/HEAD/LICENSE)
package/lib/config.js ADDED
@@ -0,0 +1,305 @@
1
+ import fs from "fs-extra";
2
+ import os from "os";
3
+ import path from "path";
4
+ import { spawnSync } from "child_process";
5
+ import { ConfigError } from "./errors.js";
6
+ import { logger } from "../utils/logger.js";
7
+
8
+ // Application name for config directory
9
+ const APP_NAME = "summonTheWarlord";
10
+
11
+ export const PRIORITY_FEE_LEVELS = ["min", "low", "medium", "high", "veryHigh"];
12
+ export const TX_VERSIONS = ["v0", "legacy"];
13
+ const DEFAULT_JITO = { enabled: false, tip: 0.0001 };
14
+ const DEPRECATED_KEYS = new Set(["swapAPIKey"]);
15
+
16
+ // Default configuration values
17
+ // Note: walletSecretKey has been moved to macOS Keychain storage
18
+ export const DEFAULT_CONFIG = {
19
+ // Welcome to summonTheWarlord, a CLI for simple fast trading on Solana.
20
+ // Its required that you use SolanaTracker.io as your RPC as they also provide required APIs.
21
+ // This is a free public endpoint and may have issues.
22
+ // You can get a free account at https://www.solanatracker.io/solana-rpc
23
+ // Replace the URL with the new one provided and keep '?advancedTx=true' after your API Key.
24
+ rpcUrl: "https://rpc.solanatracker.io/public?advancedTx=true",
25
+ slippage: 10, // Maximum acceptable slippage percentage (e.g., 10) or "auto"
26
+ priorityFee: "auto", // Amount in SOL or "auto"
27
+ priorityFeeLevel: "medium", // "min","low","medium","high","veryHigh"
28
+ txVersion: "v0", // "v0" or "legacy"
29
+ showQuoteDetails: false, // Outputs the JSON swap response to the console
30
+ DEBUG_MODE: false, // Enable debug logging
31
+ notificationsEnabled: true, // Enable macOS notifications
32
+ jito: { ...DEFAULT_JITO }, // Jito bundle settings
33
+ // walletSecretKey: "", // Deprecated: now stored in macOS Keychain,
34
+ };
35
+
36
+ export const CONFIG_KEYS = Object.freeze(Object.keys(DEFAULT_CONFIG));
37
+
38
+ const BOOLEAN_KEYS = new Set(["showQuoteDetails", "DEBUG_MODE", "notificationsEnabled"]);
39
+ const STRING_KEYS = new Set(["rpcUrl"]);
40
+
41
+ function coerceBoolean(value) {
42
+ if (typeof value === "boolean") return value;
43
+ if (typeof value === "string") {
44
+ const lowered = value.trim().toLowerCase();
45
+ if (lowered === "true") return true;
46
+ if (lowered === "false") return false;
47
+ }
48
+ return null;
49
+ }
50
+
51
+ function coerceNumber(value) {
52
+ if (typeof value === "number" && Number.isFinite(value)) return value;
53
+ if (typeof value === "string") {
54
+ const trimmed = value.trim();
55
+ if (!trimmed) return null;
56
+ const num = Number(trimmed);
57
+ if (Number.isFinite(num)) return num;
58
+ }
59
+ return null;
60
+ }
61
+
62
+ export function parseConfigValue(raw) {
63
+ const trimmed = String(raw ?? "").trim();
64
+ const bool = coerceBoolean(trimmed);
65
+ if (bool !== null) return bool;
66
+ if (trimmed !== "") {
67
+ const num = Number(trimmed);
68
+ if (!Number.isNaN(num)) return num;
69
+ }
70
+ return raw;
71
+ }
72
+
73
+ function evaluateConfigValue(key, value) {
74
+ if (key === "slippage") {
75
+ if (typeof value === "string" && value.trim().toLowerCase() === "auto") {
76
+ return { normalized: "auto" };
77
+ }
78
+ const num = coerceNumber(value);
79
+ if (num === null || num < 0) {
80
+ return { error: "Invalid slippage. Use a non-negative number or \"auto\"." };
81
+ }
82
+ return { normalized: num };
83
+ }
84
+ if (key === "priorityFee") {
85
+ if (typeof value === "string" && value.trim().toLowerCase() === "auto") {
86
+ return { normalized: "auto" };
87
+ }
88
+ const num = coerceNumber(value);
89
+ if (num === null || num < 0) {
90
+ return { error: "Invalid priorityFee. Use a non-negative number or \"auto\"." };
91
+ }
92
+ return { normalized: num };
93
+ }
94
+ if (key === "priorityFeeLevel") {
95
+ if (typeof value !== "string") {
96
+ return { error: `Invalid priorityFeeLevel. Use one of ${PRIORITY_FEE_LEVELS.join(", ")}.` };
97
+ }
98
+ const normalizedLevel = value.trim();
99
+ const match = PRIORITY_FEE_LEVELS.find((level) => level.toLowerCase() === normalizedLevel.toLowerCase());
100
+ if (!match) {
101
+ return { error: `Invalid priorityFeeLevel. Use one of ${PRIORITY_FEE_LEVELS.join(", ")}.` };
102
+ }
103
+ return { normalized: match };
104
+ }
105
+ if (key === "txVersion") {
106
+ if (typeof value !== "string") {
107
+ return { error: `Invalid txVersion. Use ${TX_VERSIONS.join(" or ")}.` };
108
+ }
109
+ const normalizedVersion = value.trim();
110
+ const match = TX_VERSIONS.find((version) => version.toLowerCase() === normalizedVersion.toLowerCase());
111
+ if (!match) {
112
+ return { error: `Invalid txVersion. Use ${TX_VERSIONS.join(" or ")}.` };
113
+ }
114
+ return { normalized: match };
115
+ }
116
+ if (key === "jito") {
117
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
118
+ return { error: "Invalid jito config. Expected an object with enabled and tip." };
119
+ }
120
+ const enabledRaw = value.enabled === undefined ? DEFAULT_JITO.enabled : value.enabled;
121
+ const enabled = coerceBoolean(enabledRaw);
122
+ if (enabled === null) {
123
+ return { error: "Invalid jito.enabled. Use true or false." };
124
+ }
125
+ const tipRaw = value.tip === undefined ? DEFAULT_JITO.tip : value.tip;
126
+ const tip = coerceNumber(tipRaw);
127
+ if (tip === null || tip < 0) {
128
+ return { error: "Invalid jito.tip. Use a non-negative number." };
129
+ }
130
+ return { normalized: { enabled, tip } };
131
+ }
132
+ if (BOOLEAN_KEYS.has(key)) {
133
+ const bool = coerceBoolean(value);
134
+ if (bool === null) {
135
+ return { error: `Invalid ${key}. Use true or false.` };
136
+ }
137
+ return { normalized: bool };
138
+ }
139
+ if (STRING_KEYS.has(key)) {
140
+ if (typeof value !== "string") {
141
+ return { error: `Invalid ${key}. Expected a string.` };
142
+ }
143
+ if (key === "rpcUrl" && value.trim() === "") {
144
+ return { error: "Invalid rpcUrl. Expected a non-empty string." };
145
+ }
146
+ return { normalized: value };
147
+ }
148
+ return { normalized: value };
149
+ }
150
+
151
+ export function normalizeConfigValue(key, value, { strict = false } = {}) {
152
+ const { normalized, error } = evaluateConfigValue(key, value);
153
+ if (error) {
154
+ if (strict) {
155
+ throw new ConfigError(error, { details: { key, value } });
156
+ }
157
+ return DEFAULT_CONFIG[key];
158
+ }
159
+ return normalized;
160
+ }
161
+
162
+ export function normalizeConfig(cfg, { strict = false } = {}) {
163
+ const normalized = { ...cfg };
164
+ const warnings = [];
165
+ let changed = false;
166
+
167
+ for (const key of DEPRECATED_KEYS) {
168
+ if (key in normalized) {
169
+ delete normalized[key];
170
+ changed = true;
171
+ }
172
+ }
173
+
174
+ for (const [key, value] of Object.entries(DEFAULT_CONFIG)) {
175
+ if (!(key in normalized)) {
176
+ normalized[key] = value;
177
+ changed = true;
178
+ }
179
+ }
180
+
181
+ for (const key of Object.keys(DEFAULT_CONFIG)) {
182
+ const originalValue = normalized[key];
183
+ const { normalized: nextValue, error } = evaluateConfigValue(key, originalValue);
184
+ if (error) {
185
+ if (strict) {
186
+ throw new ConfigError(error, { details: { key, value: originalValue } });
187
+ }
188
+ normalized[key] = DEFAULT_CONFIG[key];
189
+ warnings.push({ key, message: error });
190
+ changed = true;
191
+ continue;
192
+ }
193
+ if (!Object.is(originalValue, nextValue)) {
194
+ normalized[key] = nextValue;
195
+ changed = true;
196
+ }
197
+ }
198
+
199
+ return { config: normalized, changed, warnings };
200
+ }
201
+
202
+ /**
203
+ * Compute the path to the config file.
204
+ * - On macOS: ~/Library/Application Support/summonTheWarlord/config.json
205
+ * - Else: $XDG_CONFIG_HOME/summonTheWarlord/config.json (or ~/.config/…)
206
+ */
207
+ export function getConfigPath() {
208
+ const home = os.homedir();
209
+ if (process.env.SUMMON_CONFIG_PATH) {
210
+ return process.env.SUMMON_CONFIG_PATH;
211
+ }
212
+ if (process.env.SUMMON_CONFIG_HOME) {
213
+ return path.join(process.env.SUMMON_CONFIG_HOME, APP_NAME, "config.json");
214
+ }
215
+ if (process.platform === "darwin") {
216
+ const appSupport = path.join(home, "Library", "Application Support", APP_NAME);
217
+ return path.join(appSupport, "config.json");
218
+ }
219
+ const xdgConfig = process.env.XDG_CONFIG_HOME || path.join(home, ".config");
220
+ return path.join(xdgConfig, APP_NAME, "config.json");
221
+ }
222
+
223
+ /**
224
+ * Load the config, writing defaults if the file didn't exist.
225
+ * Also merges in any new keys from DEFAULT_CONFIG.
226
+ */
227
+ export async function loadConfig() {
228
+ const configPath = getConfigPath();
229
+
230
+ // If missing, write out defaults
231
+ if (!await fs.pathExists(configPath)) {
232
+ await fs.ensureDir(path.dirname(configPath), { mode: 0o700 });
233
+ await fs.writeJson(configPath, DEFAULT_CONFIG, { spaces: 2 });
234
+ await fs.chmod(configPath, 0o600);
235
+ return { ...DEFAULT_CONFIG };
236
+ }
237
+
238
+ // Read existing, merge missing defaults
239
+ let cfg;
240
+ try {
241
+ cfg = await fs.readJson(configPath);
242
+ } catch (err) {
243
+ let backupPath;
244
+ try {
245
+ if (await fs.pathExists(configPath)) {
246
+ backupPath = `${configPath}.invalid-${Date.now()}`;
247
+ await fs.move(configPath, backupPath, { overwrite: true });
248
+ }
249
+ } catch (moveErr) {
250
+ console.warn(`⚠️ Unable to back up invalid config: ${moveErr.message}`);
251
+ }
252
+
253
+ await fs.ensureDir(path.dirname(configPath), { mode: 0o700 });
254
+ await fs.writeJson(configPath, DEFAULT_CONFIG, { spaces: 2 });
255
+ await fs.chmod(configPath, 0o600);
256
+
257
+ if (backupPath) {
258
+ logger.warn("Config was invalid and has been reset.", { backupPath });
259
+ } else {
260
+ logger.warn("Config was invalid and has been reset.");
261
+ }
262
+ return { ...DEFAULT_CONFIG };
263
+ }
264
+ let updated = false;
265
+ for (const [key, value] of Object.entries(DEFAULT_CONFIG)) {
266
+ if (!(key in cfg)) {
267
+ cfg[key] = value;
268
+ updated = true;
269
+ }
270
+ }
271
+ const { config: normalized, changed, warnings } = normalizeConfig(cfg);
272
+ warnings.forEach((warning) => {
273
+ logger.warn(warning.message, { key: warning.key });
274
+ });
275
+ if (updated || changed) {
276
+ await fs.writeJson(configPath, normalized, { spaces: 2 });
277
+ await fs.chmod(configPath, 0o600);
278
+ }
279
+ return normalized;
280
+ }
281
+
282
+ /**
283
+ * Save the given config object back to disk (with secure perms).
284
+ */
285
+ export async function saveConfig(cfg) {
286
+ const configPath = getConfigPath();
287
+ const { config: normalized, warnings } = normalizeConfig(cfg);
288
+ warnings.forEach((warning) => {
289
+ logger.warn(warning.message, { key: warning.key });
290
+ });
291
+ await fs.ensureDir(path.dirname(configPath), { mode: 0o700 });
292
+ // Note: walletSecretKey is now stored securely in the macOS Keychain, not in this file
293
+ await fs.writeJson(configPath, normalized, { spaces: 2 });
294
+ await fs.chmod(configPath, 0o600);
295
+ }
296
+
297
+ /**
298
+ * Open the config file in the user's $EDITOR.
299
+ */
300
+ export async function editConfig() {
301
+ const configPath = getConfigPath();
302
+ await loadConfig();
303
+ const editor = process.env.EDITOR || "vim";
304
+ spawnSync(editor, [configPath], { stdio: "inherit" });
305
+ }
package/lib/doctor.js ADDED
@@ -0,0 +1,143 @@
1
+ import { loadConfig } from "./config.js";
2
+ import { getPrivateKey, hasPrivateKey } from "../utils/keychain.js";
3
+ import { notify } from "../utils/notify.js";
4
+ import { ensureAdvancedTx, getSwapClient } from "./swapClient.js";
5
+
6
+ const WRAPPED_SOL_MINT = "So11111111111111111111111111111111111111112";
7
+ const TRUMP_MINT = "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN";
8
+ const MIN_SWAP_SOL = 0.0001;
9
+
10
+ function makeResult(name, status, message, details) {
11
+ return { name, status, message, details };
12
+ }
13
+
14
+ async function checkConfig() {
15
+ try {
16
+ const cfg = await loadConfig();
17
+ return { cfg, result: makeResult("config", "ok", "Loaded and normalized config.") };
18
+ } catch (err) {
19
+ return { cfg: null, result: makeResult("config", "fail", "Failed to load config.", err?.message) };
20
+ }
21
+ }
22
+
23
+ async function checkKeychain() {
24
+ try {
25
+ const exists = await hasPrivateKey();
26
+ if (!exists) {
27
+ return { ok: false, result: makeResult("keychain", "fail", "No private key stored.") };
28
+ }
29
+ await getPrivateKey();
30
+ return { ok: true, result: makeResult("keychain", "ok", "Private key accessible.") };
31
+ } catch (err) {
32
+ return { ok: false, result: makeResult("keychain", "fail", "Unable to read private key.", err?.message) };
33
+ }
34
+ }
35
+
36
+ async function checkRpc(rpcUrl) {
37
+ if (!rpcUrl) {
38
+ return makeResult("rpc", "fail", "RPC URL not configured.");
39
+ }
40
+ const healthUrl = ensureAdvancedTx(rpcUrl);
41
+ try {
42
+ const res = await fetch(healthUrl, {
43
+ method: "POST",
44
+ headers: { "Content-Type": "application/json" },
45
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "getHealth" }),
46
+ });
47
+ if (!res.ok) {
48
+ return makeResult("rpc", "fail", "RPC health check failed.", `HTTP ${res.status}`);
49
+ }
50
+ const body = await res.json();
51
+ if (body.result !== "ok") {
52
+ return makeResult("rpc", "fail", "RPC returned unhealthy status.", JSON.stringify(body));
53
+ }
54
+ return makeResult("rpc", "ok", "RPC reachable.");
55
+ } catch (err) {
56
+ return makeResult("rpc", "fail", "RPC health check error.", err?.message);
57
+ }
58
+ }
59
+
60
+ async function checkSwapApi(cfg, keychainOk) {
61
+ if (!cfg) {
62
+ return makeResult("swap", "skip", "Swap check skipped (config unavailable).");
63
+ }
64
+ if (!keychainOk) {
65
+ return makeResult("swap", "skip", "Swap check skipped (missing keychain).");
66
+ }
67
+ try {
68
+ const tracker = await getSwapClient();
69
+ const opts = {
70
+ txVersion: cfg.txVersion || "v0",
71
+ priorityFeeLevel: cfg.priorityFeeLevel || "medium",
72
+ fee: { wallet: "8aBKXBErcp1Bi5LmaeGnaXCj9ot7PE4T2wuqHQfeT5E6", percentage: 0.4 },
73
+ feeType: "add",
74
+ };
75
+ const swapResp = await tracker.getSwapInstructions(
76
+ WRAPPED_SOL_MINT,
77
+ TRUMP_MINT,
78
+ MIN_SWAP_SOL,
79
+ cfg.slippage,
80
+ tracker.keypair.publicKey.toBase58(),
81
+ cfg.priorityFee,
82
+ false,
83
+ opts
84
+ );
85
+ const quote = swapResp?.quote ?? swapResp?.rate;
86
+ if (!quote) {
87
+ return makeResult("swap", "fail", "Swap API response missing quote.");
88
+ }
89
+ return makeResult("swap", "ok", "Swap API reachable.");
90
+ } catch (err) {
91
+ return makeResult("swap", "fail", "Swap API check failed.", err?.message);
92
+ }
93
+ }
94
+
95
+ async function checkNotifications(cfg) {
96
+ if (cfg?.notificationsEnabled === false) {
97
+ return makeResult("notifications", "skip", "Notifications disabled in config.");
98
+ }
99
+ if (process.platform !== "darwin") {
100
+ return makeResult("notifications", "skip", "Notifications are macOS-only.");
101
+ }
102
+ try {
103
+ const ok = notify({
104
+ title: "summonTheWarlord",
105
+ subtitle: "Doctor check",
106
+ message: "Notification test from summon doctor.",
107
+ sound: "Ping",
108
+ throwOnError: true,
109
+ });
110
+ if (!ok) {
111
+ return makeResult("notifications", "fail", "Notification failed.");
112
+ }
113
+ return makeResult("notifications", "ok", "Notification sent.");
114
+ } catch (err) {
115
+ return makeResult("notifications", "fail", "Notification failed.", err?.message);
116
+ }
117
+ }
118
+
119
+ export async function runDoctor({ verbose = false } = {}) {
120
+ const results = [];
121
+ const { cfg, result: configResult } = await checkConfig();
122
+ results.push(configResult);
123
+
124
+ const { ok: keychainOk, result: keychainResult } = await checkKeychain();
125
+ results.push(keychainResult);
126
+
127
+ const rpcResult = await checkRpc(cfg?.rpcUrl);
128
+ results.push(rpcResult);
129
+
130
+ const swapResult = await checkSwapApi(cfg, keychainOk);
131
+ results.push(swapResult);
132
+
133
+ const notifyResult = await checkNotifications(cfg);
134
+ results.push(notifyResult);
135
+
136
+ if (verbose) {
137
+ return results.map((item) => ({
138
+ ...item,
139
+ details: item.details || undefined,
140
+ }));
141
+ }
142
+ return results;
143
+ }
package/lib/errors.js ADDED
@@ -0,0 +1,18 @@
1
+ export class AppError extends Error {
2
+ constructor(message, { cause, details } = {}) {
3
+ super(message);
4
+ this.name = this.constructor.name;
5
+ if (cause) {
6
+ this.cause = cause;
7
+ }
8
+ if (details) {
9
+ this.details = details;
10
+ }
11
+ }
12
+ }
13
+
14
+ export class ConfigError extends AppError {}
15
+ export class KeychainError extends AppError {}
16
+ export class SwapError extends AppError {}
17
+ export class NotificationError extends AppError {}
18
+ export class DoctorError extends AppError {}