@talismn/keyring 1.0.12 → 2.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.
package/dist/index.js CHANGED
@@ -1,501 +1,409 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _talismn_crypto = require("@talismn/crypto");
3
+ //#region src/types/utils.ts
4
+ const isAccountOfType = (account, type) => {
5
+ return account?.type === type;
9
6
  };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
7
+ const isAccountInTypes = (account, types) => {
8
+ return !!account && types.includes(account.type);
17
9
  };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- Keyring: () => Keyring,
24
- getAccountGenesisHash: () => getAccountGenesisHash,
25
- getAccountPlatform: () => getAccountPlatform,
26
- getAccountSignetUrl: () => getAccountSignetUrl,
27
- isAccountAddressEthereum: () => isAccountAddressEthereum,
28
- isAccountAddressSs58: () => isAccountAddressSs58,
29
- isAccountBitcoin: () => isAccountBitcoin,
30
- isAccountExternal: () => isAccountExternal,
31
- isAccountInTypes: () => isAccountInTypes,
32
- isAccountLedgerPolkadot: () => isAccountLedgerPolkadot,
33
- isAccountLedgerPolkadotGeneric: () => isAccountLedgerPolkadotGeneric,
34
- isAccountLedgerPolkadotLegacy: () => isAccountLedgerPolkadotLegacy,
35
- isAccountNotContact: () => isAccountNotContact,
36
- isAccountOfType: () => isAccountOfType,
37
- isAccountOwned: () => isAccountOwned,
38
- isAccountPlatformEthereum: () => isAccountPlatformEthereum,
39
- isAccountPlatformPolkadot: () => isAccountPlatformPolkadot,
40
- isAccountPlatformSolana: () => isAccountPlatformSolana,
41
- isAccountPortfolio: () => isAccountPortfolio
42
- });
43
- module.exports = __toCommonJS(index_exports);
44
-
45
- // src/keyring/Keyring.ts
46
- var import_crypto3 = require("@talismn/crypto");
47
-
48
- // src/types/utils.ts
49
- var import_crypto = require("@talismn/crypto");
50
- var isAccountOfType = (account, type) => {
51
- return account?.type === type;
52
- };
53
- var isAccountInTypes = (account, types) => {
54
- return !!account && types.includes(account.type);
55
- };
56
- var ACCOUNT_TYPES_OWNED = [
57
- "keypair",
58
- "ledger-ethereum",
59
- "ledger-polkadot",
60
- "ledger-solana",
61
- "polkadot-vault"
10
+ const ACCOUNT_TYPES_OWNED = [
11
+ "keypair",
12
+ "ledger-ethereum",
13
+ "ledger-polkadot",
14
+ "ledger-solana",
15
+ "polkadot-vault"
62
16
  ];
63
- var ACCOUNT_TYPES_EXTERNAL = [
64
- "contact",
65
- "watch-only",
66
- "ledger-ethereum",
67
- "ledger-polkadot",
68
- "ledger-solana",
69
- "polkadot-vault",
70
- "signet"
17
+ const ACCOUNT_TYPES_EXTERNAL = [
18
+ "contact",
19
+ "watch-only",
20
+ "ledger-ethereum",
21
+ "ledger-polkadot",
22
+ "ledger-solana",
23
+ "polkadot-vault",
24
+ "signet"
71
25
  ];
72
- var isAccountExternal = (account) => {
73
- return isAccountInTypes(account, ACCOUNT_TYPES_EXTERNAL);
26
+ const isAccountExternal = (account) => {
27
+ return isAccountInTypes(account, ACCOUNT_TYPES_EXTERNAL);
74
28
  };
75
- var isAccountOwned = (account) => {
76
- return isAccountInTypes(account, ACCOUNT_TYPES_OWNED);
29
+ const isAccountOwned = (account) => {
30
+ return isAccountInTypes(account, ACCOUNT_TYPES_OWNED);
77
31
  };
78
- var isAccountPortfolio = (account) => {
79
- return isAccountOwned(account) || isAccountOfType(account, "watch-only") && account.isPortfolio;
32
+ const isAccountPortfolio = (account) => {
33
+ return isAccountOwned(account) || isAccountOfType(account, "watch-only") && account.isPortfolio;
80
34
  };
81
- var isAccountNotContact = (acc) => acc.type !== "contact";
82
- var isAccountAddressEthereum = (account) => {
83
- return !!account && (0, import_crypto.isEthereumAddress)(account.address);
35
+ const isAccountNotContact = (acc) => acc.type !== "contact";
36
+ const isAccountAddressEthereum = (account) => {
37
+ return !!account && (0, _talismn_crypto.isEthereumAddress)(account.address);
84
38
  };
85
- var isAccountPlatformEthereum = (account) => {
86
- return !!account && account.type !== "ledger-polkadot" && (0, import_crypto.isEthereumAddress)(account.address);
39
+ const isAccountPlatformEthereum = (account) => {
40
+ return !!account && account.type !== "ledger-polkadot" && (0, _talismn_crypto.isEthereumAddress)(account.address);
87
41
  };
88
- var isAccountPlatformSolana = (account) => {
89
- return !!account && (0, import_crypto.isSolanaAddress)(account.address);
42
+ const isAccountPlatformSolana = (account) => {
43
+ return !!account && (0, _talismn_crypto.isSolanaAddress)(account.address);
90
44
  };
91
- var isAccountPlatformPolkadot = (account) => {
92
- return !!account && account.type !== "ledger-ethereum" && (isAccountAddressEthereum(account) || isAccountAddressSs58(account));
45
+ const isAccountPlatformPolkadot = (account) => {
46
+ return !!account && account.type !== "ledger-ethereum" && (isAccountAddressEthereum(account) || isAccountAddressSs58(account));
93
47
  };
94
- var isAccountAddressSs58 = (account) => {
95
- return !!account && (0, import_crypto.detectAddressEncoding)(account.address) === "ss58";
48
+ const isAccountAddressSs58 = (account) => {
49
+ return !!account && (0, _talismn_crypto.detectAddressEncoding)(account.address) === "ss58";
96
50
  };
97
- var isAccountLedgerPolkadot = (account) => {
98
- return isAccountOfType(account, "ledger-polkadot");
51
+ const isAccountLedgerPolkadot = (account) => {
52
+ return isAccountOfType(account, "ledger-polkadot");
99
53
  };
100
- var isAccountLedgerPolkadotGeneric = (account) => {
101
- return isAccountOfType(account, "ledger-polkadot") && !account.genesisHash;
54
+ const isAccountLedgerPolkadotGeneric = (account) => {
55
+ return isAccountOfType(account, "ledger-polkadot") && !account.genesisHash;
102
56
  };
103
- var isAccountLedgerPolkadotLegacy = (account) => {
104
- return isAccountOfType(account, "ledger-polkadot") && !!account.genesisHash;
57
+ const isAccountLedgerPolkadotLegacy = (account) => {
58
+ return isAccountOfType(account, "ledger-polkadot") && !!account.genesisHash;
105
59
  };
106
- var isAccountBitcoin = (account) => {
107
- return !!account && (0, import_crypto.isBitcoinAddress)(account.address);
60
+ const isAccountBitcoin = (account) => {
61
+ return !!account && (0, _talismn_crypto.isBitcoinAddress)(account.address);
108
62
  };
109
- var getAccountGenesisHash = (account) => {
110
- if (!account) return void 0;
111
- return "genesisHash" in account ? account.genesisHash || void 0 : void 0;
63
+ const getAccountGenesisHash = (account) => {
64
+ if (!account) return void 0;
65
+ return "genesisHash" in account ? account.genesisHash || void 0 : void 0;
112
66
  };
113
- var getAccountSignetUrl = (account) => {
114
- return isAccountOfType(account, "signet") ? account.url : void 0;
67
+ const getAccountSignetUrl = (account) => {
68
+ return isAccountOfType(account, "signet") ? account.url : void 0;
115
69
  };
116
- var getAccountPlatform = (account) => {
117
- if (!account) return void 0;
118
- return "curve" in account ? (0, import_crypto.getAccountPlatformFromCurve)(account.curve) : (0, import_crypto.getAccountPlatformFromAddress)(account.address);
70
+ const getAccountPlatform = (account) => {
71
+ if (!account) return void 0;
72
+ return "curve" in account ? (0, _talismn_crypto.getAccountPlatformFromCurve)(account.curve) : (0, _talismn_crypto.getAccountPlatformFromAddress)(account.address);
119
73
  };
120
-
121
- // src/keyring/encryption.ts
122
- var import_crypto2 = require("@talismn/crypto");
123
- var deriveKey = async (password, salt) => (
124
- // Deriving 32-byte key using PBKDF2 with 100,000 iterations and SHA-256
125
- await crypto.subtle.importKey(
126
- "raw",
127
- await (0, import_crypto2.pbkdf2)(
128
- "SHA-256",
129
- new TextEncoder().encode(password),
130
- salt,
131
- 1e5,
132
- // 100,000 iterations
133
- 32
134
- // 32 bytes (32 * 8 == 256 bits)
135
- ),
136
- { name: "AES-GCM", length: 256 },
137
- false,
138
- ["encrypt", "decrypt"]
139
- )
140
- );
141
- var encryptData = async (data, password) => {
142
- try {
143
- const salt = crypto.getRandomValues(new Uint8Array(16));
144
- const iv = crypto.getRandomValues(new Uint8Array(12));
145
- const key = await deriveKey(password, salt);
146
- const encryptedSeed = await crypto.subtle.encrypt(
147
- { name: "AES-GCM", iv },
148
- key,
149
- data
150
- );
151
- const combined = new Uint8Array(salt.length + iv.length + encryptedSeed.byteLength);
152
- combined.set(salt, 0);
153
- combined.set(iv, salt.length);
154
- combined.set(new Uint8Array(encryptedSeed), salt.length + iv.length);
155
- return btoa(String.fromCharCode(...combined));
156
- } catch (cause) {
157
- throw new Error("Failed to encrypt data", { cause });
158
- }
74
+ //#endregion
75
+ //#region src/keyring/encryption.ts
76
+ const deriveKey = async (password, salt) => await crypto.subtle.importKey("raw", await (0, _talismn_crypto.pbkdf2)("SHA-256", new TextEncoder().encode(password), salt, 1e5, 32), {
77
+ name: "AES-GCM",
78
+ length: 256
79
+ }, false, ["encrypt", "decrypt"]);
80
+ const encryptData = async (data, password) => {
81
+ try {
82
+ const salt = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
83
+ const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
84
+ const key = await deriveKey(password, salt);
85
+ const encryptedSeed = await crypto.subtle.encrypt({
86
+ name: "AES-GCM",
87
+ iv
88
+ }, key, data);
89
+ const combined = new Uint8Array(salt.length + iv.length + encryptedSeed.byteLength);
90
+ combined.set(salt, 0);
91
+ combined.set(iv, salt.length);
92
+ combined.set(new Uint8Array(encryptedSeed), salt.length + iv.length);
93
+ return btoa(String.fromCharCode(...combined));
94
+ } catch (cause) {
95
+ throw new Error("Failed to encrypt data", { cause });
96
+ }
159
97
  };
160
- var decryptData = async (encryptedData, password) => {
161
- try {
162
- const combined = Uint8Array.from(atob(encryptedData), (c) => c.charCodeAt(0));
163
- const salt = combined.slice(0, 16);
164
- const iv = combined.slice(16, 28);
165
- const encryptedSeed = combined.slice(28);
166
- const key = await deriveKey(password, salt);
167
- const decryptedSeed = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, encryptedSeed);
168
- return new Uint8Array(decryptedSeed);
169
- } catch (cause) {
170
- throw new Error("Failed to decrypt data", { cause });
171
- }
98
+ const decryptData = async (encryptedData, password) => {
99
+ try {
100
+ const combined = Uint8Array.from(atob(encryptedData), (c) => c.charCodeAt(0));
101
+ const salt = combined.slice(0, 16);
102
+ const iv = combined.slice(16, 28);
103
+ const encryptedSeed = combined.slice(28);
104
+ const key = await deriveKey(password, salt);
105
+ const decryptedSeed = await crypto.subtle.decrypt({
106
+ name: "AES-GCM",
107
+ iv
108
+ }, key, encryptedSeed);
109
+ return new Uint8Array(decryptedSeed);
110
+ } catch (cause) {
111
+ throw new Error("Failed to decrypt data", { cause });
112
+ }
172
113
  };
173
- var changeEncryptedDataPassword = async (encryptedData, oldPassword, newPassword) => {
174
- try {
175
- const decrypted = await decryptData(encryptedData, oldPassword);
176
- return await encryptData(decrypted, newPassword);
177
- } catch (cause) {
178
- throw new Error("Failed to change password on encrypted data", { cause });
179
- }
114
+ const changeEncryptedDataPassword = async (encryptedData, oldPassword, newPassword) => {
115
+ try {
116
+ const decrypted = await decryptData(encryptedData, oldPassword);
117
+ return await encryptData(decrypted, newPassword);
118
+ } catch (cause) {
119
+ throw new Error("Failed to change password on encrypted data", { cause });
120
+ }
180
121
  };
181
-
182
- // src/keyring/utils.ts
183
- var REGEX_HEX_STRING = /^0x[0-9a-fA-F]*$/;
184
- var isHexString = (value) => {
185
- return typeof value === "string" && REGEX_HEX_STRING.test(value);
122
+ //#endregion
123
+ //#region src/keyring/utils.ts
124
+ const REGEX_HEX_STRING = /^0x[0-9a-fA-F]*$/;
125
+ const isHexString = (value) => {
126
+ return typeof value === "string" && REGEX_HEX_STRING.test(value);
186
127
  };
187
-
188
- // src/keyring/Keyring.ts
189
- var Keyring = class _Keyring {
190
- #data;
191
- constructor(data) {
192
- this.#data = structuredClone(data);
193
- }
194
- static create() {
195
- return new _Keyring({
196
- passwordCheck: null,
197
- // well-known data encrypted using the password, used to ensure all secrets of the keyring are encrypted with the same password
198
- mnemonics: [],
199
- accounts: []
200
- });
201
- }
202
- static load(data) {
203
- if (!data.accounts || !data.mnemonics) throw new Error("Invalid data");
204
- for (const account of data.accounts) {
205
- if (account.type === "ledger-polkadot" && !account.curve) account.curve = "ed25519";
206
- }
207
- return new _Keyring(data);
208
- }
209
- async checkPassword(password, reset = false) {
210
- if (typeof password !== "string" || !password) throw new Error("password is required");
211
- const passwordHash = oneWayHash(password);
212
- const PASSWORD_CHECK_PHRASE = "PASSWORD_CHECK_PHRASE";
213
- if (!this.#data.passwordCheck || reset) {
214
- const bytes = import_crypto3.utf8.decode(PASSWORD_CHECK_PHRASE);
215
- this.#data.passwordCheck = await encryptData(bytes, passwordHash);
216
- } else {
217
- try {
218
- const bytes = await decryptData(this.#data.passwordCheck, passwordHash);
219
- const text = import_crypto3.utf8.encode(bytes);
220
- if (text !== PASSWORD_CHECK_PHRASE) throw new Error("Invalid password");
221
- } catch {
222
- throw new Error("Invalid password");
223
- }
224
- }
225
- }
226
- /** Returns true if a password has been set on this keyring. */
227
- hasPassword() {
228
- return this.#data.passwordCheck !== null;
229
- }
230
- /**
231
- * Verify a password against the keyring's passwordCheck blob.
232
- * Returns true on success, false on wrong password.
233
- * Throws if no password has been set (caller should check hasPassword() first).
234
- */
235
- async verifyPassword(password) {
236
- if (!this.#data.passwordCheck) {
237
- throw new Error("No password set \u2014 call hasPassword() before verifyPassword()");
238
- }
239
- try {
240
- await this.checkPassword(password);
241
- return true;
242
- } catch {
243
- return false;
244
- }
245
- }
246
- /**
247
- * Initialize the password on a fresh keyring that has no password set.
248
- * Throws if a password is already set (use changePassword flow instead).
249
- */
250
- async initializePassword(password) {
251
- if (this.#data.passwordCheck !== null) {
252
- throw new Error("Password already set \u2014 cannot re-initialize");
253
- }
254
- await this.checkPassword(password, true);
255
- }
256
- toJson() {
257
- return structuredClone(this.#data);
258
- }
259
- async export(password, jsonPassword) {
260
- const keyring = new _Keyring(structuredClone(this.#data));
261
- for (const mnemonic of keyring.#data.mnemonics)
262
- mnemonic.entropy = await changeEncryptedDataPassword(mnemonic.entropy, password, jsonPassword);
263
- for (const account of keyring.#data.accounts)
264
- if (account.type === "keypair")
265
- account.secretKey = await changeEncryptedDataPassword(
266
- account.secretKey,
267
- password,
268
- jsonPassword
269
- );
270
- await keyring.checkPassword(jsonPassword, true);
271
- return keyring.toJson();
272
- }
273
- getMnemonics() {
274
- return this.#data.mnemonics.map(mnemonicFromStorage);
275
- }
276
- async addMnemonic({ name, mnemonic, confirmed }, password) {
277
- if (typeof name !== "string" || !name) throw new Error("name is required");
278
- if (typeof mnemonic !== "string") throw new Error("mnemonic is required");
279
- if (typeof confirmed !== "boolean") throw new Error("confirmed is required");
280
- if (!(0, import_crypto3.isValidMnemonic)(mnemonic)) throw new Error("Invalid mnemonic");
281
- await this.checkPassword(password);
282
- const entropy = (0, import_crypto3.mnemonicToEntropy)(mnemonic);
283
- const id = oneWayHash(entropy);
284
- if (this.#data.mnemonics.find((s) => s.id === id)) throw new Error("Mnemonic already exists");
285
- const storage = {
286
- id,
287
- name,
288
- entropy: await encryptData(entropy, password),
289
- confirmed,
290
- createdAt: Date.now()
291
- };
292
- this.#data.mnemonics.push(storage);
293
- return mnemonicFromStorage(storage);
294
- }
295
- getMnemonic(id) {
296
- const mnemonic = this.#data.mnemonics.find((s) => s.id === id);
297
- return mnemonic ? mnemonicFromStorage(mnemonic) : null;
298
- }
299
- updateMnemonic(id, { name, confirmed }) {
300
- const mnemonic = this.#data.mnemonics.find((s) => s.id === id);
301
- if (!mnemonic) throw new Error("Mnemonic not found");
302
- if (name !== void 0) {
303
- if (typeof name !== "string" || !name) throw new Error("name must be a string");
304
- mnemonic.name = name;
305
- }
306
- if (confirmed !== void 0) {
307
- if (typeof confirmed !== "boolean") throw new Error("confirmed must be a boolean");
308
- mnemonic.confirmed = confirmed;
309
- }
310
- return mnemonicFromStorage(mnemonic);
311
- }
312
- removeMnemonic(id) {
313
- const index = this.#data.mnemonics.findIndex((mnemonic) => mnemonic.id === id);
314
- if (index === -1) throw new Error("Mnemonic not found");
315
- this.#data.mnemonics.splice(index, 1);
316
- }
317
- async getMnemonicText(id, password) {
318
- const mnemonic = this.#data.mnemonics.find((s) => s.id === id);
319
- if (!mnemonic) throw new Error("Mnemonic not found");
320
- const entropy = await decryptData(mnemonic.entropy, password);
321
- return (0, import_crypto3.entropyToMnemonic)(entropy);
322
- }
323
- getExistingMnemonicId(mnemonic) {
324
- const entropy = (0, import_crypto3.mnemonicToEntropy)(mnemonic);
325
- const mnemonicId = oneWayHash(entropy);
326
- return this.#data.mnemonics.some((s) => s.id === mnemonicId) ? mnemonicId : null;
327
- }
328
- getAccounts() {
329
- return this.#data.accounts.map(accountFromStorage);
330
- }
331
- getAccount(address) {
332
- const account = this.#data.accounts.find((s) => (0, import_crypto3.isAddressEqual)(s.address, address));
333
- return account ? accountFromStorage(account) : null;
334
- }
335
- updateAccount(address, { name, isPortfolio, genesisHash }) {
336
- const account = this.#data.accounts.find((s) => s.address === address);
337
- if (!account) throw new Error("Account not found");
338
- if (name) {
339
- if (typeof name !== "string" || !name) throw new Error("name is required");
340
- account.name = name;
341
- }
342
- if (account.type === "watch-only" && isPortfolio !== void 0) {
343
- if (typeof isPortfolio !== "boolean") throw new Error("isPortfolio must be a boolean");
344
- account.isPortfolio = isPortfolio;
345
- }
346
- if (account.type === "contact") {
347
- if (genesisHash) {
348
- if (!isHexString(genesisHash)) throw new Error("genesisHash must be a hex string");
349
- account.genesisHash = genesisHash;
350
- } else delete account.genesisHash;
351
- }
352
- return accountFromStorage(account);
353
- }
354
- removeAccount(address) {
355
- const index = this.#data.accounts.findIndex((s) => (0, import_crypto3.isAddressEqual)(s.address, address));
356
- if (index === -1) throw new Error("Account not found");
357
- this.#data.accounts.splice(index, 1);
358
- }
359
- addAccountExternal(options) {
360
- const address = (0, import_crypto3.normalizeAddress)(options.address);
361
- if (this.getAccount(address)) throw new Error("Account already exists");
362
- const account = {
363
- ...options,
364
- address,
365
- createdAt: Date.now()
366
- };
367
- if (!isAccountExternal(account)) throw new Error("Invalid account type");
368
- this.#data.accounts.push(account);
369
- return accountFromStorage(account);
370
- }
371
- /**
372
- * Needs to be called before deriving an account from a mnemonic.
373
- *
374
- * This will ensure that it is present (or add it if possible) in the keyring before actually creating the account.
375
- *
376
- * @param options
377
- * @param password
378
- * @returns the id of the mnemonic
379
- */
380
- async ensureMnemonic(options, password) {
381
- await this.checkPassword(password);
382
- switch (options.type) {
383
- case "new-mnemonic": {
384
- const { mnemonic, mnemonicName: name, confirmed } = options;
385
- if (typeof name !== "string" || !name) throw new Error("mnemonicName is required");
386
- if (typeof confirmed !== "boolean") throw new Error("confirmed is required");
387
- const mnemonicId = this.getExistingMnemonicId(mnemonic);
388
- if (mnemonicId) return mnemonicId;
389
- const { id } = await this.addMnemonic(
390
- {
391
- name,
392
- mnemonic,
393
- confirmed
394
- },
395
- password
396
- );
397
- return id;
398
- }
399
- case "existing-mnemonic": {
400
- if (typeof options.mnemonicId !== "string" || !options.mnemonicId)
401
- throw new Error("mnemonicId must be a string");
402
- return options.mnemonicId;
403
- }
404
- }
405
- }
406
- async addAccountDerive(options, password) {
407
- await this.checkPassword(password);
408
- const { curve, derivationPath, name } = options;
409
- const mnemonicId = await this.ensureMnemonic(options, password);
410
- const mnemonic = this.#data.mnemonics.find((s) => s.id === mnemonicId);
411
- if (!mnemonic) throw new Error("Mnemonic not found");
412
- const entropy = await decryptData(mnemonic.entropy, password);
413
- const seed = await (0, import_crypto3.entropyToSeed)(entropy, curve);
414
- const pair = (0, import_crypto3.deriveKeypair)(seed, derivationPath, curve);
415
- if (this.getAccount(pair.address)) throw new Error("Account already exists");
416
- const account = {
417
- type: "keypair",
418
- curve,
419
- name,
420
- address: (0, import_crypto3.normalizeAddress)(pair.address),
421
- secretKey: await encryptData(pair.secretKey, password),
422
- mnemonicId,
423
- derivationPath,
424
- createdAt: Date.now()
425
- };
426
- this.#data.accounts.push(account);
427
- return accountFromStorage(account);
428
- }
429
- async addAccountKeypair({ curve, name, secretKey }, password) {
430
- await this.checkPassword(password);
431
- const publicKey = (0, import_crypto3.getPublicKeyFromSecret)(secretKey, curve);
432
- const encoding = (0, import_crypto3.addressEncodingFromCurve)(curve);
433
- const address = (0, import_crypto3.addressFromPublicKey)(publicKey, encoding);
434
- if (this.getAccount(address)) throw new Error("Account already exists");
435
- const account = {
436
- type: "keypair",
437
- curve,
438
- name,
439
- address: (0, import_crypto3.normalizeAddress)(address),
440
- secretKey: await encryptData(secretKey, password),
441
- createdAt: Date.now()
442
- };
443
- this.#data.accounts.push(account);
444
- return accountFromStorage(account);
445
- }
446
- getAccountSecretKey(address, password) {
447
- if (typeof address !== "string" || !address) throw new Error("address is required");
448
- if (typeof password !== "string" || !password) throw new Error("password is required");
449
- const account = this.#data.accounts.find((a) => a.address === (0, import_crypto3.normalizeAddress)(address));
450
- if (!account) throw new Error("Account not found");
451
- if (account.type !== "keypair") throw new Error("Secret key unavailable");
452
- return decryptData(account.secretKey, password);
453
- }
454
- async getDerivedAddress(mnemonicId, derivationPath, curve, password) {
455
- if (typeof mnemonicId !== "string" || !mnemonicId) throw new Error("mnemonicId is required");
456
- if (typeof password !== "string" || !password) throw new Error("password is required");
457
- const mnemonic = this.#data.mnemonics.find((s) => s.id === mnemonicId);
458
- if (!mnemonic) throw new Error("Mnemonic not found");
459
- const entropy = await decryptData(mnemonic.entropy, password);
460
- const seed = await (0, import_crypto3.entropyToSeed)(entropy, curve);
461
- const pair = (0, import_crypto3.deriveKeypair)(seed, derivationPath, curve);
462
- return pair.address;
463
- }
128
+ //#endregion
129
+ //#region src/keyring/Keyring.ts
130
+ var Keyring = class Keyring {
131
+ #data;
132
+ constructor(data) {
133
+ this.#data = structuredClone(data);
134
+ }
135
+ static create() {
136
+ return new Keyring({
137
+ passwordCheck: null,
138
+ mnemonics: [],
139
+ accounts: []
140
+ });
141
+ }
142
+ static load(data) {
143
+ if (!data.accounts || !data.mnemonics) throw new Error("Invalid data");
144
+ for (const account of data.accounts) if (account.type === "ledger-polkadot" && !account.curve) account.curve = "ed25519";
145
+ return new Keyring(data);
146
+ }
147
+ async checkPassword(password, reset = false) {
148
+ if (typeof password !== "string" || !password) throw new Error("password is required");
149
+ const passwordHash = oneWayHash(password);
150
+ const PASSWORD_CHECK_PHRASE = "PASSWORD_CHECK_PHRASE";
151
+ if (!this.#data.passwordCheck || reset) {
152
+ const bytes = _talismn_crypto.utf8.decode(PASSWORD_CHECK_PHRASE);
153
+ this.#data.passwordCheck = await encryptData(bytes, passwordHash);
154
+ } else try {
155
+ const bytes = await decryptData(this.#data.passwordCheck, passwordHash);
156
+ if (_talismn_crypto.utf8.encode(bytes) !== PASSWORD_CHECK_PHRASE) throw new Error("Invalid password");
157
+ } catch {
158
+ throw new Error("Invalid password");
159
+ }
160
+ }
161
+ /** Returns true if a password has been set on this keyring. */
162
+ hasPassword() {
163
+ return this.#data.passwordCheck !== null;
164
+ }
165
+ /**
166
+ * Verify a password against the keyring's passwordCheck blob.
167
+ * Returns true on success, false on wrong password.
168
+ * Throws if no password has been set (caller should check hasPassword() first).
169
+ */
170
+ async verifyPassword(password) {
171
+ if (!this.#data.passwordCheck) throw new Error("No password set — call hasPassword() before verifyPassword()");
172
+ try {
173
+ await this.checkPassword(password);
174
+ return true;
175
+ } catch {
176
+ return false;
177
+ }
178
+ }
179
+ /**
180
+ * Initialize the password on a fresh keyring that has no password set.
181
+ * Throws if a password is already set (use changePassword flow instead).
182
+ */
183
+ async initializePassword(password) {
184
+ if (this.#data.passwordCheck !== null) throw new Error("Password already set — cannot re-initialize");
185
+ await this.checkPassword(password, true);
186
+ }
187
+ toJson() {
188
+ return structuredClone(this.#data);
189
+ }
190
+ async export(password, jsonPassword) {
191
+ const keyring = new Keyring(structuredClone(this.#data));
192
+ for (const mnemonic of keyring.#data.mnemonics) mnemonic.entropy = await changeEncryptedDataPassword(mnemonic.entropy, password, jsonPassword);
193
+ for (const account of keyring.#data.accounts) if (account.type === "keypair") account.secretKey = await changeEncryptedDataPassword(account.secretKey, password, jsonPassword);
194
+ await keyring.checkPassword(jsonPassword, true);
195
+ return keyring.toJson();
196
+ }
197
+ getMnemonics() {
198
+ return this.#data.mnemonics.map(mnemonicFromStorage);
199
+ }
200
+ async addMnemonic({ name, mnemonic, confirmed }, password) {
201
+ if (typeof name !== "string" || !name) throw new Error("name is required");
202
+ if (typeof mnemonic !== "string") throw new Error("mnemonic is required");
203
+ if (typeof confirmed !== "boolean") throw new Error("confirmed is required");
204
+ if (!(0, _talismn_crypto.isValidMnemonic)(mnemonic)) throw new Error("Invalid mnemonic");
205
+ await this.checkPassword(password);
206
+ const entropy = (0, _talismn_crypto.mnemonicToEntropy)(mnemonic);
207
+ const id = oneWayHash(entropy);
208
+ if (this.#data.mnemonics.find((s) => s.id === id)) throw new Error("Mnemonic already exists");
209
+ const storage = {
210
+ id,
211
+ name,
212
+ entropy: await encryptData(entropy, password),
213
+ confirmed,
214
+ createdAt: Date.now()
215
+ };
216
+ this.#data.mnemonics.push(storage);
217
+ return mnemonicFromStorage(storage);
218
+ }
219
+ getMnemonic(id) {
220
+ const mnemonic = this.#data.mnemonics.find((s) => s.id === id);
221
+ return mnemonic ? mnemonicFromStorage(mnemonic) : null;
222
+ }
223
+ updateMnemonic(id, { name, confirmed }) {
224
+ const mnemonic = this.#data.mnemonics.find((s) => s.id === id);
225
+ if (!mnemonic) throw new Error("Mnemonic not found");
226
+ if (name !== void 0) {
227
+ if (typeof name !== "string" || !name) throw new Error("name must be a string");
228
+ mnemonic.name = name;
229
+ }
230
+ if (confirmed !== void 0) {
231
+ if (typeof confirmed !== "boolean") throw new Error("confirmed must be a boolean");
232
+ mnemonic.confirmed = confirmed;
233
+ }
234
+ return mnemonicFromStorage(mnemonic);
235
+ }
236
+ removeMnemonic(id) {
237
+ const index = this.#data.mnemonics.findIndex((mnemonic) => mnemonic.id === id);
238
+ if (index === -1) throw new Error("Mnemonic not found");
239
+ this.#data.mnemonics.splice(index, 1);
240
+ }
241
+ async getMnemonicText(id, password) {
242
+ const mnemonic = this.#data.mnemonics.find((s) => s.id === id);
243
+ if (!mnemonic) throw new Error("Mnemonic not found");
244
+ return (0, _talismn_crypto.entropyToMnemonic)(await decryptData(mnemonic.entropy, password));
245
+ }
246
+ getExistingMnemonicId(mnemonic) {
247
+ const entropy = (0, _talismn_crypto.mnemonicToEntropy)(mnemonic);
248
+ const mnemonicId = oneWayHash(entropy);
249
+ return this.#data.mnemonics.some((s) => s.id === mnemonicId) ? mnemonicId : null;
250
+ }
251
+ getAccounts() {
252
+ return this.#data.accounts.map(accountFromStorage);
253
+ }
254
+ getAccount(address) {
255
+ const account = this.#data.accounts.find((s) => (0, _talismn_crypto.isAddressEqual)(s.address, address));
256
+ return account ? accountFromStorage(account) : null;
257
+ }
258
+ updateAccount(address, { name, isPortfolio, genesisHash }) {
259
+ const account = this.#data.accounts.find((s) => s.address === address);
260
+ if (!account) throw new Error("Account not found");
261
+ if (name) {
262
+ if (typeof name !== "string" || !name) throw new Error("name is required");
263
+ account.name = name;
264
+ }
265
+ if (account.type === "watch-only" && isPortfolio !== void 0) {
266
+ if (typeof isPortfolio !== "boolean") throw new Error("isPortfolio must be a boolean");
267
+ account.isPortfolio = isPortfolio;
268
+ }
269
+ if (account.type === "contact") if (genesisHash) {
270
+ if (!isHexString(genesisHash)) throw new Error("genesisHash must be a hex string");
271
+ account.genesisHash = genesisHash;
272
+ } else delete account.genesisHash;
273
+ return accountFromStorage(account);
274
+ }
275
+ removeAccount(address) {
276
+ const index = this.#data.accounts.findIndex((s) => (0, _talismn_crypto.isAddressEqual)(s.address, address));
277
+ if (index === -1) throw new Error("Account not found");
278
+ this.#data.accounts.splice(index, 1);
279
+ }
280
+ addAccountExternal(options) {
281
+ const address = (0, _talismn_crypto.normalizeAddress)(options.address);
282
+ if (this.getAccount(address)) throw new Error("Account already exists");
283
+ const account = {
284
+ ...options,
285
+ address,
286
+ createdAt: Date.now()
287
+ };
288
+ if (!isAccountExternal(account)) throw new Error("Invalid account type");
289
+ this.#data.accounts.push(account);
290
+ return accountFromStorage(account);
291
+ }
292
+ /**
293
+ * Needs to be called before deriving an account from a mnemonic.
294
+ *
295
+ * This will ensure that it is present (or add it if possible) in the keyring before actually creating the account.
296
+ *
297
+ * @param options
298
+ * @param password
299
+ * @returns the id of the mnemonic
300
+ */
301
+ async ensureMnemonic(options, password) {
302
+ await this.checkPassword(password);
303
+ switch (options.type) {
304
+ case "new-mnemonic": {
305
+ const { mnemonic, mnemonicName: name, confirmed } = options;
306
+ if (typeof name !== "string" || !name) throw new Error("mnemonicName is required");
307
+ if (typeof confirmed !== "boolean") throw new Error("confirmed is required");
308
+ const mnemonicId = this.getExistingMnemonicId(mnemonic);
309
+ if (mnemonicId) return mnemonicId;
310
+ const { id } = await this.addMnemonic({
311
+ name,
312
+ mnemonic,
313
+ confirmed
314
+ }, password);
315
+ return id;
316
+ }
317
+ case "existing-mnemonic":
318
+ if (typeof options.mnemonicId !== "string" || !options.mnemonicId) throw new Error("mnemonicId must be a string");
319
+ return options.mnemonicId;
320
+ }
321
+ }
322
+ async addAccountDerive(options, password) {
323
+ await this.checkPassword(password);
324
+ const { curve, derivationPath, name } = options;
325
+ const mnemonicId = await this.ensureMnemonic(options, password);
326
+ const mnemonic = this.#data.mnemonics.find((s) => s.id === mnemonicId);
327
+ if (!mnemonic) throw new Error("Mnemonic not found");
328
+ const pair = (0, _talismn_crypto.deriveKeypair)(await (0, _talismn_crypto.entropyToSeed)(await decryptData(mnemonic.entropy, password), curve), derivationPath, curve);
329
+ if (this.getAccount(pair.address)) throw new Error("Account already exists");
330
+ const account = {
331
+ type: "keypair",
332
+ curve,
333
+ name,
334
+ address: (0, _talismn_crypto.normalizeAddress)(pair.address),
335
+ secretKey: await encryptData(pair.secretKey, password),
336
+ mnemonicId,
337
+ derivationPath,
338
+ createdAt: Date.now()
339
+ };
340
+ this.#data.accounts.push(account);
341
+ return accountFromStorage(account);
342
+ }
343
+ async addAccountKeypair({ curve, name, secretKey }, password) {
344
+ await this.checkPassword(password);
345
+ const address = (0, _talismn_crypto.addressFromPublicKey)((0, _talismn_crypto.getPublicKeyFromSecret)(secretKey, curve), (0, _talismn_crypto.addressEncodingFromCurve)(curve));
346
+ if (this.getAccount(address)) throw new Error("Account already exists");
347
+ const account = {
348
+ type: "keypair",
349
+ curve,
350
+ name,
351
+ address: (0, _talismn_crypto.normalizeAddress)(address),
352
+ secretKey: await encryptData(secretKey, password),
353
+ createdAt: Date.now()
354
+ };
355
+ this.#data.accounts.push(account);
356
+ return accountFromStorage(account);
357
+ }
358
+ getAccountSecretKey(address, password) {
359
+ if (typeof address !== "string" || !address) throw new Error("address is required");
360
+ if (typeof password !== "string" || !password) throw new Error("password is required");
361
+ const account = this.#data.accounts.find((a) => a.address === (0, _talismn_crypto.normalizeAddress)(address));
362
+ if (!account) throw new Error("Account not found");
363
+ if (account.type !== "keypair") throw new Error("Secret key unavailable");
364
+ return decryptData(account.secretKey, password);
365
+ }
366
+ async getDerivedAddress(mnemonicId, derivationPath, curve, password) {
367
+ if (typeof mnemonicId !== "string" || !mnemonicId) throw new Error("mnemonicId is required");
368
+ if (typeof password !== "string" || !password) throw new Error("password is required");
369
+ const mnemonic = this.#data.mnemonics.find((s) => s.id === mnemonicId);
370
+ if (!mnemonic) throw new Error("Mnemonic not found");
371
+ return (0, _talismn_crypto.deriveKeypair)(await (0, _talismn_crypto.entropyToSeed)(await decryptData(mnemonic.entropy, password), curve), derivationPath, curve).address;
372
+ }
464
373
  };
465
- var oneWayHash = (bytes) => {
466
- if (typeof bytes === "string") bytes = import_crypto3.utf8.decode(bytes);
467
- return import_crypto3.base58.encode((0, import_crypto3.blake3)(bytes));
374
+ const oneWayHash = (bytes) => {
375
+ if (typeof bytes === "string") bytes = _talismn_crypto.utf8.decode(bytes);
376
+ return _talismn_crypto.base58.encode((0, _talismn_crypto.blake3)(bytes));
468
377
  };
469
- var mnemonicFromStorage = (data) => {
470
- const copy = structuredClone(data);
471
- if ("entropy" in copy) delete copy.entropy;
472
- return Object.freeze(copy);
378
+ const mnemonicFromStorage = (data) => {
379
+ const copy = structuredClone(data);
380
+ if ("entropy" in copy) delete copy.entropy;
381
+ return Object.freeze(copy);
473
382
  };
474
- var accountFromStorage = (data) => {
475
- const copy = structuredClone(data);
476
- if ("secretKey" in copy) delete copy.secretKey;
477
- return Object.freeze(copy);
383
+ const accountFromStorage = (data) => {
384
+ const copy = structuredClone(data);
385
+ if ("secretKey" in copy) delete copy.secretKey;
386
+ return Object.freeze(copy);
478
387
  };
479
- // Annotate the CommonJS export names for ESM import in node:
480
- 0 && (module.exports = {
481
- Keyring,
482
- getAccountGenesisHash,
483
- getAccountPlatform,
484
- getAccountSignetUrl,
485
- isAccountAddressEthereum,
486
- isAccountAddressSs58,
487
- isAccountBitcoin,
488
- isAccountExternal,
489
- isAccountInTypes,
490
- isAccountLedgerPolkadot,
491
- isAccountLedgerPolkadotGeneric,
492
- isAccountLedgerPolkadotLegacy,
493
- isAccountNotContact,
494
- isAccountOfType,
495
- isAccountOwned,
496
- isAccountPlatformEthereum,
497
- isAccountPlatformPolkadot,
498
- isAccountPlatformSolana,
499
- isAccountPortfolio
500
- });
388
+ //#endregion
389
+ exports.Keyring = Keyring;
390
+ exports.getAccountGenesisHash = getAccountGenesisHash;
391
+ exports.getAccountPlatform = getAccountPlatform;
392
+ exports.getAccountSignetUrl = getAccountSignetUrl;
393
+ exports.isAccountAddressEthereum = isAccountAddressEthereum;
394
+ exports.isAccountAddressSs58 = isAccountAddressSs58;
395
+ exports.isAccountBitcoin = isAccountBitcoin;
396
+ exports.isAccountExternal = isAccountExternal;
397
+ exports.isAccountInTypes = isAccountInTypes;
398
+ exports.isAccountLedgerPolkadot = isAccountLedgerPolkadot;
399
+ exports.isAccountLedgerPolkadotGeneric = isAccountLedgerPolkadotGeneric;
400
+ exports.isAccountLedgerPolkadotLegacy = isAccountLedgerPolkadotLegacy;
401
+ exports.isAccountNotContact = isAccountNotContact;
402
+ exports.isAccountOfType = isAccountOfType;
403
+ exports.isAccountOwned = isAccountOwned;
404
+ exports.isAccountPlatformEthereum = isAccountPlatformEthereum;
405
+ exports.isAccountPlatformPolkadot = isAccountPlatformPolkadot;
406
+ exports.isAccountPlatformSolana = isAccountPlatformSolana;
407
+ exports.isAccountPortfolio = isAccountPortfolio;
408
+
501
409
  //# sourceMappingURL=index.js.map