@toon-protocol/client 0.29.7 → 2.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.
@@ -0,0 +1,166 @@
1
+ import {
2
+ generateMnemonic,
3
+ validateMnemonic
4
+ } from "./chunk-J6JVCKNV.js";
5
+
6
+ // src/keys/keystore-node.ts
7
+ import {
8
+ scryptSync,
9
+ createCipheriv,
10
+ createDecipheriv,
11
+ randomBytes
12
+ } from "crypto";
13
+ import { writeFileSync, readFileSync } from "fs";
14
+ var SCRYPT_N = 2 ** 17;
15
+ var SCRYPT_R = 8;
16
+ var SCRYPT_P = 1;
17
+ var SCRYPT_KEY_LEN = 32;
18
+ var SCRYPT_MAXMEM = SCRYPT_N * SCRYPT_R * 256 + 32 * 1024 * 1024;
19
+ var SALT_LEN = 32;
20
+ var IV_LEN = 12;
21
+ var AUTH_TAG_LEN = 16;
22
+ var KEYSTORE_VERSION = 2;
23
+ function keystoreDerivation(keystore) {
24
+ const version = keystore.version ?? 1;
25
+ if (version < KEYSTORE_VERSION) return "legacy";
26
+ return keystore.derivation ?? "standard";
27
+ }
28
+ function assertNode() {
29
+ const versions = globalThis.process?.versions;
30
+ if (!versions?.node) {
31
+ throw new Error(
32
+ "keystore-node is Node.js-only and cannot run in a browser. Use the Passkey/IndexedDB KeyManager for browser key storage."
33
+ );
34
+ }
35
+ }
36
+ function encryptMnemonic(mnemonic, password, options = {}) {
37
+ assertNode();
38
+ if (typeof mnemonic !== "string" || mnemonic.length === 0) {
39
+ throw new Error("encryptMnemonic: mnemonic must be a non-empty string");
40
+ }
41
+ if (typeof password !== "string" || password.length === 0) {
42
+ throw new Error("encryptMnemonic: password must be a non-empty string");
43
+ }
44
+ const salt = randomBytes(SALT_LEN);
45
+ const iv = randomBytes(IV_LEN);
46
+ const key = scryptSync(password, salt, SCRYPT_KEY_LEN, {
47
+ N: SCRYPT_N,
48
+ r: SCRYPT_R,
49
+ p: SCRYPT_P,
50
+ maxmem: SCRYPT_MAXMEM
51
+ });
52
+ try {
53
+ const cipher = createCipheriv("aes-256-gcm", key, iv, {
54
+ authTagLength: AUTH_TAG_LEN
55
+ });
56
+ const ciphertext = Buffer.concat([
57
+ cipher.update(mnemonic, "utf8"),
58
+ cipher.final()
59
+ ]);
60
+ const tag = cipher.getAuthTag();
61
+ return {
62
+ salt: salt.toString("base64"),
63
+ iv: iv.toString("base64"),
64
+ ciphertext: ciphertext.toString("base64"),
65
+ tag: tag.toString("base64"),
66
+ version: KEYSTORE_VERSION,
67
+ derivation: options.derivation ?? "standard"
68
+ };
69
+ } finally {
70
+ key.fill(0);
71
+ }
72
+ }
73
+ function decryptMnemonic(encrypted, password) {
74
+ assertNode();
75
+ if (typeof password !== "string" || password.length === 0) {
76
+ throw new Error("decryptMnemonic: password must be a non-empty string");
77
+ }
78
+ if (!encrypted || typeof encrypted.salt !== "string" || typeof encrypted.iv !== "string" || typeof encrypted.ciphertext !== "string" || typeof encrypted.tag !== "string") {
79
+ throw new Error("decryptMnemonic: malformed keystore envelope");
80
+ }
81
+ const salt = Buffer.from(encrypted.salt, "base64");
82
+ const iv = Buffer.from(encrypted.iv, "base64");
83
+ const ciphertext = Buffer.from(encrypted.ciphertext, "base64");
84
+ const tag = Buffer.from(encrypted.tag, "base64");
85
+ const key = scryptSync(password, salt, SCRYPT_KEY_LEN, {
86
+ N: SCRYPT_N,
87
+ r: SCRYPT_R,
88
+ p: SCRYPT_P,
89
+ maxmem: SCRYPT_MAXMEM
90
+ });
91
+ try {
92
+ const decipher = createDecipheriv("aes-256-gcm", key, iv, {
93
+ authTagLength: AUTH_TAG_LEN
94
+ });
95
+ decipher.setAuthTag(tag);
96
+ try {
97
+ const plaintext = Buffer.concat([
98
+ decipher.update(ciphertext),
99
+ decipher.final()
100
+ ]);
101
+ return plaintext.toString("utf8");
102
+ } catch {
103
+ throw new Error(
104
+ "Decryption failed: wrong password or corrupted keystore file"
105
+ );
106
+ }
107
+ } finally {
108
+ key.fill(0);
109
+ }
110
+ }
111
+ function generateKeystore(path, password, options = {}) {
112
+ assertNode();
113
+ const mnemonic = generateMnemonic();
114
+ const keystore = encryptMnemonic(mnemonic, password, options);
115
+ writeKeystoreFile(path, keystore);
116
+ return { mnemonic, keystore };
117
+ }
118
+ function importKeystore(path, mnemonic, password, options = {}) {
119
+ assertNode();
120
+ if (!validateMnemonic(mnemonic)) {
121
+ throw new Error(
122
+ "Invalid BIP-39 mnemonic: checksum or word-list validation failed"
123
+ );
124
+ }
125
+ const keystore = encryptMnemonic(mnemonic, password, options);
126
+ writeKeystoreFile(path, keystore);
127
+ return keystore;
128
+ }
129
+ function openKeystore(path, password) {
130
+ assertNode();
131
+ const raw = readFileSync(path, "utf8");
132
+ let parsed;
133
+ try {
134
+ parsed = JSON.parse(raw);
135
+ } catch {
136
+ throw new Error(`Keystore file at ${path} is not valid JSON`);
137
+ }
138
+ return {
139
+ mnemonic: decryptMnemonic(parsed, password),
140
+ derivation: keystoreDerivation(parsed),
141
+ version: parsed.version ?? 1
142
+ };
143
+ }
144
+ function loadKeystore(path, password) {
145
+ return openKeystore(path, password).mnemonic;
146
+ }
147
+ function writeKeystoreFile(path, keystore) {
148
+ assertNode();
149
+ writeFileSync(path, JSON.stringify(keystore, null, 2), {
150
+ encoding: "utf8",
151
+ mode: 384
152
+ });
153
+ }
154
+
155
+ export {
156
+ KEYSTORE_VERSION,
157
+ keystoreDerivation,
158
+ encryptMnemonic,
159
+ decryptMnemonic,
160
+ generateKeystore,
161
+ importKeystore,
162
+ openKeystore,
163
+ loadKeystore,
164
+ writeKeystoreFile
165
+ };
166
+ //# sourceMappingURL=chunk-DD7TJKP6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/keys/keystore-node.ts"],"sourcesContent":["/**\n * Node-only encrypted mnemonic keystore.\n *\n * A BIP-39 mnemonic is encrypted at rest with scrypt (KDF) + AES-256-GCM\n * (authenticated encryption), serialized as JSON, and written to disk with mode\n * `0o600`. Decryption needs the password; a wrong one fails the GCM auth-tag\n * check and throws. None of that crypto has changed, and none of it is going to\n * change quietly — the file format carries a version so that it does not have\n * to.\n *\n * ## Versions, and why a v1 file is read as `legacy`\n *\n * A keystore records **which derivation its mnemonic is meant to be read\n * under**, because a phrase alone does not say. Before 1.0 this client derived\n * its EVM key on coin type 1237 — one secp256k1 key served two roles — and a\n * keystore from that era says nothing about it. From 1.0 the EVM key is derived\n * at the BIP-44 standard `m/44'/60'/0'/0/i`, which is a different address from\n * the same phrase.\n *\n * So the migration rule, which is the whole point of the version field:\n *\n * - **A keystore with no `version`, or `version: 1`, is read as `legacy`.**\n * Every keystore written before 1.0 is one of those two, and every one of them\n * may hold a payment channel with real collateral locked at the address that\n * derivation produces. Reading it as `standard` would silently hand the caller\n * a different address, an empty wallet and no channel, while the funded one\n * sat there unreachable. Upgrading this package moves nothing.\n * - **A keystore written now is `version: 2` and records its derivation\n * explicitly** — `standard` unless the caller asked for `legacy` (importing a\n * phrase whose channels were opened under the old path).\n *\n * Nothing rewrites a v1 file in place. It keeps working as it is, and a caller\n * that wants to move to the standard path does so deliberately: import the same\n * phrase into a new keystore, and open a new channel at the new address.\n *\n * Node-only, and loudly so: `scryptSync` and POSIX file modes have no browser\n * equivalent, so every entry point throws rather than being bundled broken.\n *\n * @module\n */\n\nimport {\n scryptSync,\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} from 'node:crypto';\nimport { writeFileSync, readFileSync } from 'node:fs';\nimport {\n generateMnemonic as genMnemonic,\n validateMnemonic as isValidMnemonic,\n type KeyDerivationScheme,\n} from './KeyDerivation.js';\n\n/** scrypt parameters — N=2^17 (~0.5-1s on modern hardware), r=8, p=1. */\nconst SCRYPT_N = 2 ** 17;\nconst SCRYPT_R = 8;\nconst SCRYPT_P = 1;\nconst SCRYPT_KEY_LEN = 32;\n/** maxmem for scrypt: N * r * 128 * 2 (with headroom for Node.js overhead). */\nconst SCRYPT_MAXMEM = SCRYPT_N * SCRYPT_R * 256 + 32 * 1024 * 1024;\n\n/** Salt length in bytes. */\nconst SALT_LEN = 32;\n/** AES-GCM IV length in bytes. */\nconst IV_LEN = 12;\n/** AES-GCM authentication tag length in bytes (128-bit). */\nconst AUTH_TAG_LEN = 16;\n\n/** The version this package writes. See this module's own docs. */\nexport const KEYSTORE_VERSION = 2;\n\n/**\n * Encrypted keystore file format (JSON, all binary fields base64-encoded).\n *\n * `version` and `derivation` are both optional on the *type* because a file on\n * disk may predate them; anything this package writes sets both.\n */\nexport interface EncryptedKeystore {\n /** scrypt salt (base64). */\n salt: string;\n /** AES-GCM initialization vector (base64). */\n iv: string;\n /** AES-256-GCM ciphertext (base64). */\n ciphertext: string;\n /** AES-GCM authentication tag (base64). */\n tag: string;\n /** File-format version. Absent or `1` means a pre-1.0 file: read as `legacy`. */\n version?: number;\n /** Which derivation this mnemonic's keys are meant to be read under. */\n derivation?: KeyDerivationScheme;\n}\n\n/** A decrypted keystore: the phrase, and how to read it. */\nexport interface OpenedKeystore {\n mnemonic: string;\n /** `legacy` for any pre-1.0 file. See this module's own docs. */\n derivation: KeyDerivationScheme;\n /** The file's own version. `1` when the file recorded none. */\n version: number;\n}\n\n/** Options for writing a keystore. */\nexport interface WriteKeystoreOptions {\n /** Which derivation to record. Default `'standard'`. */\n derivation?: KeyDerivationScheme;\n}\n\n/**\n * Which derivation a keystore's mnemonic is to be read under.\n *\n * A file with no `version`, or `version: 1`, predates 1.0 and is `legacy` — its\n * addresses, and the channels funded at them, must not move. From `version: 2`\n * the file says so itself, defaulting to `standard` if the field is missing.\n */\nexport function keystoreDerivation(\n keystore: EncryptedKeystore\n): KeyDerivationScheme {\n const version = keystore.version ?? 1;\n if (version < KEYSTORE_VERSION) return 'legacy';\n return keystore.derivation ?? 'standard';\n}\n\n/**\n * Throws if this module is running outside Node.js. The scrypt/AES-256-GCM\n * primitives and the 0o600 file write are Node-only — there is no browser\n * equivalent of `node:crypto`'s `scryptSync` or POSIX file modes, so we fail\n * loudly rather than silently bundling broken code into a browser build.\n */\nfunction assertNode(): void {\n // `process.versions.node` is present in Node and absent in browsers.\n const versions = (\n globalThis as { process?: { versions?: { node?: string } } }\n ).process?.versions;\n if (!versions?.node) {\n throw new Error(\n 'keystore-node is Node.js-only and cannot run in a browser. ' +\n 'Use the Passkey/IndexedDB KeyManager for browser key storage.'\n );\n }\n}\n\n/**\n * Encrypt a mnemonic with a password using scrypt + AES-256-GCM.\n * Returns the JSON-serializable encrypted envelope (does NOT write to disk),\n * stamped `version: 2` and carrying the derivation its keys are read under.\n */\nexport function encryptMnemonic(\n mnemonic: string,\n password: string,\n options: WriteKeystoreOptions = {}\n): EncryptedKeystore {\n assertNode();\n if (typeof mnemonic !== 'string' || mnemonic.length === 0) {\n throw new Error('encryptMnemonic: mnemonic must be a non-empty string');\n }\n if (typeof password !== 'string' || password.length === 0) {\n throw new Error('encryptMnemonic: password must be a non-empty string');\n }\n\n const salt = randomBytes(SALT_LEN);\n const iv = randomBytes(IV_LEN);\n const key = scryptSync(password, salt, SCRYPT_KEY_LEN, {\n N: SCRYPT_N,\n r: SCRYPT_R,\n p: SCRYPT_P,\n maxmem: SCRYPT_MAXMEM,\n });\n\n try {\n const cipher = createCipheriv('aes-256-gcm', key, iv, {\n authTagLength: AUTH_TAG_LEN,\n });\n const ciphertext = Buffer.concat([\n cipher.update(mnemonic, 'utf8'),\n cipher.final(),\n ]);\n const tag = cipher.getAuthTag();\n\n return {\n salt: salt.toString('base64'),\n iv: iv.toString('base64'),\n ciphertext: ciphertext.toString('base64'),\n tag: tag.toString('base64'),\n version: KEYSTORE_VERSION,\n derivation: options.derivation ?? 'standard',\n };\n } finally {\n key.fill(0);\n }\n}\n\n/**\n * Decrypt an encrypted keystore envelope with a password.\n * Throws on a wrong password (GCM auth-tag verification failure) or corruption.\n */\nexport function decryptMnemonic(\n encrypted: EncryptedKeystore,\n password: string\n): string {\n assertNode();\n if (typeof password !== 'string' || password.length === 0) {\n throw new Error('decryptMnemonic: password must be a non-empty string');\n }\n if (\n !encrypted ||\n typeof encrypted.salt !== 'string' ||\n typeof encrypted.iv !== 'string' ||\n typeof encrypted.ciphertext !== 'string' ||\n typeof encrypted.tag !== 'string'\n ) {\n throw new Error('decryptMnemonic: malformed keystore envelope');\n }\n\n const salt = Buffer.from(encrypted.salt, 'base64');\n const iv = Buffer.from(encrypted.iv, 'base64');\n const ciphertext = Buffer.from(encrypted.ciphertext, 'base64');\n const tag = Buffer.from(encrypted.tag, 'base64');\n\n const key = scryptSync(password, salt, SCRYPT_KEY_LEN, {\n N: SCRYPT_N,\n r: SCRYPT_R,\n p: SCRYPT_P,\n maxmem: SCRYPT_MAXMEM,\n });\n\n try {\n const decipher = createDecipheriv('aes-256-gcm', key, iv, {\n authTagLength: AUTH_TAG_LEN,\n });\n decipher.setAuthTag(tag);\n try {\n const plaintext = Buffer.concat([\n decipher.update(ciphertext),\n decipher.final(),\n ]);\n return plaintext.toString('utf8');\n } catch {\n throw new Error(\n 'Decryption failed: wrong password or corrupted keystore file'\n );\n }\n } finally {\n key.fill(0);\n }\n}\n\n/**\n * Generate a fresh 12-word BIP-39 mnemonic, encrypt it under `password`, and\n * write the encrypted keystore to `path` with mode 0o600.\n *\n * Returns the mnemonic (for one-time display/backup) alongside the encrypted\n * envelope. The caller is responsible for displaying the mnemonic securely and\n * NOT persisting it in plaintext.\n */\nexport function generateKeystore(\n path: string,\n password: string,\n options: WriteKeystoreOptions = {}\n): { mnemonic: string; keystore: EncryptedKeystore } {\n assertNode();\n const mnemonic = genMnemonic();\n const keystore = encryptMnemonic(mnemonic, password, options);\n writeKeystoreFile(path, keystore);\n return { mnemonic, keystore };\n}\n\n/**\n * Import an existing BIP-39 mnemonic (12 or 24 words), encrypt it under\n * `password`, and write the encrypted keystore to `path` with mode 0o600.\n *\n * Throws if the mnemonic is not a valid BIP-39 phrase (wrong checksum/word\n * count) before any file is written.\n */\nexport function importKeystore(\n path: string,\n mnemonic: string,\n password: string,\n options: WriteKeystoreOptions = {}\n): EncryptedKeystore {\n assertNode();\n if (!isValidMnemonic(mnemonic)) {\n throw new Error(\n 'Invalid BIP-39 mnemonic: checksum or word-list validation failed'\n );\n }\n const keystore = encryptMnemonic(mnemonic, password, options);\n writeKeystoreFile(path, keystore);\n return keystore;\n}\n\n/**\n * Read a keystore file at `path`, decrypt it with `password`, and report both\n * the phrase and the derivation it is to be read under. Throws on a wrong\n * password or corruption.\n *\n * Prefer this over {@link loadKeystore}: a mnemonic on its own does not say\n * which addresses it means, and a pre-1.0 file means the `legacy` ones.\n */\nexport function openKeystore(path: string, password: string): OpenedKeystore {\n assertNode();\n const raw = readFileSync(path, 'utf8');\n let parsed: EncryptedKeystore;\n try {\n parsed = JSON.parse(raw) as EncryptedKeystore;\n } catch {\n throw new Error(`Keystore file at ${path} is not valid JSON`);\n }\n return {\n mnemonic: decryptMnemonic(parsed, password),\n derivation: keystoreDerivation(parsed),\n version: parsed.version ?? 1,\n };\n}\n\n/**\n * Load and decrypt a keystore file at `path` with `password`, returning the\n * plaintext mnemonic alone. Throws on a wrong password or corruption.\n *\n * The phrase without its derivation is only half the answer — see\n * {@link openKeystore}.\n */\nexport function loadKeystore(path: string, password: string): string {\n return openKeystore(path, password).mnemonic;\n}\n\n/**\n * Serialize and write an encrypted keystore to disk with mode 0o600\n * (owner read/write only), mirroring the relay node wallet file permissions.\n */\nexport function writeKeystoreFile(\n path: string,\n keystore: EncryptedKeystore\n): void {\n assertNode();\n writeFileSync(path, JSON.stringify(keystore, null, 2), {\n encoding: 'utf8',\n mode: 0o600,\n });\n}\n"],"mappings":";;;;;;AAyCA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe,oBAAoB;AAQ5C,IAAM,WAAW,KAAK;AACtB,IAAM,WAAW;AACjB,IAAM,WAAW;AACjB,IAAM,iBAAiB;AAEvB,IAAM,gBAAgB,WAAW,WAAW,MAAM,KAAK,OAAO;AAG9D,IAAM,WAAW;AAEjB,IAAM,SAAS;AAEf,IAAM,eAAe;AAG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nB,aAAW;AACX,MAAI,CAAC,iBAAgB,QAAQ,GAAG;AAC9B,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,QAAM,WAAW,gBAAgB,UAAU,UAAU,OAAO;AAC5D,oBAAkB,MAAM,QAAQ;AAChC,SAAO;AACT;AAUO,SAAS,aAAa,MAAc,UAAkC;AAC3E,aAAW;AACX,QAAM,MAAM,aAAa,MAAM,MAAM;AACrC,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,GAAG;AAAA,EACzB,QAAQ;AACN,UAAM,IAAI,MAAM,oBAAoB,IAAI,oBAAoB;AAAA,EAC9D;AACA,SAAO;AAAA,IACL,UAAU,gBAAgB,QAAQ,QAAQ;AAAA,IAC1C,YAAY,mBAAmB,MAAM;AAAA,IACrC,SAAS,OAAO,WAAW;AAAA,EAC7B;AACF;AASO,SAAS,aAAa,MAAc,UAA0B;AACnE,SAAO,aAAa,MAAM,QAAQ,EAAE;AACtC;AAMO,SAAS,kBACd,MACA,UACM;AACN,aAAW;AACX,gBAAc,MAAM,KAAK,UAAU,UAAU,MAAM,CAAC,GAAG;AAAA,IACrD,UAAU;AAAA,IACV,MAAM;AAAA,EACR,CAAC;AACH;","names":[]}
@@ -0,0 +1,201 @@
1
+ // src/keys/KeyDerivation.ts
2
+ import { privateKeyToAccount } from "viem/accounts";
3
+ import { toHex } from "viem";
4
+ import {
5
+ generateMnemonic as _genMnemonic,
6
+ validateMnemonic as _validateMnemonic,
7
+ mnemonicToSeedSync
8
+ } from "@scure/bip39";
9
+ import { wordlist as english } from "@scure/bip39/wordlists/english";
10
+ import { HDKey } from "@scure/bip32";
11
+ import { hmac } from "@noble/hashes/hmac";
12
+ import { sha512 } from "@noble/hashes/sha512";
13
+ import { ed25519 } from "@noble/curves/ed25519.js";
14
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
15
+
16
+ // src/utils/base58.ts
17
+ import { base58 } from "@scure/base";
18
+ function base58Encode(bytes) {
19
+ return base58.encode(bytes);
20
+ }
21
+ function base58Decode(text) {
22
+ return base58.decode(text);
23
+ }
24
+
25
+ // src/keys/KeyDerivation.ts
26
+ var EVM_COIN_TYPE_STANDARD = 60;
27
+ var EVM_COIN_TYPE_LEGACY = 1237;
28
+ function generateMnemonic() {
29
+ return _genMnemonic(english, 128);
30
+ }
31
+ function validateMnemonic(mnemonic) {
32
+ return _validateMnemonic(mnemonic, english);
33
+ }
34
+ var MAX_BIP32_INDEX = 2147483647;
35
+ function assertValidAccountIndex(accountIndex) {
36
+ if (!Number.isInteger(accountIndex) || accountIndex < 0 || accountIndex > MAX_BIP32_INDEX) {
37
+ throw new Error(
38
+ `accountIndex must be an integer in [0, ${MAX_BIP32_INDEX}]; got ${String(accountIndex)}`
39
+ );
40
+ }
41
+ }
42
+ function evmDerivationPath(scheme, accountIndex = 0) {
43
+ const coinType = scheme === "legacy" ? EVM_COIN_TYPE_LEGACY : EVM_COIN_TYPE_STANDARD;
44
+ return `m/44'/${String(coinType)}'/0'/0/${String(accountIndex)}`;
45
+ }
46
+ function deriveEvmKey(seed, scheme, accountIndex) {
47
+ const child = HDKey.fromMasterSeed(seed).derive(
48
+ evmDerivationPath(scheme, accountIndex)
49
+ );
50
+ if (!child.privateKey) {
51
+ throw new Error("Failed to derive an EVM private key from the seed");
52
+ }
53
+ return evmIdentityFromKey(new Uint8Array(child.privateKey));
54
+ }
55
+ function evmIdentityFromKey(privateKey) {
56
+ const account = privateKeyToAccount(toHex(privateKey));
57
+ return { privateKey, address: account.address };
58
+ }
59
+ function deriveSolanaKey(seed, accountIndex) {
60
+ const encoder = new TextEncoder();
61
+ let I = hmac(sha512, encoder.encode("ed25519 seed"), seed);
62
+ let key = I.slice(0, 32);
63
+ let chainCode = I.slice(32);
64
+ const indices = [
65
+ 2147483692,
66
+ // 44'
67
+ 2147484149,
68
+ // 501'
69
+ 2147483648 + accountIndex >>> 0,
70
+ // {accountIndex}'
71
+ 2147483648
72
+ // 0'
73
+ ];
74
+ for (const index of indices) {
75
+ const data = new Uint8Array(37);
76
+ data[0] = 0;
77
+ data.set(key, 1);
78
+ data[33] = index >>> 24 & 255;
79
+ data[34] = index >>> 16 & 255;
80
+ data[35] = index >>> 8 & 255;
81
+ data[36] = index & 255;
82
+ I = hmac(sha512, chainCode, data);
83
+ key = I.slice(0, 32);
84
+ chainCode = I.slice(32);
85
+ }
86
+ const publicKeyBytes = ed25519.getPublicKey(key);
87
+ const keypair = new Uint8Array(64);
88
+ keypair.set(key, 0);
89
+ keypair.set(publicKeyBytes, 32);
90
+ return { secretKey: keypair, publicKey: base58Encode(publicKeyBytes) };
91
+ }
92
+ function deriveFullIdentity(mnemonic, options = {}) {
93
+ const opts = typeof options === "number" ? { accountIndex: options } : options;
94
+ const accountIndex = opts.accountIndex ?? 0;
95
+ const scheme = opts.scheme ?? "standard";
96
+ assertValidAccountIndex(accountIndex);
97
+ const seed = mnemonicToSeedSync(mnemonic);
98
+ try {
99
+ return {
100
+ evm: deriveEvmKey(seed, scheme, accountIndex),
101
+ solana: deriveSolanaKey(seed, accountIndex)
102
+ };
103
+ } finally {
104
+ seed.fill(0);
105
+ }
106
+ }
107
+ function generateRandomIdentity() {
108
+ const evmKey = secp256k1.utils.randomSecretKey();
109
+ const solanaSeed = ed25519.utils.randomSecretKey();
110
+ const solanaPublic = ed25519.getPublicKey(solanaSeed);
111
+ const keypair = new Uint8Array(64);
112
+ keypair.set(solanaSeed, 0);
113
+ keypair.set(solanaPublic, 32);
114
+ return {
115
+ evm: evmIdentityFromKey(evmKey),
116
+ solana: { secretKey: keypair, publicKey: base58Encode(solanaPublic) }
117
+ };
118
+ }
119
+
120
+ // src/presets.ts
121
+ var DEVNET = {
122
+ /**
123
+ * The store node: an Arweave-backed object store behind `g.toon.store`, and
124
+ * the one route here that METERS — 1000 base units (0.001 USDC) plus 10 per
125
+ * kibibyte of sealed payload, so no packet on it costs only `price`.
126
+ */
127
+ store: {
128
+ url: "https://proxy.ario.devnet.toonprotocol.dev",
129
+ route: "g.toon.store",
130
+ price: 1000n,
131
+ pricePerKib: 10n
132
+ },
133
+ /**
134
+ * The gas station behind `g.toon.gas`, priced flat at 1000 base units.
135
+ * Reachable directly, or through the relay at `g.toon.relay.gas`.
136
+ */
137
+ gas: {
138
+ url: "https://proxy.gas.devnet.toonprotocol.dev",
139
+ route: "g.toon.gas",
140
+ price: 1000n
141
+ },
142
+ /**
143
+ * The relay node behind `g.toon.relay`, priced at 1 base unit. Its route is
144
+ * pinned to **BTP**: an HTTP one-shot to it is refused with the same terms
145
+ * document an unpaid request gets, carrying `extra.requiredTransport`.
146
+ */
147
+ relay: {
148
+ url: "https://proxy.relay.devnet.toonprotocol.dev",
149
+ route: "g.toon.relay",
150
+ price: 1n,
151
+ requiredTransport: "btp"
152
+ },
153
+ /**
154
+ * The relay's ephemeral lane, priced at **zero** — the one route on the devnet
155
+ * that exercises the whole wire while holding no funds and no channel. Not
156
+ * carriage-pinned, unlike `g.toon.relay` beside it.
157
+ */
158
+ ephemeral: {
159
+ url: "https://proxy.relay.devnet.toonprotocol.dev",
160
+ route: "g.toon.relay.ephemeral",
161
+ price: 0n
162
+ },
163
+ /** Test funds. `POST /api/base-sepolia/request` and `/api/solana/usdc-request`. */
164
+ faucet: "https://faucet.devnet.toonprotocol.dev",
165
+ /** Base Sepolia. The registry is the stable address; the token network is resolved from it. */
166
+ evm: {
167
+ chainId: 84532,
168
+ rpcUrl: "https://sepolia.base.org",
169
+ tokenNetworkRegistry: "0x0c41D9D424d6B075A3cEa1068a694f7847a8CCa5",
170
+ tokenNetwork: "0xe9E05dfecfe165266C88d73e61D483612651952a",
171
+ /** Mock USDC, 6 decimals, ungated `mint()`. */
172
+ tokenAddress: "0x49beE1Bca5d15Fb0963117923403F9498119a9Ce",
173
+ decimals: 6
174
+ },
175
+ /** Solana devnet — the public cluster, not a local validator. */
176
+ solana: {
177
+ rpcUrl: "https://api.devnet.solana.com",
178
+ /** The deployed `payment-channel` program. Bound into every claim (ADR 0053). */
179
+ programId: "2aEVJ8koKD8LTZrLRSGtAtU7LBt4e7QjjCgf1kzQ7Rip",
180
+ /** Mock USDC SPL mint, 6 decimals. */
181
+ tokenAddress: "34eSxY7qxQ4GzyhDJ8GpUcTz1WWzruGbJbR8q6TtxfQU",
182
+ decimals: 6
183
+ }
184
+ };
185
+ function defaultRpcUrl(chain) {
186
+ return chain === "evm" ? DEVNET.evm.rpcUrl : DEVNET.solana.rpcUrl;
187
+ }
188
+
189
+ export {
190
+ base58Encode,
191
+ base58Decode,
192
+ generateMnemonic,
193
+ validateMnemonic,
194
+ evmDerivationPath,
195
+ evmIdentityFromKey,
196
+ deriveFullIdentity,
197
+ generateRandomIdentity,
198
+ DEVNET,
199
+ defaultRpcUrl
200
+ };
201
+ //# sourceMappingURL=chunk-J6JVCKNV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/keys/KeyDerivation.ts","../src/utils/base58.ts","../src/presets.ts"],"sourcesContent":["/**\n * One BIP-39 phrase → an EVM key and a Solana key.\n *\n * ## Which path an EVM key comes from\n *\n * There are two, and the difference is historical rather than cryptographic.\n *\n * - **`standard`** — `m/44'/60'/0'/0/{accountIndex}`, BIP-44's registered coin\n * type for Ethereum. This is what every wallet derives, so the same phrase\n * typed into MetaMask or a hardware wallet produces the same address: the\n * channel wallet can be inspected, topped up or swept without this package.\n * New keystores use it.\n *\n * - **`legacy`** — `m/44'/1237'/0'/0/{accountIndex}`, Nostr's coin type. Before\n * 1.0 this client derived one secp256k1 key and used it for both a Nostr\n * identity and an EVM account, so the EVM key sat on Nostr's path. The Nostr\n * half is gone, but the addresses are not: they hold channels with real\n * collateral. A keystore written before 1.0 records no scheme and is read as\n * `legacy`, so nothing moves under an existing deployment.\n *\n * Solana is unaffected — `m/44'/501'/{accountIndex}'/0'`, SLIP-0010, all\n * hardened, which is what Phantom and the Solana CLI derive.\n */\nimport { privateKeyToAccount } from 'viem/accounts';\nimport { toHex } from 'viem';\nimport {\n generateMnemonic as _genMnemonic,\n validateMnemonic as _validateMnemonic,\n mnemonicToSeedSync,\n} from '@scure/bip39';\nimport { wordlist as english } from '@scure/bip39/wordlists/english';\nimport { HDKey } from '@scure/bip32';\nimport { hmac } from '@noble/hashes/hmac';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { secp256k1 } from '@noble/curves/secp256k1.js';\nimport { base58Encode } from '../utils/base58.js';\nimport type { DerivedIdentity } from './types.js';\n\n/** How a mnemonic becomes an EVM key. See this module's own docs. */\nexport type KeyDerivationScheme = 'standard' | 'legacy';\n\n/** BIP-44 coin type 60: Ethereum, and every EVM chain by convention. */\nconst EVM_COIN_TYPE_STANDARD = 60;\n/** BIP-44 coin type 1237: Nostr. What this client used before 1.0. */\nconst EVM_COIN_TYPE_LEGACY = 1237;\n\n/** Generate a new 12-word BIP-39 mnemonic. */\nexport function generateMnemonic(): string {\n return _genMnemonic(english, 128);\n}\n\n/** Is this a well-formed BIP-39 phrase with a valid checksum? */\nexport function validateMnemonic(mnemonic: string): boolean {\n return _validateMnemonic(mnemonic, english);\n}\n\n/** Maximum valid BIP-32 non-hardened child index (2^31 − 1). */\nconst MAX_BIP32_INDEX = 0x7fffffff;\n\nfunction assertValidAccountIndex(accountIndex: number): void {\n if (\n !Number.isInteger(accountIndex) ||\n accountIndex < 0 ||\n accountIndex > MAX_BIP32_INDEX\n ) {\n throw new Error(\n `accountIndex must be an integer in [0, ${MAX_BIP32_INDEX}]; got ${String(accountIndex)}`\n );\n }\n}\n\n/** The BIP-44 path an EVM key is derived at, under a given scheme. */\nexport function evmDerivationPath(\n scheme: KeyDerivationScheme,\n accountIndex = 0\n): string {\n const coinType =\n scheme === 'legacy' ? EVM_COIN_TYPE_LEGACY : EVM_COIN_TYPE_STANDARD;\n return `m/44'/${String(coinType)}'/0'/0/${String(accountIndex)}`;\n}\n\nfunction deriveEvmKey(\n seed: Uint8Array,\n scheme: KeyDerivationScheme,\n accountIndex: number\n): DerivedIdentity['evm'] {\n const child = HDKey.fromMasterSeed(seed).derive(\n evmDerivationPath(scheme, accountIndex)\n );\n if (!child.privateKey) {\n throw new Error('Failed to derive an EVM private key from the seed');\n }\n return evmIdentityFromKey(new Uint8Array(child.privateKey));\n}\n\n/** The account an existing secp256k1 secret belongs to. */\nexport function evmIdentityFromKey(\n privateKey: Uint8Array\n): DerivedIdentity['evm'] {\n const account = privateKeyToAccount(toHex(privateKey));\n return { privateKey, address: account.address };\n}\n\n/**\n * SLIP-0010 Ed25519 derivation at `m/44'/501'/{accountIndex}'/0'`.\n *\n * Ed25519 has no non-hardened derivation, so every level is hardened and the\n * chain code is carried by hand rather than through `HDKey` (which implements\n * BIP-32 for secp256k1).\n */\nfunction deriveSolanaKey(\n seed: Uint8Array,\n accountIndex: number\n): DerivedIdentity['solana'] {\n const encoder = new TextEncoder();\n let I = hmac(sha512, encoder.encode('ed25519 seed'), seed);\n let key = I.slice(0, 32);\n let chainCode = I.slice(32);\n\n const indices = [\n 0x8000002c, // 44'\n 0x800001f5, // 501'\n (0x80000000 + accountIndex) >>> 0, // {accountIndex}'\n 0x80000000, // 0'\n ];\n\n for (const index of indices) {\n const data = new Uint8Array(37);\n data[0] = 0x00;\n data.set(key, 1);\n data[33] = (index >>> 24) & 0xff;\n data[34] = (index >>> 16) & 0xff;\n data[35] = (index >>> 8) & 0xff;\n data[36] = index & 0xff;\n\n I = hmac(sha512, chainCode, data);\n key = I.slice(0, 32);\n chainCode = I.slice(32);\n }\n\n const publicKeyBytes = ed25519.getPublicKey(key);\n // A Solana secret key is the 32-byte seed followed by its public key.\n const keypair = new Uint8Array(64);\n keypair.set(key, 0);\n keypair.set(publicKeyBytes, 32);\n\n return { secretKey: keypair, publicKey: base58Encode(publicKeyBytes) };\n}\n\nexport interface DeriveIdentityOptions {\n accountIndex?: number;\n /** Default `'standard'`. */\n scheme?: KeyDerivationScheme;\n}\n\n/**\n * Derive both chain keys from a mnemonic.\n *\n * The seed is zeroed before returning; the derived keys are not, because they\n * are the return value.\n */\nexport function deriveFullIdentity(\n mnemonic: string,\n options: DeriveIdentityOptions | number = {}\n): DerivedIdentity {\n // `deriveFullIdentity(mnemonic, 3)` used to mean account index 3.\n const opts: DeriveIdentityOptions =\n typeof options === 'number' ? { accountIndex: options } : options;\n const accountIndex = opts.accountIndex ?? 0;\n const scheme = opts.scheme ?? 'standard';\n assertValidAccountIndex(accountIndex);\n\n const seed = mnemonicToSeedSync(mnemonic);\n try {\n return {\n evm: deriveEvmKey(seed, scheme, accountIndex),\n solana: deriveSolanaKey(seed, accountIndex),\n };\n } finally {\n seed.fill(0);\n }\n}\n\n/**\n * A random identity, for tests and ephemeral use. The keys are unrelated to\n * each other and to any mnemonic, so nothing here can be recovered from a\n * phrase — generate a mnemonic instead if the keys need to outlive the process.\n */\nexport function generateRandomIdentity(): DerivedIdentity {\n const evmKey = secp256k1.utils.randomSecretKey();\n const solanaSeed = ed25519.utils.randomSecretKey();\n const solanaPublic = ed25519.getPublicKey(solanaSeed);\n const keypair = new Uint8Array(64);\n keypair.set(solanaSeed, 0);\n keypair.set(solanaPublic, 32);\n return {\n evm: evmIdentityFromKey(evmKey),\n solana: { secretKey: keypair, publicKey: base58Encode(solanaPublic) },\n };\n}\n","/**\n * Base58 (Bitcoin alphabet) — the encoding every Solana address, program id,\n * mint and signature-free pubkey arrives in.\n *\n * A thin wrapper over `@scure/base` rather than a hand-rolled implementation:\n * the same audited primitive already sits under `@scure/bip32`, so this adds no\n * install weight, and base58 decoding is exactly the kind of loop where a\n * hand-rolled version is wrong only for inputs you did not test.\n *\n * Replaces `@toon-protocol/core`'s `base58Encode`/`base58Decode`.\n */\nimport { base58 } from '@scure/base';\n\n/** Encode raw bytes as base58. */\nexport function base58Encode(bytes: Uint8Array): string {\n return base58.encode(bytes);\n}\n\n/**\n * Decode base58 text to raw bytes.\n *\n * Throws on any character outside the alphabet — a Solana pubkey that fails to\n * decode is a caller error worth surfacing, never something to coerce.\n */\nexport function base58Decode(text: string): Uint8Array {\n return base58.decode(text);\n}\n","/**\n * Well-known values for the public TOON devnet.\n *\n * **These are conveniences, never authorities.** Every settlement fact a client\n * actually pays against — the chain, the counterparty address, the token\n * network, the mint, the decimals — comes from the connector's own `GET /ilp`,\n * because the connector proved each of them against a live chain when it booted\n * (`self-description-spec.md` ND-07). Two declarations of one fact is how a\n * mainnet node comes to be described as devnet, so nothing here is ever\n * consulted in preference to the document a node answers with.\n *\n * What they are good for: a default RPC endpoint, a default faucet, and a URL to\n * put in an example so it can be run rather than adapted.\n *\n * Everything below is a **testnet**. Base Sepolia and Solana devnet carry no\n * real value, and the USDC is a mock mint anyone can draw from the faucet.\n */\n\n/** A connector on the public devnet. */\nexport interface DevnetNode {\n /** Client-edge base URL — `GET /ilp` here returns everything else. */\n url: string;\n /** The route this node terminates. */\n route: string;\n /** That route's base price, in base units of the settlement asset (USDC, 6dp). */\n price: bigint;\n /**\n * Added per kibibyte of sealed payload, on a route that meters by size. A\n * packet on such a route always costs strictly more than `price`.\n */\n pricePerKib?: bigint;\n /** Set when the route accepts only one carriage. */\n requiredTransport?: 'http' | 'btp';\n}\n\nexport const DEVNET = {\n /**\n * The store node: an Arweave-backed object store behind `g.toon.store`, and\n * the one route here that METERS — 1000 base units (0.001 USDC) plus 10 per\n * kibibyte of sealed payload, so no packet on it costs only `price`.\n */\n store: {\n url: 'https://proxy.ario.devnet.toonprotocol.dev',\n route: 'g.toon.store',\n price: 1000n,\n pricePerKib: 10n,\n } satisfies DevnetNode,\n\n /**\n * The gas station behind `g.toon.gas`, priced flat at 1000 base units.\n * Reachable directly, or through the relay at `g.toon.relay.gas`.\n */\n gas: {\n url: 'https://proxy.gas.devnet.toonprotocol.dev',\n route: 'g.toon.gas',\n price: 1000n,\n } satisfies DevnetNode,\n\n /**\n * The relay node behind `g.toon.relay`, priced at 1 base unit. Its route is\n * pinned to **BTP**: an HTTP one-shot to it is refused with the same terms\n * document an unpaid request gets, carrying `extra.requiredTransport`.\n */\n relay: {\n url: 'https://proxy.relay.devnet.toonprotocol.dev',\n route: 'g.toon.relay',\n price: 1n,\n requiredTransport: 'btp',\n } satisfies DevnetNode,\n\n /**\n * The relay's ephemeral lane, priced at **zero** — the one route on the devnet\n * that exercises the whole wire while holding no funds and no channel. Not\n * carriage-pinned, unlike `g.toon.relay` beside it.\n */\n ephemeral: {\n url: 'https://proxy.relay.devnet.toonprotocol.dev',\n route: 'g.toon.relay.ephemeral',\n price: 0n,\n } satisfies DevnetNode,\n\n /** Test funds. `POST /api/base-sepolia/request` and `/api/solana/usdc-request`. */\n faucet: 'https://faucet.devnet.toonprotocol.dev',\n\n /** Base Sepolia. The registry is the stable address; the token network is resolved from it. */\n evm: {\n chainId: 84532,\n rpcUrl: 'https://sepolia.base.org',\n tokenNetworkRegistry: '0x0c41D9D424d6B075A3cEa1068a694f7847a8CCa5',\n tokenNetwork: '0xe9E05dfecfe165266C88d73e61D483612651952a',\n /** Mock USDC, 6 decimals, ungated `mint()`. */\n tokenAddress: '0x49beE1Bca5d15Fb0963117923403F9498119a9Ce',\n decimals: 6,\n },\n\n /** Solana devnet — the public cluster, not a local validator. */\n solana: {\n rpcUrl: 'https://api.devnet.solana.com',\n /** The deployed `payment-channel` program. Bound into every claim (ADR 0053). */\n programId: '2aEVJ8koKD8LTZrLRSGtAtU7LBt4e7QjjCgf1kzQ7Rip',\n /** Mock USDC SPL mint, 6 decimals. */\n tokenAddress: '34eSxY7qxQ4GzyhDJ8GpUcTz1WWzruGbJbR8q6TtxfQU',\n decimals: 6,\n },\n} as const;\n\n/** The default RPC URL for a chain when a caller configures none. */\nexport function defaultRpcUrl(chain: 'evm' | 'solana'): string {\n return chain === 'evm' ? DEVNET.evm.rpcUrl : DEVNET.solana.rpcUrl;\n}\n"],"mappings":";AAuBA,SAAS,2BAA2B;AACpC,SAAS,aAAa;AACtB;AAAA,EACE,oBAAoB;AAAA,EACpB,oBAAoB;AAAA,EACpB;AAAA,OACK;AACP,SAAS,YAAY,eAAe;AACpC,SAAS,aAAa;AACtB,SAA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