@execra/core 1.0.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.
Files changed (52) hide show
  1. package/dist/cli/commands.d.ts +21 -0
  2. package/dist/cli/commands.js +686 -0
  3. package/dist/cli/commands.js.map +1 -0
  4. package/dist/cli/index.d.ts +8 -0
  5. package/dist/cli/index.js +1162 -0
  6. package/dist/cli/index.js.map +1 -0
  7. package/dist/cli/prompts.d.ts +12 -0
  8. package/dist/cli/prompts.js +98 -0
  9. package/dist/cli/prompts.js.map +1 -0
  10. package/dist/cli/ui.d.ts +38 -0
  11. package/dist/cli/ui.js +990 -0
  12. package/dist/cli/ui.js.map +1 -0
  13. package/dist/handler/index.d.ts +93 -0
  14. package/dist/handler/index.js +628 -0
  15. package/dist/handler/index.js.map +1 -0
  16. package/dist/handler/walletConnect.d.ts +6 -0
  17. package/dist/handler/walletConnect.js +623 -0
  18. package/dist/handler/walletConnect.js.map +1 -0
  19. package/dist/index.d.ts +14 -0
  20. package/dist/index.js +2046 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/session/index.d.ts +20 -0
  23. package/dist/session/index.js +79 -0
  24. package/dist/session/index.js.map +1 -0
  25. package/dist/solana/index.d.ts +5 -0
  26. package/dist/solana/index.js +302 -0
  27. package/dist/solana/index.js.map +1 -0
  28. package/dist/solana/rpc.d.ts +45 -0
  29. package/dist/solana/rpc.js +120 -0
  30. package/dist/solana/rpc.js.map +1 -0
  31. package/dist/solana/simulate.d.ts +41 -0
  32. package/dist/solana/simulate.js +173 -0
  33. package/dist/solana/simulate.js.map +1 -0
  34. package/dist/solana/tx.d.ts +54 -0
  35. package/dist/solana/tx.js +141 -0
  36. package/dist/solana/tx.js.map +1 -0
  37. package/dist/vault/accounts.d.ts +88 -0
  38. package/dist/vault/accounts.js +126 -0
  39. package/dist/vault/accounts.js.map +1 -0
  40. package/dist/vault/config.d.ts +40 -0
  41. package/dist/vault/config.js +131 -0
  42. package/dist/vault/config.js.map +1 -0
  43. package/dist/vault/index.d.ts +122 -0
  44. package/dist/vault/index.js +580 -0
  45. package/dist/vault/index.js.map +1 -0
  46. package/dist/vault/keystore.d.ts +44 -0
  47. package/dist/vault/keystore.js +118 -0
  48. package/dist/vault/keystore.js.map +1 -0
  49. package/dist/vault/mnemonic.d.ts +43 -0
  50. package/dist/vault/mnemonic.js +37 -0
  51. package/dist/vault/mnemonic.js.map +1 -0
  52. package/package.json +49 -0
@@ -0,0 +1,126 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/vault/accounts.ts
4
+ import { derivePath } from "ed25519-hd-key";
5
+ import nacl from "tweetnacl";
6
+ import bs58 from "bs58";
7
+
8
+ // src/vault/mnemonic.ts
9
+ import * as bip39 from "bip39";
10
+ function validateMnemonic2(mnemonic) {
11
+ const cleaned = cleanMnemonic(mnemonic);
12
+ return bip39.validateMnemonic(cleaned);
13
+ }
14
+ async function mnemonicToSeed2(mnemonic, passphrase = "") {
15
+ const cleaned = cleanMnemonic(mnemonic);
16
+ if (!validateMnemonic2(cleaned)) {
17
+ throw new Error("Invalid mnemonic: failed wordlist or checksum validation");
18
+ }
19
+ return bip39.mnemonicToSeed(cleaned, passphrase);
20
+ }
21
+ function cleanMnemonic(mnemonic) {
22
+ return mnemonic.trim().toLowerCase().replace(/\s+/g, " ");
23
+ }
24
+
25
+ // src/vault/accounts.ts
26
+ function deriveAccount(seed, index, name = `Account ${index + 1}`) {
27
+ const path = derivationPath(index);
28
+ const { key: privateKeyBytes } = derivePath(path, seed.toString("hex"));
29
+ const keypair = nacl.sign.keyPair.fromSeed(privateKeyBytes);
30
+ const publicKey = bs58.encode(Buffer.from(keypair.publicKey));
31
+ return {
32
+ index,
33
+ name,
34
+ publicKey,
35
+ secretKey: keypair.secretKey,
36
+ // 64 bytes: seed + public key
37
+ derivationPath: path,
38
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
39
+ };
40
+ }
41
+ function deriveAccounts(seed, accountStore) {
42
+ return accountStore.accounts.map(
43
+ (account) => deriveAccount(seed, account.index, account.name)
44
+ );
45
+ }
46
+ async function deriveAccountFromMnemonic(mnemonic, index, name, passphrase) {
47
+ const seed = await mnemonicToSeed2(mnemonic, passphrase);
48
+ return deriveAccount(seed, index, name);
49
+ }
50
+ function createAccountStore(firstAccountName = "Account 1") {
51
+ return {
52
+ accounts: [
53
+ {
54
+ index: 0,
55
+ name: firstAccountName,
56
+ publicKey: "",
57
+ // filled in after derivation
58
+ derivationPath: derivationPath(0),
59
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
60
+ }
61
+ ],
62
+ activeIndex: 0
63
+ };
64
+ }
65
+ function addAccount(store, seed, name) {
66
+ const nextIndex = store.accounts.length > 0 ? Math.max(...store.accounts.map((a) => a.index)) + 1 : 0;
67
+ const accountName = name ?? `Account ${nextIndex + 1}`;
68
+ const keypair = deriveAccount(seed, nextIndex, accountName);
69
+ const newAccount = {
70
+ index: nextIndex,
71
+ name: accountName,
72
+ publicKey: keypair.publicKey,
73
+ derivationPath: keypair.derivationPath,
74
+ createdAt: keypair.createdAt
75
+ };
76
+ const updatedStore = {
77
+ ...store,
78
+ accounts: [...store.accounts, newAccount]
79
+ };
80
+ return { store: updatedStore, keypair };
81
+ }
82
+ function setActiveAccount(store, index) {
83
+ const exists = store.accounts.find((a) => a.index === index);
84
+ if (!exists) {
85
+ throw new Error(`Account index ${index} does not exist.`);
86
+ }
87
+ return { ...store, activeIndex: index };
88
+ }
89
+ function renameAccount(store, index, newName) {
90
+ return {
91
+ ...store,
92
+ accounts: store.accounts.map(
93
+ (a) => a.index === index ? { ...a, name: newName } : a
94
+ )
95
+ };
96
+ }
97
+ function getActiveAccount(store) {
98
+ const account = store.accounts.find((a) => a.index === store.activeIndex);
99
+ if (!account) throw new Error("No active account found.");
100
+ return account;
101
+ }
102
+ function signMessage(message, secretKey) {
103
+ const signature = nacl.sign.detached(message, secretKey);
104
+ return bs58.encode(Buffer.from(signature));
105
+ }
106
+ function formatAccount(account, isActive) {
107
+ const activeMarker = isActive ? "\u25CF" : "\u25CB";
108
+ const shortKey = `${account.publicKey.slice(0, 4)}...${account.publicKey.slice(-4)}`;
109
+ return `${activeMarker} [${account.index}] ${account.name.padEnd(20)} ${shortKey}`;
110
+ }
111
+ function derivationPath(index) {
112
+ return `m/44'/501'/${index}'/0'`;
113
+ }
114
+ export {
115
+ addAccount,
116
+ createAccountStore,
117
+ deriveAccount,
118
+ deriveAccountFromMnemonic,
119
+ deriveAccounts,
120
+ formatAccount,
121
+ getActiveAccount,
122
+ renameAccount,
123
+ setActiveAccount,
124
+ signMessage
125
+ };
126
+ //# sourceMappingURL=accounts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/vault/accounts.ts","../../src/vault/mnemonic.ts"],"sourcesContent":["/**\n *\n * BIP-44 HD key derivation for Solana accounts.\n *\n * Derivation path: m/44'/501'/index'/0'\n * 44' = BIP-44 purpose\n * 501' = Solana's registered coin type (SLIP-44)\n * n' = account index (0 = first account, 1 = second, etc.)\n * 0' = change (always 0 for Solana)\n *\n * This is the exact path Phantom, Backpack, and Solflare use.\n * Same seed → same addresses as those wallets.\n *\n * Dependencies: ed25519-hd-key, tweetnacl, bs58\n */\n\nimport { derivePath } from \"ed25519-hd-key\";\nimport nacl from \"tweetnacl\";\nimport bs58 from \"bs58\";\nimport { mnemonicToSeed } from \"./mnemonic\";\n\n// ── Types ─────────────────────────────────────────────────────────────────────\n\nexport interface Account {\n index: number; // derivation index\n name: string; // user-defined label\n publicKey: string; // Base58 encoded — this is the Solana address\n derivationPath: string; // m/44'/501'/index'/0'\n createdAt: string;\n}\n\n/**\n * In-memory keypair — private key NEVER persisted to disk.\n * Lives only for the duration of the daemon session.\n */\nexport interface AccountKeypair extends Account {\n secretKey: Uint8Array; // 64-byte Ed25519 secret key (seed + public key)\n}\n\nexport interface AccountStore {\n accounts: Account[];\n activeIndex: number;\n}\n\n// ── Derivation ────────────────────────────────────────────────────────────────\n\n/**\n * Derive an Ed25519 keypair at a specific BIP-44 index.\n * This is the core operation — called once per session after vault unlock.\n *\n * @param seed - 64-byte seed from BIP-39 mnemonic\n * @param index - account index (0-based)\n * @param name - label for this account\n */\nexport function deriveAccount(\n seed: Buffer,\n index: number,\n name: string = `Account ${index + 1}`,\n): AccountKeypair {\n const path = derivationPath(index);\n\n // SLIP-0010 Ed25519 derivation\n const { key: privateKeyBytes } = derivePath(path, seed.toString(\"hex\"));\n\n // nacl keypair from 32-byte seed\n const keypair = nacl.sign.keyPair.fromSeed(privateKeyBytes);\n\n const publicKey = bs58.encode(Buffer.from(keypair.publicKey));\n\n return {\n index,\n name,\n publicKey,\n secretKey: keypair.secretKey, // 64 bytes: seed + public key\n derivationPath: path,\n createdAt: new Date().toISOString(),\n };\n}\n\n/**\n * Derive multiple accounts at once.\n * Used on wallet startup to load all known accounts into memory.\n */\nexport function deriveAccounts(\n seed: Buffer,\n accountStore: AccountStore,\n): AccountKeypair[] {\n return accountStore.accounts.map((account) =>\n deriveAccount(seed, account.index, account.name),\n );\n}\n\n/**\n * Derive a single account directly from mnemonic.\n * Convenience wrapper used in tests and programmatic access.\n */\nexport async function deriveAccountFromMnemonic(\n mnemonic: string,\n index: number,\n name?: string,\n passphrase?: string,\n): Promise<AccountKeypair> {\n const seed = await mnemonicToSeed(mnemonic, passphrase);\n return deriveAccount(seed, index, name);\n}\n\n// ── Account Store ─────────────────────────────────────────────────────────────\n\n/**\n * Create a fresh account store with the first account.\n */\nexport function createAccountStore(\n firstAccountName: string = \"Account 1\",\n): AccountStore {\n return {\n accounts: [\n {\n index: 0,\n name: firstAccountName,\n publicKey: \"\", // filled in after derivation\n derivationPath: derivationPath(0),\n createdAt: new Date().toISOString(),\n },\n ],\n activeIndex: 0,\n };\n}\n\n/**\n * Add a new account to the store.\n * The next index is always max(existing indices) + 1.\n */\nexport function addAccount(\n store: AccountStore,\n seed: Buffer,\n name?: string,\n): { store: AccountStore; keypair: AccountKeypair } {\n const nextIndex =\n store.accounts.length > 0\n ? Math.max(...store.accounts.map((a) => a.index)) + 1\n : 0;\n\n const accountName = name ?? `Account ${nextIndex + 1}`;\n const keypair = deriveAccount(seed, nextIndex, accountName);\n\n const newAccount: Account = {\n index: nextIndex,\n name: accountName,\n publicKey: keypair.publicKey,\n derivationPath: keypair.derivationPath,\n createdAt: keypair.createdAt,\n };\n\n const updatedStore: AccountStore = {\n ...store,\n accounts: [...store.accounts, newAccount],\n };\n\n return { store: updatedStore, keypair };\n}\n\n/**\n * Set the active account by index.\n * The active account is used for all dApp connections and signing.\n */\nexport function setActiveAccount(\n store: AccountStore,\n index: number,\n): AccountStore {\n const exists = store.accounts.find((a) => a.index === index);\n if (!exists) {\n throw new Error(`Account index ${index} does not exist.`);\n }\n return { ...store, activeIndex: index };\n}\n\n/**\n * Rename an account.\n */\nexport function renameAccount(\n store: AccountStore,\n index: number,\n newName: string,\n): AccountStore {\n return {\n ...store,\n accounts: store.accounts.map((a) =>\n a.index === index ? { ...a, name: newName } : a,\n ),\n };\n}\n\n/**\n * Get the active account metadata from the store.\n */\nexport function getActiveAccount(store: AccountStore): Account {\n const account = store.accounts.find((a) => a.index === store.activeIndex);\n if (!account) throw new Error(\"No active account found.\");\n return account;\n}\n\n// ── Utilities ─────────────────────────────────────────────────────────────────\n\n/**\n * Sign a raw message with an account's secret key.\n * Returns a Base58 encoded signature.\n */\nexport function signMessage(\n message: Uint8Array,\n secretKey: Uint8Array,\n): string {\n const signature = nacl.sign.detached(message, secretKey);\n return bs58.encode(Buffer.from(signature));\n}\n\n/**\n * Format account for display in terminal.\n */\nexport function formatAccount(account: Account, isActive: boolean): string {\n const activeMarker = isActive ? \"●\" : \"○\";\n const shortKey = `${account.publicKey.slice(0, 4)}...${account.publicKey.slice(-4)}`;\n return `${activeMarker} [${account.index}] ${account.name.padEnd(20)} ${shortKey}`;\n}\n\n// ── Internal ──────────────────────────────────────────────────────────────────\n\nfunction derivationPath(index: number): string {\n return `m/44'/501'/${index}'/0'`;\n}\n","/**\n *\n * BIP-39 mnemonic generation, validation, and seed derivation.\n * Supports 12-word (128-bit) and 24-word (256-bit) mnemonics.\n *\n * Dependencies: bip39\n */\n\nimport * as bip39 from \"bip39\";\n\nexport type MnemonicStrength = 12 | 24; // 128 = 12 words, 256 = 24 words\n\nexport interface MnemonicResult {\n mnemonic: string;\n wordCount: 12 | 24;\n}\n\n/**\n * Generate a new cryptographically random BIP-39 mnemonic.\n * @param strength 128 for 12-word, 256 for 24-word (default: 128)\n */\nexport function generateMnemonic(\n strength: MnemonicStrength = 12,\n): MnemonicResult {\n const mnemonic = bip39.generateMnemonic(strength == 12 ? 128 : 256);\n const wordCount = strength;\n return { mnemonic, wordCount };\n}\n\n/**\n * Validate a BIP-39 mnemonic phrase.\n * Checks both wordlist membership and BIP-39 checksum.\n */\nexport function validateMnemonic(mnemonic: string): boolean {\n const cleaned = cleanMnemonic(mnemonic);\n return bip39.validateMnemonic(cleaned);\n}\n\n/**\n * Derive a 64-byte seed buffer from a mnemonic.\n * Optional passphrase adds extra security per BIP-39 spec.\n * This seed is the root of ALL derived accounts.\n */\nexport async function mnemonicToSeed(\n mnemonic: string,\n passphrase: string = \"\",\n): Promise<Buffer> {\n const cleaned = cleanMnemonic(mnemonic);\n\n if (!validateMnemonic(cleaned)) {\n throw new Error(\"Invalid mnemonic: failed wordlist or checksum validation\");\n }\n\n return bip39.mnemonicToSeed(cleaned, passphrase);\n}\n\n/**\n * Split mnemonic into a numbered word array.\n * Used for backup verification display in the terminal UI.\n *\n * Example output:\n * [ \"1. witch\", \"2. collapse\", \"3. practice\", ... ]\n */\nexport function mnemonicToNumberedWords(mnemonic: string): string[] {\n return cleanMnemonic(mnemonic)\n .split(\" \")\n .map((word, i) => `${i + 1}. ${word}`);\n}\n\n/**\n * Reconstruct mnemonic from a word array.\n * Used when user inputs words one by one during restore flow.\n */\nexport function wordsToMnemonic(words: string[]): string {\n return words.map((w) => w.trim().toLowerCase()).join(\" \");\n}\n\n// ── Internal ──────────────────────────────────────────────────────────────────\n\nfunction cleanMnemonic(mnemonic: string): string {\n return mnemonic.trim().toLowerCase().replace(/\\s+/g, \" \");\n}\n"],"mappings":";;;AAgBA,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AACjB,OAAO,UAAU;;;ACVjB,YAAY,WAAW;AAyBhB,SAASA,kBAAiB,UAA2B;AAC1D,QAAM,UAAU,cAAc,QAAQ;AACtC,SAAa,uBAAiB,OAAO;AACvC;AAOA,eAAsBC,gBACpB,UACA,aAAqB,IACJ;AACjB,QAAM,UAAU,cAAc,QAAQ;AAEtC,MAAI,CAACD,kBAAiB,OAAO,GAAG;AAC9B,UAAM,IAAI,MAAM,0DAA0D;AAAA,EAC5E;AAEA,SAAa,qBAAe,SAAS,UAAU;AACjD;AAyBA,SAAS,cAAc,UAA0B;AAC/C,SAAO,SAAS,KAAK,EAAE,YAAY,EAAE,QAAQ,QAAQ,GAAG;AAC1D;;;AD3BO,SAAS,cACd,MACA,OACA,OAAe,WAAW,QAAQ,CAAC,IACnB;AAChB,QAAM,OAAO,eAAe,KAAK;AAGjC,QAAM,EAAE,KAAK,gBAAgB,IAAI,WAAW,MAAM,KAAK,SAAS,KAAK,CAAC;AAGtE,QAAM,UAAU,KAAK,KAAK,QAAQ,SAAS,eAAe;AAE1D,QAAM,YAAY,KAAK,OAAO,OAAO,KAAK,QAAQ,SAAS,CAAC;AAE5D,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW,QAAQ;AAAA;AAAA,IACnB,gBAAgB;AAAA,IAChB,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,EACpC;AACF;AAMO,SAAS,eACd,MACA,cACkB;AAClB,SAAO,aAAa,SAAS;AAAA,IAAI,CAAC,YAChC,cAAc,MAAM,QAAQ,OAAO,QAAQ,IAAI;AAAA,EACjD;AACF;AAMA,eAAsB,0BACpB,UACA,OACA,MACA,YACyB;AACzB,QAAM,OAAO,MAAME,gBAAe,UAAU,UAAU;AACtD,SAAO,cAAc,MAAM,OAAO,IAAI;AACxC;AAOO,SAAS,mBACd,mBAA2B,aACb;AACd,SAAO;AAAA,IACL,UAAU;AAAA,MACR;AAAA,QACE,OAAO;AAAA,QACP,MAAM;AAAA,QACN,WAAW;AAAA;AAAA,QACX,gBAAgB,eAAe,CAAC;AAAA,QAChC,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC;AAAA,IACF;AAAA,IACA,aAAa;AAAA,EACf;AACF;AAMO,SAAS,WACd,OACA,MACA,MACkD;AAClD,QAAM,YACJ,MAAM,SAAS,SAAS,IACpB,KAAK,IAAI,GAAG,MAAM,SAAS,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,IAClD;AAEN,QAAM,cAAc,QAAQ,WAAW,YAAY,CAAC;AACpD,QAAM,UAAU,cAAc,MAAM,WAAW,WAAW;AAE1D,QAAM,aAAsB;AAAA,IAC1B,OAAO;AAAA,IACP,MAAM;AAAA,IACN,WAAW,QAAQ;AAAA,IACnB,gBAAgB,QAAQ;AAAA,IACxB,WAAW,QAAQ;AAAA,EACrB;AAEA,QAAM,eAA6B;AAAA,IACjC,GAAG;AAAA,IACH,UAAU,CAAC,GAAG,MAAM,UAAU,UAAU;AAAA,EAC1C;AAEA,SAAO,EAAE,OAAO,cAAc,QAAQ;AACxC;AAMO,SAAS,iBACd,OACA,OACc;AACd,QAAM,SAAS,MAAM,SAAS,KAAK,CAAC,MAAM,EAAE,UAAU,KAAK;AAC3D,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,iBAAiB,KAAK,kBAAkB;AAAA,EAC1D;AACA,SAAO,EAAE,GAAG,OAAO,aAAa,MAAM;AACxC;AAKO,SAAS,cACd,OACA,OACA,SACc;AACd,SAAO;AAAA,IACL,GAAG;AAAA,IACH,UAAU,MAAM,SAAS;AAAA,MAAI,CAAC,MAC5B,EAAE,UAAU,QAAQ,EAAE,GAAG,GAAG,MAAM,QAAQ,IAAI;AAAA,IAChD;AAAA,EACF;AACF;AAKO,SAAS,iBAAiB,OAA8B;AAC7D,QAAM,UAAU,MAAM,SAAS,KAAK,CAAC,MAAM,EAAE,UAAU,MAAM,WAAW;AACxE,MAAI,CAAC,QAAS,OAAM,IAAI,MAAM,0BAA0B;AACxD,SAAO;AACT;AAQO,SAAS,YACd,SACA,WACQ;AACR,QAAM,YAAY,KAAK,KAAK,SAAS,SAAS,SAAS;AACvD,SAAO,KAAK,OAAO,OAAO,KAAK,SAAS,CAAC;AAC3C;AAKO,SAAS,cAAc,SAAkB,UAA2B;AACzE,QAAM,eAAe,WAAW,WAAM;AACtC,QAAM,WAAW,GAAG,QAAQ,UAAU,MAAM,GAAG,CAAC,CAAC,MAAM,QAAQ,UAAU,MAAM,EAAE,CAAC;AAClF,SAAO,GAAG,YAAY,KAAK,QAAQ,KAAK,KAAK,QAAQ,KAAK,OAAO,EAAE,CAAC,IAAI,QAAQ;AAClF;AAIA,SAAS,eAAe,OAAuB;AAC7C,SAAO,cAAc,KAAK;AAC5B;","names":["validateMnemonic","mnemonicToSeed","mnemonicToSeed"]}
@@ -0,0 +1,40 @@
1
+ import { AccountStore } from './accounts.js';
2
+
3
+ /**
4
+ *
5
+ * Reads and writes ~/.wallet/config.json
6
+ * Stores non-sensitive wallet preferences:
7
+ * - Active account index
8
+ * - RPC endpoint (mainnet / devnet)
9
+ * - Account metadata (names, indices — no keys)
10
+ * - WalletConnect project ID
11
+ *
12
+ * Dependencies: Node.js built-in `fs`, `os`, `path`
13
+ */
14
+
15
+ type ClusterType = "mainnet-beta" | "devnet" | "testnet" | "localnet" | "custom";
16
+ interface WalletConfig {
17
+ version: number;
18
+ cluster: ClusterType;
19
+ rpcUrl: string;
20
+ walletConnectProjectId: string;
21
+ accountStore: AccountStore;
22
+ createdAt: string;
23
+ updatedAt: string;
24
+ }
25
+ declare const RPC_URLS: Record<Exclude<ClusterType, "custom">, string>;
26
+ declare function configExists(): boolean;
27
+ declare function loadConfig(): WalletConfig;
28
+ declare function saveConfig(config: WalletConfig): void;
29
+ /**
30
+ * Create a fresh config on `wallet init`.
31
+ */
32
+ declare function createConfig(walletConnectProjectId?: string, cluster?: Exclude<ClusterType, "custom">): WalletConfig;
33
+ declare function updateCluster(cluster: Exclude<ClusterType, "custom">): void;
34
+ declare function updateRpcUrl(url: string): void;
35
+ declare function updateAccountStore(accountStore: AccountStore): void;
36
+ declare function getRpcUrl(): string;
37
+ declare function getCluster(): ClusterType;
38
+ declare function getAccountStore(): AccountStore;
39
+
40
+ export { type ClusterType, RPC_URLS, type WalletConfig, configExists, createConfig, getAccountStore, getCluster, getRpcUrl, loadConfig, saveConfig, updateAccountStore, updateCluster, updateRpcUrl };
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/vault/config.ts
4
+ import fs2 from "fs";
5
+
6
+ // src/vault/keystore.ts
7
+ import fs from "fs";
8
+ import os from "os";
9
+ import path from "path";
10
+ function getWalletDir() {
11
+ return path.join(os.homedir(), ".wallet");
12
+ }
13
+ function getConfigPath() {
14
+ return path.join(getWalletDir(), "config.json");
15
+ }
16
+ function getSessionsPath() {
17
+ return path.join(getWalletDir(), "sessions.json");
18
+ }
19
+ var SESSIONS_FILE = getSessionsPath();
20
+ function ensureWalletDir() {
21
+ const dir = getWalletDir();
22
+ if (!fs.existsSync(dir)) {
23
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
24
+ }
25
+ }
26
+
27
+ // src/vault/accounts.ts
28
+ import { derivePath } from "ed25519-hd-key";
29
+ import nacl from "tweetnacl";
30
+ import bs58 from "bs58";
31
+
32
+ // src/vault/mnemonic.ts
33
+ import * as bip39 from "bip39";
34
+
35
+ // src/vault/accounts.ts
36
+ function createAccountStore(firstAccountName = "Account 1") {
37
+ return {
38
+ accounts: [
39
+ {
40
+ index: 0,
41
+ name: firstAccountName,
42
+ publicKey: "",
43
+ // filled in after derivation
44
+ derivationPath: derivationPath(0),
45
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
46
+ }
47
+ ],
48
+ activeIndex: 0
49
+ };
50
+ }
51
+ function derivationPath(index) {
52
+ return `m/44'/501'/${index}'/0'`;
53
+ }
54
+
55
+ // src/vault/config.ts
56
+ var HELIUS_API_KEY = process.env.HELIUS_API_KEY;
57
+ var RPC_URLS = {
58
+ "mainnet-beta": HELIUS_API_KEY ? `https://mainnet.helius-rpc.com/?api-key=${HELIUS_API_KEY}` : "https://api.mainnet-beta.solana.com",
59
+ devnet: HELIUS_API_KEY ? `https://devnet.helius-rpc.com/?api-key=${HELIUS_API_KEY}` : "https://api.devnet.solana.com",
60
+ testnet: "https://api.testnet.solana.com",
61
+ localnet: "http://localhost:8899"
62
+ };
63
+ var CONFIG_VERSION = 1;
64
+ function configExists() {
65
+ return fs2.existsSync(getConfigPath());
66
+ }
67
+ function loadConfig() {
68
+ if (!configExists()) {
69
+ throw new Error("No config found. Run `wallet init` first.");
70
+ }
71
+ const raw = fs2.readFileSync(getConfigPath(), "utf8");
72
+ return JSON.parse(raw);
73
+ }
74
+ function saveConfig(config) {
75
+ ensureWalletDir();
76
+ const updated = { ...config, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
77
+ fs2.writeFileSync(getConfigPath(), JSON.stringify(updated, null, 2), {
78
+ mode: 384
79
+ });
80
+ }
81
+ function createConfig(walletConnectProjectId = "", cluster = "devnet") {
82
+ const now = (/* @__PURE__ */ new Date()).toISOString();
83
+ return {
84
+ version: CONFIG_VERSION,
85
+ cluster,
86
+ rpcUrl: RPC_URLS[cluster],
87
+ walletConnectProjectId,
88
+ accountStore: createAccountStore("Account 1"),
89
+ createdAt: now,
90
+ updatedAt: now
91
+ };
92
+ }
93
+ function updateCluster(cluster) {
94
+ const config = loadConfig();
95
+ config.cluster = cluster;
96
+ config.rpcUrl = RPC_URLS[cluster];
97
+ saveConfig(config);
98
+ }
99
+ function updateRpcUrl(url) {
100
+ const config = loadConfig();
101
+ config.rpcUrl = url;
102
+ saveConfig(config);
103
+ }
104
+ function updateAccountStore(accountStore) {
105
+ const config = loadConfig();
106
+ config.accountStore = accountStore;
107
+ saveConfig(config);
108
+ }
109
+ function getRpcUrl() {
110
+ return loadConfig().rpcUrl;
111
+ }
112
+ function getCluster() {
113
+ return loadConfig().cluster;
114
+ }
115
+ function getAccountStore() {
116
+ return loadConfig().accountStore;
117
+ }
118
+ export {
119
+ RPC_URLS,
120
+ configExists,
121
+ createConfig,
122
+ getAccountStore,
123
+ getCluster,
124
+ getRpcUrl,
125
+ loadConfig,
126
+ saveConfig,
127
+ updateAccountStore,
128
+ updateCluster,
129
+ updateRpcUrl
130
+ };
131
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/vault/config.ts","../../src/vault/keystore.ts","../../src/vault/accounts.ts","../../src/vault/mnemonic.ts"],"sourcesContent":["/**\n *\n * Reads and writes ~/.wallet/config.json\n * Stores non-sensitive wallet preferences:\n * - Active account index\n * - RPC endpoint (mainnet / devnet)\n * - Account metadata (names, indices — no keys)\n * - WalletConnect project ID\n *\n * Dependencies: Node.js built-in `fs`, `os`, `path`\n */\n\nimport fs from \"fs\";\nimport { getConfigPath, ensureWalletDir } from \"./keystore\";\nimport { AccountStore, createAccountStore } from \"./accounts\";\n\n// ── Types ─────────────────────────────────────────────────────────────────────\n\nexport type ClusterType = \"mainnet-beta\" | \"devnet\" | \"testnet\" | \"localnet\" | \"custom\";\n\nexport interface WalletConfig {\n version: number;\n cluster: ClusterType;\n rpcUrl: string;\n walletConnectProjectId: string;\n accountStore: AccountStore;\n createdAt: string;\n updatedAt: string;\n}\n\n// ── Defaults ──────────────────────────────────────────────────────────────────\n\nconst HELIUS_API_KEY = process.env.HELIUS_API_KEY;\nexport const RPC_URLS: Record<Exclude<ClusterType, \"custom\">, string> = {\n \"mainnet-beta\": HELIUS_API_KEY\n ? `https://mainnet.helius-rpc.com/?api-key=${HELIUS_API_KEY}`\n : \"https://api.mainnet-beta.solana.com\",\n devnet: HELIUS_API_KEY\n ? `https://devnet.helius-rpc.com/?api-key=${HELIUS_API_KEY}`\n : \"https://api.devnet.solana.com\",\n testnet: \"https://api.testnet.solana.com\",\n localnet: \"http://localhost:8899\",\n};\n\nconst CONFIG_VERSION = 1;\n\n// ── Read / Write ──────────────────────────────────────────────────────────────\n\nexport function configExists(): boolean {\n return fs.existsSync(getConfigPath());\n}\n\nexport function loadConfig(): WalletConfig {\n if (!configExists()) {\n throw new Error(\"No config found. Run `wallet init` first.\");\n }\n const raw = fs.readFileSync(getConfigPath(), \"utf8\");\n return JSON.parse(raw) as WalletConfig;\n}\n\nexport function saveConfig(config: WalletConfig): void {\n ensureWalletDir();\n const updated = { ...config, updatedAt: new Date().toISOString() };\n fs.writeFileSync(getConfigPath(), JSON.stringify(updated, null, 2), {\n mode: 0o600,\n });\n}\n\n/**\n * Create a fresh config on `wallet init`.\n */\nexport function createConfig(\n walletConnectProjectId: string = \"\",\n cluster: Exclude<ClusterType, \"custom\"> = \"devnet\",\n): WalletConfig {\n const now = new Date().toISOString();\n return {\n version: CONFIG_VERSION,\n cluster,\n rpcUrl: RPC_URLS[cluster],\n walletConnectProjectId,\n accountStore: createAccountStore(\"Account 1\"),\n createdAt: now,\n updatedAt: now,\n };\n}\n\n// ── Helpers ───────────────────────────────────────────────────────────────────\n\nexport function updateCluster(cluster: Exclude<ClusterType, \"custom\">): void {\n const config = loadConfig();\n config.cluster = cluster;\n config.rpcUrl = RPC_URLS[cluster];\n saveConfig(config);\n}\n\nexport function updateRpcUrl(url: string): void {\n const config = loadConfig();\n config.rpcUrl = url;\n saveConfig(config);\n}\n\nexport function updateAccountStore(accountStore: AccountStore): void {\n const config = loadConfig();\n config.accountStore = accountStore;\n saveConfig(config);\n}\n\nexport function getRpcUrl(): string {\n return loadConfig().rpcUrl;\n}\n\nexport function getCluster(): ClusterType {\n return loadConfig().cluster;\n}\n\nexport function getAccountStore(): AccountStore {\n return loadConfig().accountStore;\n}\n","/**\n *\n * AES-256-GCM encrypted keystore.\n * The mnemonic (seed phrase) is encrypted at rest in ~/.wallet/vault.enc\n * Private keys NEVER touch disk — they are derived in memory at runtime.\n *\n * Encryption scheme:\n * - Key derivation: PBKDF2 (SHA-512, 210,000 iterations) — OWASP recommended\n * - Cipher: AES-256-GCM (authenticated encryption — detects tampering)\n * - Salt: 32 random bytes (unique per vault)\n * - IV: 16 random bytes (unique per encryption)\n *\n * Dependencies: Node.js built-in `crypto`, `fs`, `os`, `path`\n */\n\nimport crypto from \"crypto\";\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\n\n// ── Types ─────────────────────────────────────────────────────────────────────\n\nexport interface VaultData {\n mnemonic: string;\n createdAt: string;\n version: number;\n}\n\ninterface EncryptedVault {\n version: number; // format version for future migrations\n salt: string; // hex — used for PBKDF2 key derivation\n iv: string; // hex — AES-GCM initialisation vector\n authTag: string; // hex — GCM authentication tag (detects tampering)\n ciphertext: string; // hex — encrypted vault data\n}\n\n// ── Constants ─────────────────────────────────────────────────────────────────\n\nconst VAULT_VERSION = 1;\nconst PBKDF2_ITERATIONS = 210_000; // OWASP 2024 recommendation for PBKDF2-SHA512\nconst PBKDF2_DIGEST = \"sha512\";\nconst KEY_LENGTH = 32; // 256 bits for AES-256\nconst SALT_LENGTH = 32; // 256 bits\nconst IV_LENGTH = 16; // 128 bits for AES-GCM\nconst CIPHER = \"aes-256-gcm\";\n\n// ── Vault Path ────────────────────────────────────────────────────────────────\n\nexport function getWalletDir(): string {\n // return path.join(__dirname, \".wallet\");\n return path.join(os.homedir(), \".wallet\");\n}\n\nexport function getVaultPath(): string {\n return path.join(getWalletDir(), \"vault.enc\");\n}\n\nexport function getConfigPath(): string {\n return path.join(getWalletDir(), \"config.json\");\n}\n\nexport function getSessionsPath(): string {\n return path.join(getWalletDir(), \"sessions.json\");\n}\n\nexport const SESSIONS_FILE = getSessionsPath();\n\nexport function ensureWalletDir(): void {\n const dir = getWalletDir();\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); // owner-only access\n }\n}\n\nexport function vaultExists(): boolean {\n return fs.existsSync(getVaultPath());\n}\n\n// ── Encryption ────────────────────────────────────────────────────────────────\n\n/**\n * Encrypt and save the vault to disk.\n * @param data - vault contents (mnemonic + metadata)\n * @param password - user's wallet password\n */\nexport async function saveVault(\n data: VaultData,\n password: string,\n): Promise<void> {\n ensureWalletDir();\n\n const salt = crypto.randomBytes(SALT_LENGTH);\n const iv = crypto.randomBytes(IV_LENGTH);\n const key = await deriveKey(password, salt);\n\n const plaintext = JSON.stringify(data);\n const cipher = crypto.createCipheriv(CIPHER, key, iv);\n\n const encrypted = Buffer.concat([\n cipher.update(plaintext, \"utf8\"),\n cipher.final(),\n ]);\n\n const authTag = cipher.getAuthTag();\n\n const vault: EncryptedVault = {\n version: VAULT_VERSION,\n salt: salt.toString(\"hex\"),\n iv: iv.toString(\"hex\"),\n authTag: authTag.toString(\"hex\"),\n ciphertext: encrypted.toString(\"hex\"),\n };\n\n fs.writeFileSync(getVaultPath(), JSON.stringify(vault, null, 2), {\n mode: 0o600, // owner read/write only\n });\n}\n\n/**\n * Load and decrypt the vault from disk.\n * Throws if the password is wrong or the file has been tampered with.\n */\nexport async function loadVault(password: string): Promise<VaultData> {\n if (!vaultExists()) {\n throw new Error(\"No vault found. Run `wallet init` to create one.\");\n }\n\n const raw = fs.readFileSync(getVaultPath(), \"utf8\");\n const vault: EncryptedVault = JSON.parse(raw);\n\n if (vault.version !== VAULT_VERSION) {\n throw new Error(`Unsupported vault version: ${vault.version}`);\n }\n\n const salt = Buffer.from(vault.salt, \"hex\");\n const iv = Buffer.from(vault.iv, \"hex\");\n const authTag = Buffer.from(vault.authTag, \"hex\");\n const ciphertext = Buffer.from(vault.ciphertext, \"hex\");\n\n const key = await deriveKey(password, salt);\n\n try {\n const decipher = crypto.createDecipheriv(CIPHER, key, iv);\n decipher.setAuthTag(authTag);\n\n const decrypted = Buffer.concat([\n decipher.update(ciphertext),\n decipher.final(),\n ]);\n\n return JSON.parse(decrypted.toString(\"utf8\")) as VaultData;\n } catch {\n // GCM auth tag failure means wrong password OR tampered file\n throw new Error(\"Decryption failed: wrong password or vault is corrupted.\");\n }\n}\n\n/**\n * Change the vault password.\n * Decrypts with old password, re-encrypts with new password.\n */\nexport async function changePassword(\n oldPassword: string,\n newPassword: string,\n): Promise<void> {\n const data = await loadVault(oldPassword);\n await saveVault(data, newPassword);\n}\n\n// ── Internal ──────────────────────────────────────────────────────────────────\n\n/**\n * Derive a 256-bit AES key from a password using PBKDF2-SHA512.\n */\nfunction deriveKey(password: string, salt: Buffer): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n crypto.pbkdf2(\n password,\n salt,\n PBKDF2_ITERATIONS,\n KEY_LENGTH,\n PBKDF2_DIGEST,\n (err, key) => {\n if (err) reject(err);\n else resolve(key);\n },\n );\n });\n}\n","/**\n *\n * BIP-44 HD key derivation for Solana accounts.\n *\n * Derivation path: m/44'/501'/index'/0'\n * 44' = BIP-44 purpose\n * 501' = Solana's registered coin type (SLIP-44)\n * n' = account index (0 = first account, 1 = second, etc.)\n * 0' = change (always 0 for Solana)\n *\n * This is the exact path Phantom, Backpack, and Solflare use.\n * Same seed → same addresses as those wallets.\n *\n * Dependencies: ed25519-hd-key, tweetnacl, bs58\n */\n\nimport { derivePath } from \"ed25519-hd-key\";\nimport nacl from \"tweetnacl\";\nimport bs58 from \"bs58\";\nimport { mnemonicToSeed } from \"./mnemonic\";\n\n// ── Types ─────────────────────────────────────────────────────────────────────\n\nexport interface Account {\n index: number; // derivation index\n name: string; // user-defined label\n publicKey: string; // Base58 encoded — this is the Solana address\n derivationPath: string; // m/44'/501'/index'/0'\n createdAt: string;\n}\n\n/**\n * In-memory keypair — private key NEVER persisted to disk.\n * Lives only for the duration of the daemon session.\n */\nexport interface AccountKeypair extends Account {\n secretKey: Uint8Array; // 64-byte Ed25519 secret key (seed + public key)\n}\n\nexport interface AccountStore {\n accounts: Account[];\n activeIndex: number;\n}\n\n// ── Derivation ────────────────────────────────────────────────────────────────\n\n/**\n * Derive an Ed25519 keypair at a specific BIP-44 index.\n * This is the core operation — called once per session after vault unlock.\n *\n * @param seed - 64-byte seed from BIP-39 mnemonic\n * @param index - account index (0-based)\n * @param name - label for this account\n */\nexport function deriveAccount(\n seed: Buffer,\n index: number,\n name: string = `Account ${index + 1}`,\n): AccountKeypair {\n const path = derivationPath(index);\n\n // SLIP-0010 Ed25519 derivation\n const { key: privateKeyBytes } = derivePath(path, seed.toString(\"hex\"));\n\n // nacl keypair from 32-byte seed\n const keypair = nacl.sign.keyPair.fromSeed(privateKeyBytes);\n\n const publicKey = bs58.encode(Buffer.from(keypair.publicKey));\n\n return {\n index,\n name,\n publicKey,\n secretKey: keypair.secretKey, // 64 bytes: seed + public key\n derivationPath: path,\n createdAt: new Date().toISOString(),\n };\n}\n\n/**\n * Derive multiple accounts at once.\n * Used on wallet startup to load all known accounts into memory.\n */\nexport function deriveAccounts(\n seed: Buffer,\n accountStore: AccountStore,\n): AccountKeypair[] {\n return accountStore.accounts.map((account) =>\n deriveAccount(seed, account.index, account.name),\n );\n}\n\n/**\n * Derive a single account directly from mnemonic.\n * Convenience wrapper used in tests and programmatic access.\n */\nexport async function deriveAccountFromMnemonic(\n mnemonic: string,\n index: number,\n name?: string,\n passphrase?: string,\n): Promise<AccountKeypair> {\n const seed = await mnemonicToSeed(mnemonic, passphrase);\n return deriveAccount(seed, index, name);\n}\n\n// ── Account Store ─────────────────────────────────────────────────────────────\n\n/**\n * Create a fresh account store with the first account.\n */\nexport function createAccountStore(\n firstAccountName: string = \"Account 1\",\n): AccountStore {\n return {\n accounts: [\n {\n index: 0,\n name: firstAccountName,\n publicKey: \"\", // filled in after derivation\n derivationPath: derivationPath(0),\n createdAt: new Date().toISOString(),\n },\n ],\n activeIndex: 0,\n };\n}\n\n/**\n * Add a new account to the store.\n * The next index is always max(existing indices) + 1.\n */\nexport function addAccount(\n store: AccountStore,\n seed: Buffer,\n name?: string,\n): { store: AccountStore; keypair: AccountKeypair } {\n const nextIndex =\n store.accounts.length > 0\n ? Math.max(...store.accounts.map((a) => a.index)) + 1\n : 0;\n\n const accountName = name ?? `Account ${nextIndex + 1}`;\n const keypair = deriveAccount(seed, nextIndex, accountName);\n\n const newAccount: Account = {\n index: nextIndex,\n name: accountName,\n publicKey: keypair.publicKey,\n derivationPath: keypair.derivationPath,\n createdAt: keypair.createdAt,\n };\n\n const updatedStore: AccountStore = {\n ...store,\n accounts: [...store.accounts, newAccount],\n };\n\n return { store: updatedStore, keypair };\n}\n\n/**\n * Set the active account by index.\n * The active account is used for all dApp connections and signing.\n */\nexport function setActiveAccount(\n store: AccountStore,\n index: number,\n): AccountStore {\n const exists = store.accounts.find((a) => a.index === index);\n if (!exists) {\n throw new Error(`Account index ${index} does not exist.`);\n }\n return { ...store, activeIndex: index };\n}\n\n/**\n * Rename an account.\n */\nexport function renameAccount(\n store: AccountStore,\n index: number,\n newName: string,\n): AccountStore {\n return {\n ...store,\n accounts: store.accounts.map((a) =>\n a.index === index ? { ...a, name: newName } : a,\n ),\n };\n}\n\n/**\n * Get the active account metadata from the store.\n */\nexport function getActiveAccount(store: AccountStore): Account {\n const account = store.accounts.find((a) => a.index === store.activeIndex);\n if (!account) throw new Error(\"No active account found.\");\n return account;\n}\n\n// ── Utilities ─────────────────────────────────────────────────────────────────\n\n/**\n * Sign a raw message with an account's secret key.\n * Returns a Base58 encoded signature.\n */\nexport function signMessage(\n message: Uint8Array,\n secretKey: Uint8Array,\n): string {\n const signature = nacl.sign.detached(message, secretKey);\n return bs58.encode(Buffer.from(signature));\n}\n\n/**\n * Format account for display in terminal.\n */\nexport function formatAccount(account: Account, isActive: boolean): string {\n const activeMarker = isActive ? \"●\" : \"○\";\n const shortKey = `${account.publicKey.slice(0, 4)}...${account.publicKey.slice(-4)}`;\n return `${activeMarker} [${account.index}] ${account.name.padEnd(20)} ${shortKey}`;\n}\n\n// ── Internal ──────────────────────────────────────────────────────────────────\n\nfunction derivationPath(index: number): string {\n return `m/44'/501'/${index}'/0'`;\n}\n","/**\n *\n * BIP-39 mnemonic generation, validation, and seed derivation.\n * Supports 12-word (128-bit) and 24-word (256-bit) mnemonics.\n *\n * Dependencies: bip39\n */\n\nimport * as bip39 from \"bip39\";\n\nexport type MnemonicStrength = 12 | 24; // 128 = 12 words, 256 = 24 words\n\nexport interface MnemonicResult {\n mnemonic: string;\n wordCount: 12 | 24;\n}\n\n/**\n * Generate a new cryptographically random BIP-39 mnemonic.\n * @param strength 128 for 12-word, 256 for 24-word (default: 128)\n */\nexport function generateMnemonic(\n strength: MnemonicStrength = 12,\n): MnemonicResult {\n const mnemonic = bip39.generateMnemonic(strength == 12 ? 128 : 256);\n const wordCount = strength;\n return { mnemonic, wordCount };\n}\n\n/**\n * Validate a BIP-39 mnemonic phrase.\n * Checks both wordlist membership and BIP-39 checksum.\n */\nexport function validateMnemonic(mnemonic: string): boolean {\n const cleaned = cleanMnemonic(mnemonic);\n return bip39.validateMnemonic(cleaned);\n}\n\n/**\n * Derive a 64-byte seed buffer from a mnemonic.\n * Optional passphrase adds extra security per BIP-39 spec.\n * This seed is the root of ALL derived accounts.\n */\nexport async function mnemonicToSeed(\n mnemonic: string,\n passphrase: string = \"\",\n): Promise<Buffer> {\n const cleaned = cleanMnemonic(mnemonic);\n\n if (!validateMnemonic(cleaned)) {\n throw new Error(\"Invalid mnemonic: failed wordlist or checksum validation\");\n }\n\n return bip39.mnemonicToSeed(cleaned, passphrase);\n}\n\n/**\n * Split mnemonic into a numbered word array.\n * Used for backup verification display in the terminal UI.\n *\n * Example output:\n * [ \"1. witch\", \"2. collapse\", \"3. practice\", ... ]\n */\nexport function mnemonicToNumberedWords(mnemonic: string): string[] {\n return cleanMnemonic(mnemonic)\n .split(\" \")\n .map((word, i) => `${i + 1}. ${word}`);\n}\n\n/**\n * Reconstruct mnemonic from a word array.\n * Used when user inputs words one by one during restore flow.\n */\nexport function wordsToMnemonic(words: string[]): string {\n return words.map((w) => w.trim().toLowerCase()).join(\" \");\n}\n\n// ── Internal ──────────────────────────────────────────────────────────────────\n\nfunction cleanMnemonic(mnemonic: string): string {\n return mnemonic.trim().toLowerCase().replace(/\\s+/g, \" \");\n}\n"],"mappings":";;;AAYA,OAAOA,SAAQ;;;ACIf,OAAO,QAAQ;AACf,OAAO,QAAQ;AACf,OAAO,UAAU;AA8BV,SAAS,eAAuB;AAErC,SAAO,KAAK,KAAK,GAAG,QAAQ,GAAG,SAAS;AAC1C;AAMO,SAAS,gBAAwB;AACtC,SAAO,KAAK,KAAK,aAAa,GAAG,aAAa;AAChD;AAEO,SAAS,kBAA0B;AACxC,SAAO,KAAK,KAAK,aAAa,GAAG,eAAe;AAClD;AAEO,IAAM,gBAAgB,gBAAgB;AAEtC,SAAS,kBAAwB;AACtC,QAAM,MAAM,aAAa;AACzB,MAAI,CAAC,GAAG,WAAW,GAAG,GAAG;AACvB,OAAG,UAAU,KAAK,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAAA,EACpD;AACF;;;ACxDA,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AACjB,OAAO,UAAU;;;ACVjB,YAAY,WAAW;;;ADuGhB,SAAS,mBACd,mBAA2B,aACb;AACd,SAAO;AAAA,IACL,UAAU;AAAA,MACR;AAAA,QACE,OAAO;AAAA,QACP,MAAM;AAAA,QACN,WAAW;AAAA;AAAA,QACX,gBAAgB,eAAe,CAAC;AAAA,QAChC,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC;AAAA,IACF;AAAA,IACA,aAAa;AAAA,EACf;AACF;AAoGA,SAAS,eAAe,OAAuB;AAC7C,SAAO,cAAc,KAAK;AAC5B;;;AFpMA,IAAM,iBAAiB,QAAQ,IAAI;AAC5B,IAAM,WAA2D;AAAA,EACtE,gBAAgB,iBACZ,2CAA2C,cAAc,KACzD;AAAA,EACJ,QAAQ,iBACJ,0CAA0C,cAAc,KACxD;AAAA,EACJ,SAAS;AAAA,EACT,UAAU;AACZ;AAEA,IAAM,iBAAiB;AAIhB,SAAS,eAAwB;AACtC,SAAOC,IAAG,WAAW,cAAc,CAAC;AACtC;AAEO,SAAS,aAA2B;AACzC,MAAI,CAAC,aAAa,GAAG;AACnB,UAAM,IAAI,MAAM,2CAA2C;AAAA,EAC7D;AACA,QAAM,MAAMA,IAAG,aAAa,cAAc,GAAG,MAAM;AACnD,SAAO,KAAK,MAAM,GAAG;AACvB;AAEO,SAAS,WAAW,QAA4B;AACrD,kBAAgB;AAChB,QAAM,UAAU,EAAE,GAAG,QAAQ,YAAW,oBAAI,KAAK,GAAE,YAAY,EAAE;AACjE,EAAAA,IAAG,cAAc,cAAc,GAAG,KAAK,UAAU,SAAS,MAAM,CAAC,GAAG;AAAA,IAClE,MAAM;AAAA,EACR,CAAC;AACH;AAKO,SAAS,aACd,yBAAiC,IACjC,UAA0C,UAC5B;AACd,QAAM,OAAM,oBAAI,KAAK,GAAE,YAAY;AACnC,SAAO;AAAA,IACL,SAAS;AAAA,IACT;AAAA,IACA,QAAQ,SAAS,OAAO;AAAA,IACxB;AAAA,IACA,cAAc,mBAAmB,WAAW;AAAA,IAC5C,WAAW;AAAA,IACX,WAAW;AAAA,EACb;AACF;AAIO,SAAS,cAAc,SAA+C;AAC3E,QAAM,SAAS,WAAW;AAC1B,SAAO,UAAU;AACjB,SAAO,SAAS,SAAS,OAAO;AAChC,aAAW,MAAM;AACnB;AAEO,SAAS,aAAa,KAAmB;AAC9C,QAAM,SAAS,WAAW;AAC1B,SAAO,SAAS;AAChB,aAAW,MAAM;AACnB;AAEO,SAAS,mBAAmB,cAAkC;AACnE,QAAM,SAAS,WAAW;AAC1B,SAAO,eAAe;AACtB,aAAW,MAAM;AACnB;AAEO,SAAS,YAAoB;AAClC,SAAO,WAAW,EAAE;AACtB;AAEO,SAAS,aAA0B;AACxC,SAAO,WAAW,EAAE;AACtB;AAEO,SAAS,kBAAgC;AAC9C,SAAO,WAAW,EAAE;AACtB;","names":["fs","fs"]}
@@ -0,0 +1,122 @@
1
+ import { AccountKeypair } from './accounts.js';
2
+ export { Account, AccountStore, addAccount, createAccountStore, deriveAccount, deriveAccountFromMnemonic, deriveAccounts, formatAccount, getActiveAccount, renameAccount, setActiveAccount, signMessage } from './accounts.js';
3
+ import { ClusterType, WalletConfig } from './config.js';
4
+ export { RPC_URLS, configExists, createConfig, getAccountStore, getCluster, getRpcUrl, loadConfig, saveConfig, updateAccountStore, updateCluster, updateRpcUrl } from './config.js';
5
+ export { MnemonicResult, MnemonicStrength, generateMnemonic, mnemonicToNumberedWords, mnemonicToSeed, validateMnemonic, wordsToMnemonic } from './mnemonic.js';
6
+ export { SESSIONS_FILE, VaultData, changePassword, ensureWalletDir, getConfigPath, getSessionsPath, getVaultPath, getWalletDir, loadVault, saveVault, vaultExists } from './keystore.js';
7
+
8
+ /**
9
+ *
10
+ * Public API for the vault module.
11
+ * All other modules import from here — not directly from sub-files.
12
+ *
13
+ * Usage:
14
+ * import { WalletVault } from "../vault"
15
+ *
16
+ * const vault = new WalletVault()
17
+ * await vault.init("my password")
18
+ * const account = vault.getActiveKeypair()
19
+ */
20
+
21
+ /**
22
+ * WalletVault is the in-memory session state of the wallet.
23
+ * It is populated on `unlock()` and holds derived keypairs
24
+ * for the duration of the daemon session.
25
+ *
26
+ * Private keys exist ONLY in this object — never on disk.
27
+ */
28
+ declare class WalletVault {
29
+ private _keypairs;
30
+ private _seed;
31
+ private _config;
32
+ private _unlocked;
33
+ private _mnemonic;
34
+ /**
35
+ * Initialize a brand new wallet.
36
+ * Generates a mnemonic, encrypts it, writes config.
37
+ * Returns the mnemonic for the user to write down — shown ONCE.
38
+ */
39
+ init(password: string, options?: {
40
+ strength?: 12 | 24;
41
+ cluster?: Exclude<ClusterType, "custom">;
42
+ walletConnectProjectId?: string;
43
+ firstAccountName?: string;
44
+ }): Promise<string>;
45
+ /**
46
+ * Unlock the wallet for a session.
47
+ * Decrypts the vault, derives all account keypairs into memory.
48
+ */
49
+ unlock(password: string): Promise<void>;
50
+ /**
51
+ * Restore wallet from an existing mnemonic (import flow).
52
+ */
53
+ restore(mnemonic: string, password: string, options?: {
54
+ cluster?: Exclude<ClusterType, "custom">;
55
+ }): Promise<void>;
56
+ lock(): void;
57
+ /**
58
+ * Get the currently active keypair (used for signing + dApp connections).
59
+ */
60
+ getActiveKeypair(): AccountKeypair;
61
+ /**
62
+ * Lock the wallet — wipe all keypairs from memory.
63
+ */
64
+ /**
65
+ * Returns the mnemonic — only available while unlocked.
66
+ * Used by agent_connect to derive new accounts on demand.
67
+ */
68
+ getMnemonic(): string;
69
+ /**
70
+ * Reload config and re-derive keypairs from seed.
71
+ * Call after adding new accounts so the vault picks them up.
72
+ */
73
+ reload(): Promise<void>;
74
+ /**
75
+ * Get a keypair by account index.
76
+ */
77
+ getKeypair(index: number): AccountKeypair;
78
+ /**
79
+ * Get all loaded keypairs.
80
+ */
81
+ getAllKeypairs(): AccountKeypair[];
82
+ /**
83
+ * Add a new derived account.
84
+ */
85
+ addAccount(name?: string, password?: string): Promise<AccountKeypair>;
86
+ /**
87
+ * Switch the active account.
88
+ */
89
+ setActiveAccount(index: number): void;
90
+ /**
91
+ * Rename an account.
92
+ */
93
+ renameAccount(index: number, newName: string): void;
94
+ /**
95
+ * Format all accounts for terminal display.
96
+ */
97
+ listAccounts(): string[];
98
+ /**
99
+ * Sign a message with the active account.
100
+ */
101
+ signMessage(message: Uint8Array): string;
102
+ get isUnlocked(): boolean;
103
+ get config(): WalletConfig;
104
+ static exists(): boolean;
105
+ /**
106
+ * Display mnemonic as numbered words — for backup verification flow.
107
+ */
108
+ static formatMnemonicForDisplay(mnemonic: string): string;
109
+ private assertUnlocked;
110
+ /**
111
+ * Find an account by name or create it if it doesn't exist.
112
+ * Uses the cached seed — no password needed.
113
+ * This is the primary way agents acquire their account.
114
+ */
115
+ findOrCreate(name: string): Promise<AccountKeypair>;
116
+ /**
117
+ * Find an account by name. Returns null if not found.
118
+ */
119
+ findByName(name: string): AccountKeypair | null;
120
+ }
121
+
122
+ export { AccountKeypair, ClusterType, WalletConfig, WalletVault };