@talismn/crypto 0.2.3 → 0.3.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.
Files changed (41) hide show
  1. package/dist/index.d.mts +124 -0
  2. package/dist/index.d.ts +124 -0
  3. package/dist/index.js +811 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/index.mjs +729 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/package.json +25 -24
  8. package/dist/declarations/src/address/addressFromPublicKey.d.ts +0 -5
  9. package/dist/declarations/src/address/encodeAnyAddress.d.ts +0 -5
  10. package/dist/declarations/src/address/encoding/addressEncodingFromCurve.d.ts +0 -3
  11. package/dist/declarations/src/address/encoding/bitcoin.d.ts +0 -37
  12. package/dist/declarations/src/address/encoding/detectAddressEncoding.d.ts +0 -2
  13. package/dist/declarations/src/address/encoding/ethereum.d.ts +0 -6
  14. package/dist/declarations/src/address/encoding/index.d.ts +0 -6
  15. package/dist/declarations/src/address/encoding/solana.d.ts +0 -2
  16. package/dist/declarations/src/address/encoding/ss58.d.ts +0 -3
  17. package/dist/declarations/src/address/index.d.ts +0 -6
  18. package/dist/declarations/src/address/isAddressEqual.d.ts +0 -1
  19. package/dist/declarations/src/address/isAddressValid.d.ts +0 -1
  20. package/dist/declarations/src/address/normalizeAddress.d.ts +0 -1
  21. package/dist/declarations/src/derivation/common.d.ts +0 -5
  22. package/dist/declarations/src/derivation/deriveEcdsa.d.ts +0 -3
  23. package/dist/declarations/src/derivation/deriveEd25519.d.ts +0 -3
  24. package/dist/declarations/src/derivation/deriveEthereum.d.ts +0 -3
  25. package/dist/declarations/src/derivation/deriveSolana.d.ts +0 -3
  26. package/dist/declarations/src/derivation/deriveSr25519.d.ts +0 -4
  27. package/dist/declarations/src/derivation/index.d.ts +0 -1
  28. package/dist/declarations/src/derivation/utils.d.ts +0 -7
  29. package/dist/declarations/src/hashing/index.d.ts +0 -9
  30. package/dist/declarations/src/index.d.ts +0 -7
  31. package/dist/declarations/src/mnemonic/index.d.ts +0 -9
  32. package/dist/declarations/src/platform/index.d.ts +0 -4
  33. package/dist/declarations/src/types/index.d.ts +0 -9
  34. package/dist/declarations/src/utils/exports.d.ts +0 -2
  35. package/dist/declarations/src/utils/index.d.ts +0 -2
  36. package/dist/declarations/src/utils/pbkdf2.d.ts +0 -1
  37. package/dist/talismn-crypto.cjs.d.ts +0 -1
  38. package/dist/talismn-crypto.cjs.dev.js +0 -766
  39. package/dist/talismn-crypto.cjs.js +0 -7
  40. package/dist/talismn-crypto.cjs.prod.js +0 -766
  41. package/dist/talismn-crypto.esm.js +0 -699
package/dist/index.mjs ADDED
@@ -0,0 +1,729 @@
1
+ // src/address/encoding/addressEncodingFromCurve.ts
2
+ var addressEncodingFromCurve = (curve) => {
3
+ switch (curve) {
4
+ case "sr25519":
5
+ case "ed25519":
6
+ case "ecdsa":
7
+ return "ss58";
8
+ case "bitcoin-ecdsa":
9
+ case "bitcoin-ed25519":
10
+ return "bech32m";
11
+ case "ethereum":
12
+ return "ethereum";
13
+ case "solana":
14
+ return "base58solana";
15
+ }
16
+ };
17
+
18
+ // src/address/encoding/bitcoin.ts
19
+ import { bech32, bech32m } from "bech32";
20
+ import bs58check from "bs58check";
21
+ var isBitcoinAddress = (address) => isBech32mAddress(address) || isBech32Address(address) || isBase58CheckAddress(address);
22
+ function isBech32mAddress(address) {
23
+ try {
24
+ fromBech32m(address);
25
+ } catch {
26
+ return false;
27
+ }
28
+ return true;
29
+ }
30
+ function isBech32Address(address) {
31
+ try {
32
+ fromBech32(address);
33
+ } catch {
34
+ return false;
35
+ }
36
+ return true;
37
+ }
38
+ function isBase58CheckAddress(address) {
39
+ try {
40
+ fromBase58Check(address);
41
+ } catch {
42
+ return false;
43
+ }
44
+ return true;
45
+ }
46
+ function fromBech32m(address) {
47
+ const result = bech32m.decode(address);
48
+ const version = result.words[0];
49
+ if (version === 0) throw new TypeError(`${address} uses wrong encoding`);
50
+ const data = bech32m.fromWords(result.words.slice(1));
51
+ return {
52
+ version,
53
+ prefix: result.prefix,
54
+ data: Uint8Array.from(data)
55
+ };
56
+ }
57
+ function fromBech32(address) {
58
+ const result = bech32.decode(address);
59
+ const version = result.words[0];
60
+ if (version !== 0) throw new TypeError(`${address} uses wrong encoding`);
61
+ const data = bech32.fromWords(result.words.slice(1));
62
+ return {
63
+ version,
64
+ prefix: result.prefix,
65
+ data: Uint8Array.from(data)
66
+ };
67
+ }
68
+ function fromBase58Check(address) {
69
+ const payload = bs58check.decode(address);
70
+ if (payload.length < 21) throw new TypeError(`${address} is too short`);
71
+ if (payload.length > 21) throw new TypeError(`${address} is too long`);
72
+ function readUInt8(buffer, offset) {
73
+ if (offset + 1 > buffer.length) {
74
+ throw new Error("Offset is outside the bounds of Uint8Array");
75
+ }
76
+ const buf = Buffer.from(buffer);
77
+ return buf.readUInt8(offset);
78
+ }
79
+ const version = readUInt8(payload, 0);
80
+ const hash = payload.slice(1);
81
+ return { version, hash };
82
+ }
83
+
84
+ // src/address/encoding/ethereum.ts
85
+ import { keccak_256 } from "@noble/hashes/sha3";
86
+ import { bytesToHex } from "@noble/hashes/utils";
87
+ var encodeAddressEthereum = (publicKey) => {
88
+ if (publicKey[0] !== 4) throw new Error("Invalid public key format");
89
+ const publicKeyWithoutPrefix = publicKey.slice(1);
90
+ const hash = keccak_256(publicKeyWithoutPrefix);
91
+ const address = hash.slice(-20);
92
+ return checksumEthereumAddress(`0x${bytesToHex(address)}`);
93
+ };
94
+ var checksumEthereumAddress = (address) => {
95
+ const addr = address.toLowerCase().replace(/^0x/, "");
96
+ const hash = keccak_256(new TextEncoder().encode(addr));
97
+ const hashHex = bytesToHex(hash);
98
+ const checksum = addr.split("").map((char, i) => parseInt(hashHex[i], 16) >= 8 ? char.toUpperCase() : char).join("");
99
+ return `0x${checksum}`;
100
+ };
101
+ function isEthereumAddress(address) {
102
+ return /^0x[a-fA-F0-9]{40}$/.test(address);
103
+ }
104
+
105
+ // src/address/encoding/solana.ts
106
+ import { base58 } from "@scure/base";
107
+ var encodeAddressSolana = (publicKey) => {
108
+ if (publicKey.length !== 32)
109
+ throw new Error("Public key must be 32 bytes long for Solana base58 encoding");
110
+ return base58.encode(publicKey);
111
+ };
112
+ function isSolanaAddress(address) {
113
+ try {
114
+ const bytes = base58.decode(address);
115
+ return bytes.length === 32;
116
+ } catch {
117
+ return false;
118
+ }
119
+ }
120
+
121
+ // src/address/encoding/ss58.ts
122
+ import { base58 as base583 } from "@scure/base";
123
+
124
+ // src/hashing/index.ts
125
+ import { blake2b } from "@noble/hashes/blake2b";
126
+ import { blake3 as blake3Hasher } from "@noble/hashes/blake3";
127
+ import { base58 as base582 } from "@scure/base";
128
+ var blake3 = blake3Hasher;
129
+ var blake2b256 = (msg) => blake2b(msg, { dkLen: 32 });
130
+ var blake2b512 = (msg) => blake2b(msg, { dkLen: 64 });
131
+ var getSafeHash = (bytes) => {
132
+ return base582.encode(blake3Hasher(bytes));
133
+ };
134
+
135
+ // src/address/encoding/ss58.ts
136
+ var VALID_PUBLICKEY_LENGTHS = [32, 33];
137
+ var accountId = (publicKey) => {
138
+ if (!VALID_PUBLICKEY_LENGTHS.includes(publicKey.length)) throw new Error("Invalid publicKey");
139
+ return publicKey.length === 33 ? blake2b256(publicKey) : publicKey;
140
+ };
141
+ var SS58PRE = /* @__PURE__ */ new TextEncoder().encode("SS58PRE");
142
+ var CHECKSUM_LENGTH = 2;
143
+ var VALID_PAYLOAD_LENGTHS = [32, 33];
144
+ var ss58Encode = (payload, prefix = 42) => {
145
+ if (!VALID_PAYLOAD_LENGTHS.includes(payload.length)) throw new Error("Invalid payload");
146
+ const prefixBytes = prefix < 64 ? Uint8Array.of(prefix) : Uint8Array.of(
147
+ (prefix & 252) >> 2 | 64,
148
+ prefix >> 8 | (prefix & 3) << 6
149
+ );
150
+ const checksum = blake2b512(Uint8Array.of(...SS58PRE, ...prefixBytes, ...payload)).subarray(
151
+ 0,
152
+ CHECKSUM_LENGTH
153
+ );
154
+ return base583.encode(Uint8Array.of(...prefixBytes, ...payload, ...checksum));
155
+ };
156
+ var VALID_ADDRESS_LENGTHS = [35, 36, 37];
157
+ var decodeSs58Address = (addressStr) => {
158
+ const address = base583.decode(addressStr);
159
+ if (!VALID_ADDRESS_LENGTHS.includes(address.length)) throw new Error("Invalid address length");
160
+ const addressChecksum = address.subarray(address.length - CHECKSUM_LENGTH);
161
+ const checksum = blake2b512(
162
+ Uint8Array.of(...SS58PRE, ...address.subarray(0, address.length - CHECKSUM_LENGTH))
163
+ ).subarray(0, CHECKSUM_LENGTH);
164
+ if (addressChecksum[0] !== checksum[0] || addressChecksum[1] !== checksum[1])
165
+ throw new Error("Invalid checksum");
166
+ const prefixLength = address[0] & 64 ? 2 : 1;
167
+ const prefix = prefixLength === 1 ? address[0] : (address[0] & 63) << 2 | address[1] >> 6 | (address[1] & 63) << 8;
168
+ const publicKey = address.slice(prefixLength, address.length - CHECKSUM_LENGTH);
169
+ return [publicKey, prefix];
170
+ };
171
+ var encodeAddressSs58 = (publicKey, prefix = 42) => {
172
+ if (typeof publicKey === "string") [publicKey] = decodeSs58Address(publicKey);
173
+ return ss58Encode(accountId(publicKey), prefix);
174
+ };
175
+ function isSs58Address(address) {
176
+ try {
177
+ decodeSs58Address(address);
178
+ return true;
179
+ } catch {
180
+ return false;
181
+ }
182
+ }
183
+
184
+ // src/address/encoding/detectAddressEncoding.ts
185
+ var CACHE = /* @__PURE__ */ new Map();
186
+ var detectAddressEncodingInner = (address) => {
187
+ if (isEthereumAddress(address)) return "ethereum";
188
+ if (isSs58Address(address)) return "ss58";
189
+ if (isSolanaAddress(address)) return "base58solana";
190
+ if (isBech32mAddress(address)) return "bech32m";
191
+ if (isBech32Address(address)) return "bech32";
192
+ if (isBase58CheckAddress(address)) return "base58check";
193
+ throw new Error(`Unknown address encoding`);
194
+ };
195
+ var detectAddressEncoding = (address) => {
196
+ if (!CACHE.has(address)) CACHE.set(address, detectAddressEncodingInner(address));
197
+ return CACHE.get(address);
198
+ };
199
+
200
+ // src/address/addressFromPublicKey.ts
201
+ var addressFromPublicKey = (publicKey, encoding, options) => {
202
+ switch (encoding) {
203
+ case "ss58":
204
+ return encodeAddressSs58(publicKey, options?.ss58Prefix);
205
+ case "ethereum":
206
+ return encodeAddressEthereum(publicKey);
207
+ case "base58solana":
208
+ return encodeAddressSolana(publicKey);
209
+ case "bech32m":
210
+ case "bech32":
211
+ case "base58check":
212
+ throw new Error("addressFromPublicKey is not implemented for Bitcoin");
213
+ }
214
+ };
215
+
216
+ // src/address/normalizeAddress.ts
217
+ var CACHE2 = /* @__PURE__ */ new Map();
218
+ var normalizeAddress = (address) => {
219
+ try {
220
+ if (!CACHE2.has(address)) CACHE2.set(address, normalizeAnyAddress(address));
221
+ return CACHE2.get(address);
222
+ } catch (cause) {
223
+ throw new Error(`Unable to normalize address: ${address}`, { cause });
224
+ }
225
+ };
226
+ var normalizeAnyAddress = (address) => {
227
+ switch (detectAddressEncoding(address)) {
228
+ case "ethereum":
229
+ return checksumEthereumAddress(address);
230
+ case "bech32m":
231
+ case "bech32":
232
+ case "base58check":
233
+ case "base58solana":
234
+ return address;
235
+ case "ss58": {
236
+ const [pk] = decodeSs58Address(address);
237
+ return encodeAddressSs58(pk, 42);
238
+ }
239
+ }
240
+ };
241
+
242
+ // src/address/encodeAnyAddress.ts
243
+ var encodeAnyAddress = (address, options) => {
244
+ const encoding = detectAddressEncoding(address);
245
+ if (encoding === "ss58" && options?.ss58Format !== void 0) {
246
+ const [publicKey] = decodeSs58Address(address);
247
+ return encodeAddressSs58(publicKey, options?.ss58Format ?? 42);
248
+ }
249
+ return normalizeAddress(address);
250
+ };
251
+
252
+ // src/address/isAddressEqual.ts
253
+ var isAddressEqual = (address1, address2) => {
254
+ try {
255
+ return normalizeAddress(address1) === normalizeAddress(address2);
256
+ } catch {
257
+ return false;
258
+ }
259
+ };
260
+
261
+ // src/address/isAddressValid.ts
262
+ var isAddressValid = (address) => {
263
+ try {
264
+ detectAddressEncoding(address);
265
+ return true;
266
+ } catch {
267
+ return false;
268
+ }
269
+ };
270
+
271
+ // src/derivation/deriveSolana.ts
272
+ import { ed25519 } from "@noble/curves/ed25519";
273
+ import { hmac } from "@noble/hashes/hmac";
274
+ import { sha512 } from "@noble/hashes/sha512";
275
+ var parseDerivationPath = (path) => {
276
+ if (!path.startsWith("m/")) throw new Error("Path must start with 'm/'");
277
+ return path.split("/").slice(1).map((p) => {
278
+ if (!p.endsWith("'")) throw new Error("Only hardened derivation is supported");
279
+ return parseInt(p.slice(0, -1), 10) + 2147483648;
280
+ });
281
+ };
282
+ var deriveSolana = (seed, derivationPath) => {
283
+ let I = hmac(sha512, new TextEncoder().encode("ed25519 seed"), seed);
284
+ let secretKey = I.slice(0, 32);
285
+ let chainCode = I.slice(32);
286
+ for (const index of parseDerivationPath(derivationPath)) {
287
+ const data = new Uint8Array(1 + secretKey.length + 4);
288
+ data.set([0], 0);
289
+ data.set(secretKey, 1);
290
+ data.set(
291
+ new Uint8Array([
292
+ index >> 24 & 255,
293
+ index >> 16 & 255,
294
+ index >> 8 & 255,
295
+ index & 255
296
+ ]),
297
+ 1 + secretKey.length
298
+ );
299
+ I = hmac(sha512, chainCode, data);
300
+ secretKey = I.slice(0, 32);
301
+ chainCode = I.slice(32);
302
+ }
303
+ const publicKey = getPublicKeySolana(secretKey);
304
+ return {
305
+ type: "solana",
306
+ secretKey,
307
+ publicKey,
308
+ address: addressFromPublicKey(publicKey, "base58solana")
309
+ };
310
+ };
311
+ var getPublicKeySolana = (secretKey) => {
312
+ return ed25519.getPublicKey(secretKey);
313
+ };
314
+
315
+ // src/derivation/utils.ts
316
+ import { base58 as base585, hex as hex2 } from "@scure/base";
317
+
318
+ // src/mnemonic/index.ts
319
+ import {
320
+ entropyToMnemonic as entropyToMnemonicBip39,
321
+ generateMnemonic as generateMnemonicBip39,
322
+ mnemonicToEntropy as mnemonicToEntropyBip39,
323
+ validateMnemonic
324
+ } from "@scure/bip39";
325
+ import { wordlist } from "@scure/bip39/wordlists/english";
326
+
327
+ // src/utils/exports.ts
328
+ import { ed25519 as ed255192 } from "@noble/curves/ed25519";
329
+ import { base58 as base584, base64, hex, utf8 } from "@scure/base";
330
+
331
+ // src/utils/pbkdf2.ts
332
+ var pbkdf2 = async (hash, entropy, salt, iterations, outputLenBytes) => {
333
+ const keyMaterial = await crypto.subtle.importKey("raw", entropy, "PBKDF2", false, ["deriveBits"]);
334
+ const derivedBits = await crypto.subtle.deriveBits(
335
+ { name: "PBKDF2", salt, iterations, hash },
336
+ keyMaterial,
337
+ outputLenBytes * 8
338
+ );
339
+ return new Uint8Array(derivedBits);
340
+ };
341
+
342
+ // src/mnemonic/index.ts
343
+ var mnemonicToEntropy = (mnemonic) => {
344
+ return mnemonicToEntropyBip39(mnemonic, wordlist);
345
+ };
346
+ var entropyToMnemonic = (entropy) => {
347
+ return entropyToMnemonicBip39(entropy, wordlist);
348
+ };
349
+ var entropyToSeedSubstrate = async (entropy, password) => await pbkdf2(
350
+ "SHA-512",
351
+ entropy,
352
+ mnemonicPasswordToSalt(password ?? ""),
353
+ 2048,
354
+ // 2048 iterations
355
+ 32
356
+ // 32 bytes (32 * 8 == 256 bits)
357
+ );
358
+ var entropyToSeedClassic = async (entropy, password) => await pbkdf2(
359
+ "SHA-512",
360
+ encodeNormalized(entropyToMnemonic(entropy)),
361
+ mnemonicPasswordToSalt(password ?? ""),
362
+ 2048,
363
+ // 2048 iterations
364
+ 64
365
+ // 64 bytes (64 * 8 == 512 bits)
366
+ );
367
+ var mnemonicPasswordToSalt = (password) => encodeNormalized(`mnemonic${password}`);
368
+ var encodeNormalized = (utf82) => new TextEncoder().encode(utf82.normalize("NFKD"));
369
+ var getSeedDerivationType = (curve) => {
370
+ switch (curve) {
371
+ case "sr25519":
372
+ case "ed25519":
373
+ case "ecdsa":
374
+ return "substrate";
375
+ case "ethereum":
376
+ case "solana":
377
+ return "classic";
378
+ case "bitcoin-ecdsa":
379
+ case "bitcoin-ed25519":
380
+ throw new Error("seed derivation is not implemented for Bitcoin");
381
+ }
382
+ };
383
+ var entropyToSeed = async (entropy, curve, password) => {
384
+ const type = getSeedDerivationType(curve);
385
+ switch (type) {
386
+ case "classic":
387
+ return await entropyToSeedClassic(entropy, password);
388
+ case "substrate":
389
+ return await entropyToSeedSubstrate(entropy, password);
390
+ }
391
+ };
392
+ var isValidMnemonic = (mnemonic) => {
393
+ return validateMnemonic(mnemonic, wordlist);
394
+ };
395
+ var generateMnemonic = (words) => {
396
+ switch (words) {
397
+ case 12:
398
+ return generateMnemonicBip39(wordlist, 128);
399
+ case 24:
400
+ return generateMnemonicBip39(wordlist, 256);
401
+ }
402
+ };
403
+ var DEV_MNEMONIC_POLKADOT = "bottom drive obey lake curtain smoke basket hold race lonely fit walk";
404
+ var DEV_MNEMONIC_ETHEREUM = "test test test test test test test test test test test junk";
405
+ var DEV_SEED_CACHE = /* @__PURE__ */ new Map();
406
+ var getDevSeed = async (curve) => {
407
+ const type = getSeedDerivationType(curve);
408
+ if (!DEV_SEED_CACHE.has(type)) {
409
+ switch (type) {
410
+ case "classic": {
411
+ const entropy = mnemonicToEntropy(DEV_MNEMONIC_ETHEREUM);
412
+ const seed = await entropyToSeedClassic(entropy);
413
+ DEV_SEED_CACHE.set(type, seed);
414
+ break;
415
+ }
416
+ case "substrate": {
417
+ const entropy = mnemonicToEntropy(DEV_MNEMONIC_POLKADOT);
418
+ const seed = await entropyToSeedSubstrate(entropy);
419
+ DEV_SEED_CACHE.set(type, seed);
420
+ break;
421
+ }
422
+ default:
423
+ throw new Error("Unsupported derivation type");
424
+ }
425
+ }
426
+ return DEV_SEED_CACHE.get(type);
427
+ };
428
+
429
+ // src/derivation/deriveEcdsa.ts
430
+ import { secp256k1 } from "@noble/curves/secp256k1";
431
+
432
+ // src/derivation/common.ts
433
+ import { Bytes, str, Tuple, u32 } from "scale-ts";
434
+ var DERIVATION_RE = /(\/{1,2})(\w+)/g;
435
+ var parseSubstrateDerivations = (derivationsStr) => {
436
+ const derivations = [];
437
+ if (derivations)
438
+ for (const [_, type, code] of derivationsStr.matchAll(DERIVATION_RE)) {
439
+ derivations.push([type === "//" ? "hard" : "soft", code]);
440
+ }
441
+ return derivations;
442
+ };
443
+ var createChainCode = (code) => {
444
+ const chainCode = new Uint8Array(32);
445
+ chainCode.set(Number.isNaN(+code) ? str.enc(code) : u32.enc(+code));
446
+ return chainCode;
447
+ };
448
+ var derivationCodec = /* @__PURE__ */ Tuple(str, Bytes(32), Bytes(32));
449
+ var createSubstrateDeriveFn = (prefix) => (seed, chainCode) => blake2b256(derivationCodec.enc([prefix, seed, chainCode]));
450
+ var deriveSubstrateSecretKey = (seed, derivationPath, prefix) => {
451
+ const derivations = parseSubstrateDerivations(derivationPath);
452
+ const derive = createSubstrateDeriveFn(prefix);
453
+ return derivations.reduce((seed2, [type, chainCode]) => {
454
+ const code = createChainCode(chainCode);
455
+ if (type === "soft") throw new Error("Soft derivations are not supported");
456
+ return derive(seed2, code);
457
+ }, seed);
458
+ };
459
+
460
+ // src/derivation/deriveEcdsa.ts
461
+ var deriveEcdsa = (seed, derivationPath) => {
462
+ const secretKey = deriveSubstrateSecretKey(seed, derivationPath, "Secp256k1HDKD");
463
+ const publicKey = getPublicKeyEcdsa(secretKey);
464
+ return {
465
+ type: "ecdsa",
466
+ secretKey,
467
+ publicKey,
468
+ address: addressFromPublicKey(publicKey, "ss58")
469
+ };
470
+ };
471
+ var getPublicKeyEcdsa = (secretKey) => {
472
+ return secp256k1.getPublicKey(secretKey);
473
+ };
474
+
475
+ // src/derivation/deriveEd25519.ts
476
+ import { ed25519 as ed255193 } from "@noble/curves/ed25519";
477
+ var deriveEd25519 = (seed, derivationPath) => {
478
+ const secretKey = deriveSubstrateSecretKey(seed, derivationPath, "Ed25519HDKD");
479
+ const publicKey = getPublicKeyEd25519(secretKey);
480
+ return {
481
+ type: "ed25519",
482
+ secretKey,
483
+ publicKey,
484
+ address: addressFromPublicKey(publicKey, "ss58")
485
+ };
486
+ };
487
+ var getPublicKeyEd25519 = (secretKey) => {
488
+ if (secretKey.length === 64) {
489
+ const [privateComponent, publicComponent] = [secretKey.slice(0, 32), secretKey.slice(32)];
490
+ const publicKey = ed255193.getPublicKey(privateComponent);
491
+ if (!isUint8ArrayEq(publicComponent, publicKey)) return ed255193.getPublicKey(secretKey);
492
+ return publicKey;
493
+ }
494
+ return ed255193.getPublicKey(secretKey);
495
+ };
496
+ var isUint8ArrayEq = (a, b) => (
497
+ // biome-ignore lint/complexity/noUselessTernary: legacy
498
+ a.length !== b.length || a.some((v, i) => v !== b[i]) ? false : true
499
+ );
500
+
501
+ // src/derivation/deriveEthereum.ts
502
+ import { secp256k1 as secp256k12 } from "@noble/curves/secp256k1";
503
+ import { HDKey } from "@scure/bip32";
504
+ var deriveEthereum = (seed, derivationPath) => {
505
+ const hdkey = HDKey.fromMasterSeed(seed);
506
+ const childKey = hdkey.derive(derivationPath);
507
+ if (!childKey.privateKey) throw new Error("Invalid derivation path");
508
+ const secretKey = new Uint8Array(childKey.privateKey);
509
+ const publicKey = getPublicKeyEthereum(secretKey);
510
+ return {
511
+ type: "ethereum",
512
+ secretKey,
513
+ publicKey,
514
+ address: addressFromPublicKey(publicKey, "ethereum")
515
+ };
516
+ };
517
+ var getPublicKeyEthereum = (secretKey) => {
518
+ const scalar = secp256k12.utils.normPrivateKeyToScalar(secretKey);
519
+ return secp256k12.getPublicKey(scalar, false);
520
+ };
521
+
522
+ // src/derivation/deriveSr25519.ts
523
+ import { randomBytes } from "@noble/hashes/utils";
524
+ import { getPublicKey, HDKD, secretFromSeed } from "micro-sr25519";
525
+ var deriveSr25519 = (seed, derivationPath) => {
526
+ const derivations = parseSubstrateDerivations(derivationPath);
527
+ const secretKey = derivations.reduce((secretKey2, [type, chainCode]) => {
528
+ const deriveFn = type === "hard" ? HDKD.secretHard : HDKD.secretSoft;
529
+ const code = createChainCode(chainCode);
530
+ return deriveFn(secretKey2, code, randomBytes);
531
+ }, secretFromSeed(seed));
532
+ const publicKey = getPublicKeySr25519(secretKey);
533
+ return {
534
+ type: "sr25519",
535
+ secretKey,
536
+ publicKey,
537
+ address: addressFromPublicKey(publicKey, "ss58")
538
+ };
539
+ };
540
+ var getPublicKeySr25519 = getPublicKey;
541
+
542
+ // src/derivation/utils.ts
543
+ var deriveKeypair = (seed, derivationPath, curve) => {
544
+ switch (curve) {
545
+ case "sr25519":
546
+ return deriveSr25519(seed, derivationPath);
547
+ case "ed25519":
548
+ return deriveEd25519(seed, derivationPath);
549
+ case "ecdsa":
550
+ return deriveEcdsa(seed, derivationPath);
551
+ case "bitcoin-ecdsa":
552
+ case "bitcoin-ed25519":
553
+ throw new Error("deriveKeypair is not implemented for Bitcoin");
554
+ case "ethereum":
555
+ return deriveEthereum(seed, derivationPath);
556
+ case "solana":
557
+ return deriveSolana(seed, derivationPath);
558
+ }
559
+ };
560
+ var getPublicKeyFromSecret = (secretKey, curve) => {
561
+ switch (curve) {
562
+ case "ecdsa":
563
+ return getPublicKeyEcdsa(secretKey);
564
+ case "ethereum":
565
+ return getPublicKeyEthereum(secretKey);
566
+ case "sr25519":
567
+ return getPublicKeySr25519(secretKey);
568
+ case "ed25519":
569
+ return getPublicKeyEd25519(secretKey);
570
+ case "bitcoin-ecdsa":
571
+ case "bitcoin-ed25519":
572
+ throw new Error("getPublicKeyFromSecret is not implemented for Bitcoin");
573
+ case "solana":
574
+ return getPublicKeySolana(secretKey);
575
+ }
576
+ };
577
+ var addressFromMnemonic = async (mnemonic, derivationPath, curve) => {
578
+ const entropy = mnemonicToEntropy(mnemonic);
579
+ const seed = await entropyToSeed(entropy, curve);
580
+ const { address } = deriveKeypair(seed, derivationPath, curve);
581
+ return address;
582
+ };
583
+ var removeHexPrefix = (secretKey) => {
584
+ if (secretKey.startsWith("0x")) return secretKey.slice(2);
585
+ return secretKey;
586
+ };
587
+ var parseSecretKey = (secretKey, platform) => {
588
+ switch (platform) {
589
+ case "ethereum": {
590
+ const privateKey = removeHexPrefix(secretKey);
591
+ return hex2.decode(privateKey);
592
+ }
593
+ case "solana": {
594
+ const bytes = secretKey.startsWith("[") ? (
595
+ // JSON bytes array (ex: solflare)
596
+ Uint8Array.from(JSON.parse(secretKey))
597
+ ) : (
598
+ // base58 encoded string (ex: phantom)
599
+ base585.decode(secretKey)
600
+ );
601
+ if (bytes.length === 64) {
602
+ const privateKey = bytes.slice(0, 32);
603
+ const publicKey = bytes.slice(32, 64);
604
+ const computedPublicKey = getPublicKeySolana(privateKey);
605
+ if (!publicKey.every((b, i) => b === computedPublicKey[i]))
606
+ throw new Error("Invalid Solana secret key: public key does not match");
607
+ return privateKey;
608
+ } else if (bytes.length === 32) return bytes;
609
+ throw new Error("Invalid Solana secret key length");
610
+ }
611
+ default:
612
+ throw new Error("Not implemented");
613
+ }
614
+ };
615
+ var isValidDerivationPath = async (derivationPath, curve) => {
616
+ try {
617
+ deriveKeypair(await getDevSeed(curve), derivationPath, curve);
618
+ return true;
619
+ } catch {
620
+ return false;
621
+ }
622
+ };
623
+
624
+ // src/encryption/encryptKemAead.ts
625
+ import { xchacha20poly1305 } from "@noble/ciphers/chacha.js";
626
+ import { concatBytes } from "@noble/ciphers/utils.js";
627
+ import { MlKem768 } from "mlkem";
628
+ var encryptKemAead = async (publicKey, plaintext) => {
629
+ const kem = new MlKem768();
630
+ const [kemCt, sharedSecret] = await kem.encap(publicKey);
631
+ if (sharedSecret.length !== 32) {
632
+ throw new Error(`Expected 32-byte shared secret, got ${sharedSecret.length}`);
633
+ }
634
+ const nonce = crypto.getRandomValues(new Uint8Array(24));
635
+ const aead = xchacha20poly1305(sharedSecret, nonce);
636
+ const aeadCt = aead.encrypt(plaintext);
637
+ const kemLen = new Uint8Array(2);
638
+ new DataView(kemLen.buffer).setUint16(0, kemCt.length, true);
639
+ return concatBytes(kemLen, kemCt, nonce, aeadCt);
640
+ };
641
+
642
+ // src/platform/index.ts
643
+ var getAccountPlatformFromCurve = (curve) => {
644
+ switch (curve) {
645
+ case "sr25519":
646
+ case "ed25519":
647
+ case "ecdsa":
648
+ return "polkadot";
649
+ case "ethereum":
650
+ return "ethereum";
651
+ case "bitcoin-ecdsa":
652
+ case "bitcoin-ed25519":
653
+ return "bitcoin";
654
+ case "solana":
655
+ return "solana";
656
+ }
657
+ };
658
+ var getAccountPlatformFromEncoding = (encoding) => {
659
+ switch (encoding) {
660
+ case "ss58":
661
+ return "polkadot";
662
+ case "ethereum":
663
+ return "ethereum";
664
+ case "bech32m":
665
+ case "bech32":
666
+ case "base58check":
667
+ return "bitcoin";
668
+ case "base58solana":
669
+ return "solana";
670
+ }
671
+ };
672
+ var getAccountPlatformFromAddress = (address) => {
673
+ const encoding = detectAddressEncoding(address);
674
+ return getAccountPlatformFromEncoding(encoding);
675
+ };
676
+ export {
677
+ DEV_MNEMONIC_ETHEREUM,
678
+ DEV_MNEMONIC_POLKADOT,
679
+ addressEncodingFromCurve,
680
+ addressFromMnemonic,
681
+ addressFromPublicKey,
682
+ base584 as base58,
683
+ base64,
684
+ blake2b256,
685
+ blake2b512,
686
+ blake3,
687
+ checksumEthereumAddress,
688
+ decodeSs58Address,
689
+ deriveKeypair,
690
+ detectAddressEncoding,
691
+ ed255192 as ed25519,
692
+ encodeAddressEthereum,
693
+ encodeAddressSolana,
694
+ encodeAddressSs58,
695
+ encodeAnyAddress,
696
+ encryptKemAead,
697
+ entropyToMnemonic,
698
+ entropyToSeed,
699
+ fromBase58Check,
700
+ fromBech32,
701
+ fromBech32m,
702
+ generateMnemonic,
703
+ getAccountPlatformFromAddress,
704
+ getAccountPlatformFromCurve,
705
+ getAccountPlatformFromEncoding,
706
+ getDevSeed,
707
+ getPublicKeyFromSecret,
708
+ getPublicKeySolana,
709
+ getSafeHash,
710
+ hex,
711
+ isAddressEqual,
712
+ isAddressValid,
713
+ isBase58CheckAddress,
714
+ isBech32Address,
715
+ isBech32mAddress,
716
+ isBitcoinAddress,
717
+ isEthereumAddress,
718
+ isSolanaAddress,
719
+ isSs58Address,
720
+ isValidDerivationPath,
721
+ isValidMnemonic,
722
+ mnemonicToEntropy,
723
+ normalizeAddress,
724
+ parseSecretKey,
725
+ pbkdf2,
726
+ removeHexPrefix,
727
+ utf8
728
+ };
729
+ //# sourceMappingURL=index.mjs.map