@noosphere/crypto 0.1.0-alpha.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 ADDED
@@ -0,0 +1,512 @@
1
+ // src/KeystoreManager.ts
2
+ import { ethers } from "ethers";
3
+ import fs from "fs/promises";
4
+ import path from "path";
5
+ var KeystoreManager = class _KeystoreManager {
6
+ constructor(keystorePath, password) {
7
+ this.keystore = null;
8
+ this.keystorePath = keystorePath;
9
+ this.password = password;
10
+ }
11
+ /**
12
+ * Initialize a new keystore with an EOA
13
+ * @param privateKey - Private key of the EOA (agent's main wallet)
14
+ * @param provider - Ethereum provider
15
+ */
16
+ static async initialize(keystorePath, password, privateKey, provider) {
17
+ const wallet = new ethers.Wallet(privateKey, provider);
18
+ console.log("Encrypting EOA keystore...");
19
+ const eoaKeystore = await wallet.encrypt(password);
20
+ const keystore = {
21
+ version: "1.0.0",
22
+ eoa: {
23
+ address: wallet.address,
24
+ keystore: eoaKeystore
25
+ },
26
+ paymentWallets: {},
27
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
28
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
29
+ };
30
+ await fs.mkdir(path.dirname(keystorePath), { recursive: true });
31
+ await fs.writeFile(keystorePath, JSON.stringify(keystore, null, 2));
32
+ console.log(`\u2713 Keystore initialized: ${keystorePath}`);
33
+ console.log(` EOA Address: ${wallet.address}`);
34
+ const manager = new _KeystoreManager(keystorePath, password);
35
+ manager.keystore = keystore;
36
+ return manager;
37
+ }
38
+ /**
39
+ * Load existing keystore
40
+ */
41
+ async load() {
42
+ try {
43
+ const data = await fs.readFile(this.keystorePath, "utf-8");
44
+ this.keystore = JSON.parse(data);
45
+ console.log(`\u2713 Loaded keystore: ${this.keystorePath}`);
46
+ console.log(` EOA: ${this.keystore.eoa.address}`);
47
+ console.log(` Payment Wallets: ${Object.keys(this.keystore.paymentWallets).length}`);
48
+ } catch (error) {
49
+ if (error.code === "ENOENT") {
50
+ throw new Error(
51
+ `Keystore not found: ${this.keystorePath}
52
+ Initialize a new keystore with KeystoreManager.initialize()`
53
+ );
54
+ }
55
+ throw error;
56
+ }
57
+ }
58
+ /**
59
+ * Get the EOA wallet
60
+ */
61
+ async getEOA(provider) {
62
+ if (!this.keystore) {
63
+ throw new Error("Keystore not loaded. Call load() first.");
64
+ }
65
+ console.log("Decrypting EOA...");
66
+ const wallet = await ethers.Wallet.fromEncryptedJson(this.keystore.eoa.keystore, this.password);
67
+ return wallet.connect(provider);
68
+ }
69
+ /**
70
+ * Get EOA address without decrypting
71
+ */
72
+ getEOAAddress() {
73
+ if (!this.keystore) {
74
+ throw new Error("Keystore not loaded. Call load() first.");
75
+ }
76
+ return this.keystore.eoa.address;
77
+ }
78
+ /**
79
+ * Add a payment wallet to the keystore
80
+ * @param walletAddress - Address of the payment wallet
81
+ * @param privateKey - Private key of the payment wallet
82
+ * @param subscriptionId - Optional subscription ID this wallet is for
83
+ */
84
+ async addPaymentWallet(walletAddress, privateKey, subscriptionId, metadata) {
85
+ if (!this.keystore) {
86
+ throw new Error("Keystore not loaded. Call load() first.");
87
+ }
88
+ const encryptedKey = await this.encryptData(privateKey);
89
+ this.keystore.paymentWallets[walletAddress] = {
90
+ address: walletAddress,
91
+ privateKey: encryptedKey,
92
+ subscriptionId,
93
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
94
+ metadata
95
+ };
96
+ this.keystore.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
97
+ await this.save();
98
+ console.log(`\u2713 Added payment wallet: ${walletAddress}`);
99
+ if (subscriptionId) {
100
+ console.log(` Subscription ID: ${subscriptionId}`);
101
+ }
102
+ }
103
+ /**
104
+ * Get a payment wallet
105
+ */
106
+ async getPaymentWallet(walletAddress, provider) {
107
+ if (!this.keystore) {
108
+ throw new Error("Keystore not loaded. Call load() first.");
109
+ }
110
+ const walletData = this.keystore.paymentWallets[walletAddress];
111
+ if (!walletData) {
112
+ throw new Error(`Payment wallet not found: ${walletAddress}`);
113
+ }
114
+ const privateKey = await this.decryptData(walletData.privateKey);
115
+ const wallet = new ethers.Wallet(privateKey, provider);
116
+ if (wallet.address.toLowerCase() !== walletAddress.toLowerCase()) {
117
+ throw new Error("Decrypted wallet address mismatch");
118
+ }
119
+ return wallet;
120
+ }
121
+ /**
122
+ * List all payment wallet addresses
123
+ */
124
+ listPaymentWallets() {
125
+ if (!this.keystore) {
126
+ throw new Error("Keystore not loaded. Call load() first.");
127
+ }
128
+ return Object.values(this.keystore.paymentWallets).map((w) => ({
129
+ address: w.address,
130
+ subscriptionId: w.subscriptionId,
131
+ createdAt: w.createdAt,
132
+ metadata: w.metadata
133
+ }));
134
+ }
135
+ /**
136
+ * Remove a payment wallet
137
+ */
138
+ async removePaymentWallet(walletAddress) {
139
+ if (!this.keystore) {
140
+ throw new Error("Keystore not loaded. Call load() first.");
141
+ }
142
+ if (!this.keystore.paymentWallets[walletAddress]) {
143
+ throw new Error(`Payment wallet not found: ${walletAddress}`);
144
+ }
145
+ delete this.keystore.paymentWallets[walletAddress];
146
+ this.keystore.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
147
+ await this.save();
148
+ console.log(`\u2713 Removed payment wallet: ${walletAddress}`);
149
+ }
150
+ /**
151
+ * Get keystore info without decrypting
152
+ */
153
+ getInfo() {
154
+ if (!this.keystore) {
155
+ throw new Error("Keystore not loaded. Call load() first.");
156
+ }
157
+ return {
158
+ version: this.keystore.version,
159
+ eoaAddress: this.keystore.eoa.address,
160
+ paymentWalletCount: Object.keys(this.keystore.paymentWallets).length,
161
+ createdAt: this.keystore.createdAt,
162
+ updatedAt: this.keystore.updatedAt
163
+ };
164
+ }
165
+ /**
166
+ * Check if a payment wallet exists
167
+ */
168
+ hasPaymentWallet(walletAddress) {
169
+ if (!this.keystore) {
170
+ return false;
171
+ }
172
+ return walletAddress in this.keystore.paymentWallets;
173
+ }
174
+ /**
175
+ * Update EOA (re-encrypt with new password or new private key)
176
+ */
177
+ async updateEOA(newPrivateKey, provider) {
178
+ if (!this.keystore) {
179
+ throw new Error("Keystore not loaded. Call load() first.");
180
+ }
181
+ const wallet = new ethers.Wallet(newPrivateKey, provider);
182
+ console.log("Re-encrypting EOA...");
183
+ const newKeystore = await wallet.encrypt(this.password);
184
+ this.keystore.eoa = {
185
+ address: wallet.address,
186
+ keystore: newKeystore
187
+ };
188
+ this.keystore.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
189
+ await this.save();
190
+ console.log(`\u2713 Updated EOA: ${wallet.address}`);
191
+ }
192
+ /**
193
+ * Save keystore to disk
194
+ */
195
+ async save() {
196
+ if (!this.keystore) {
197
+ throw new Error("No keystore to save");
198
+ }
199
+ await fs.writeFile(this.keystorePath, JSON.stringify(this.keystore, null, 2));
200
+ }
201
+ /**
202
+ * Encrypt data using password
203
+ * Uses a simple base64 encoding for now - in production, use proper encryption
204
+ */
205
+ async encryptData(data) {
206
+ const encoded = Buffer.from(data).toString("base64");
207
+ return JSON.stringify({
208
+ version: "1.0",
209
+ _data: encoded
210
+ });
211
+ }
212
+ /**
213
+ * Decrypt data using password
214
+ */
215
+ async decryptData(encryptedData) {
216
+ const keystoreObj = JSON.parse(encryptedData);
217
+ if (!keystoreObj._data) {
218
+ throw new Error("Invalid encrypted data format");
219
+ }
220
+ return Buffer.from(keystoreObj._data, "base64").toString();
221
+ }
222
+ /**
223
+ * Export keystore for backup
224
+ */
225
+ async exportKeystore() {
226
+ if (!this.keystore) {
227
+ throw new Error("Keystore not loaded. Call load() first.");
228
+ }
229
+ return JSON.stringify(this.keystore, null, 2);
230
+ }
231
+ /**
232
+ * Import keystore from backup
233
+ */
234
+ static async importKeystore(keystorePath, password, keystoreJson) {
235
+ const keystore = JSON.parse(keystoreJson);
236
+ if (!keystore.version || !keystore.eoa || !keystore.paymentWallets) {
237
+ throw new Error("Invalid keystore format");
238
+ }
239
+ await fs.mkdir(path.dirname(keystorePath), { recursive: true });
240
+ await fs.writeFile(keystorePath, JSON.stringify(keystore, null, 2));
241
+ const manager = new _KeystoreManager(keystorePath, password);
242
+ manager.keystore = keystore;
243
+ console.log(`\u2713 Imported keystore: ${keystorePath}`);
244
+ console.log(` EOA: ${keystore.eoa.address}`);
245
+ console.log(` Payment Wallets: ${Object.keys(keystore.paymentWallets).length}`);
246
+ return manager;
247
+ }
248
+ /**
249
+ * Change password (re-encrypt all wallets)
250
+ */
251
+ async changePassword(oldPassword, newPassword, provider) {
252
+ if (oldPassword !== this.password) {
253
+ throw new Error("Old password is incorrect");
254
+ }
255
+ if (!this.keystore) {
256
+ throw new Error("Keystore not loaded. Call load() first.");
257
+ }
258
+ console.log("Changing password...");
259
+ const eoaWallet = await ethers.Wallet.fromEncryptedJson(
260
+ this.keystore.eoa.keystore,
261
+ oldPassword
262
+ );
263
+ const newEoaKeystore = await eoaWallet.encrypt(newPassword);
264
+ this.keystore.eoa.keystore = newEoaKeystore;
265
+ const walletAddresses = Object.keys(this.keystore.paymentWallets);
266
+ for (const address of walletAddresses) {
267
+ const walletData = this.keystore.paymentWallets[address];
268
+ const decryptedKey = await this.decryptData(walletData.privateKey);
269
+ this.password = newPassword;
270
+ const reEncrypted = await this.encryptData(decryptedKey);
271
+ walletData.privateKey = reEncrypted;
272
+ }
273
+ this.password = newPassword;
274
+ this.keystore.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
275
+ await this.save();
276
+ console.log("\u2713 Password changed successfully");
277
+ }
278
+ };
279
+
280
+ // src/WalletManager.ts
281
+ import { ethers as ethers2 } from "ethers";
282
+ import fs2 from "fs/promises";
283
+ import path2 from "path";
284
+ import { WalletFactoryAbi__factory } from "@noosphere/contracts";
285
+ var WalletManager = class _WalletManager {
286
+ constructor(privateKey, provider, keystoreManager) {
287
+ this.wallet = new ethers2.Wallet(privateKey, provider);
288
+ this.provider = provider;
289
+ this.keystoreManager = keystoreManager;
290
+ }
291
+ /**
292
+ * Initialize WalletManager from KeystoreManager
293
+ * This is the recommended way to create a WalletManager for production use
294
+ */
295
+ static async fromKeystoreManager(keystoreManager, provider) {
296
+ const wallet = await keystoreManager.getEOA(provider);
297
+ const manager = new _WalletManager(wallet.privateKey, provider, keystoreManager);
298
+ console.log("\u2713 WalletManager initialized from keystore");
299
+ return manager;
300
+ }
301
+ /**
302
+ * Get the agent's wallet address
303
+ */
304
+ getAddress() {
305
+ return this.wallet.address;
306
+ }
307
+ /**
308
+ * Get the wallet instance
309
+ */
310
+ getWallet() {
311
+ return this.wallet;
312
+ }
313
+ /**
314
+ * Generate deterministic payment wallet using HDNode derivation
315
+ * @param subscriptionId - Subscription ID to derive wallet for
316
+ */
317
+ async getDeterministicPaymentWallet(subscriptionId) {
318
+ const hdNode = ethers2.HDNodeWallet.fromPhrase(
319
+ await this.getMnemonic(),
320
+ void 0,
321
+ `m/44'/60'/0'/0/${subscriptionId.toString()}`
322
+ );
323
+ return hdNode.address;
324
+ }
325
+ /**
326
+ * Get or generate mnemonic for HD wallet derivation
327
+ */
328
+ async getMnemonic() {
329
+ const mnemonicPath = path2.join(process.cwd(), ".noosphere", "mnemonic.txt");
330
+ try {
331
+ const mnemonic = await fs2.readFile(mnemonicPath, "utf-8");
332
+ return mnemonic.trim();
333
+ } catch {
334
+ const wallet = ethers2.Wallet.createRandom();
335
+ const mnemonic = wallet.mnemonic.phrase;
336
+ await fs2.mkdir(path2.dirname(mnemonicPath), { recursive: true });
337
+ await fs2.writeFile(mnemonicPath, mnemonic);
338
+ console.log("Generated new mnemonic and saved to", mnemonicPath);
339
+ console.log("\u26A0\uFE0F IMPORTANT: Back up this mnemonic phrase securely!");
340
+ return mnemonic;
341
+ }
342
+ }
343
+ /**
344
+ * Sign EIP-712 typed data for delegated subscription creation
345
+ */
346
+ async signTypedData(domain, types, value) {
347
+ return this.wallet.signTypedData(domain, types, value);
348
+ }
349
+ /**
350
+ * Get current ETH balance
351
+ */
352
+ async getBalance() {
353
+ return this.provider.getBalance(this.wallet.address);
354
+ }
355
+ /**
356
+ * Get ERC20 token balance
357
+ */
358
+ async getTokenBalance(tokenAddress) {
359
+ const erc20Abi = ["function balanceOf(address owner) view returns (uint256)"];
360
+ const contract = new ethers2.Contract(tokenAddress, erc20Abi, this.provider);
361
+ return contract.balanceOf(this.wallet.address);
362
+ }
363
+ /**
364
+ * Load wallet from keystore file
365
+ */
366
+ static async fromKeystore(keystorePath, password, provider) {
367
+ const keystore = await fs2.readFile(keystorePath, "utf-8");
368
+ const wallet = await ethers2.Wallet.fromEncryptedJson(keystore, password);
369
+ return new _WalletManager(wallet.privateKey, provider);
370
+ }
371
+ /**
372
+ * Save wallet to encrypted keystore file
373
+ */
374
+ async toKeystore(password, outputPath) {
375
+ const keystore = await this.wallet.encrypt(password);
376
+ await fs2.mkdir(path2.dirname(outputPath), { recursive: true });
377
+ await fs2.writeFile(outputPath, keystore);
378
+ }
379
+ /**
380
+ * Create a new payment wallet using WalletFactory contract
381
+ * @param walletFactoryAddress - Address of the WalletFactory contract
382
+ * @param initialOwner - Address that will own the new wallet (typically subscription owner)
383
+ * @param subscriptionId - Optional subscription ID to associate with this wallet
384
+ * @returns Transaction receipt and new wallet address
385
+ */
386
+ async createPaymentWallet(walletFactoryAddress, initialOwner, subscriptionId) {
387
+ const walletFactory = WalletFactoryAbi__factory.connect(walletFactoryAddress, this.wallet);
388
+ console.log(`Creating payment wallet for owner: ${initialOwner}...`);
389
+ const tx = await walletFactory.createWallet(initialOwner);
390
+ const receipt = await tx.wait();
391
+ if (!receipt) {
392
+ throw new Error("Transaction receipt not available");
393
+ }
394
+ const event = receipt.logs.map((log) => {
395
+ try {
396
+ return walletFactory.interface.parseLog({
397
+ topics: [...log.topics],
398
+ data: log.data
399
+ });
400
+ } catch {
401
+ return null;
402
+ }
403
+ }).find((e) => e && e.name === "WalletCreated");
404
+ if (!event) {
405
+ throw new Error("WalletCreated event not found in transaction receipt");
406
+ }
407
+ const walletAddress = event.args.walletAddress;
408
+ console.log(`\u2713 Payment wallet created: ${walletAddress}`);
409
+ console.log(` Transaction: ${receipt.hash}`);
410
+ console.log(` \u26A0\uFE0F This is a smart contract wallet (not an EOA)`);
411
+ if (this.keystoreManager && subscriptionId) {
412
+ await this.keystoreManager.addPaymentWallet(
413
+ walletAddress,
414
+ "",
415
+ // Smart contract wallet has no private key
416
+ subscriptionId,
417
+ {
418
+ type: "SmartContract",
419
+ factoryAddress: walletFactoryAddress
420
+ }
421
+ );
422
+ console.log(` \u2713 Wallet metadata saved to keystore`);
423
+ }
424
+ return {
425
+ walletAddress,
426
+ txHash: receipt.hash
427
+ };
428
+ }
429
+ /**
430
+ * Create a new EOA payment wallet and save to keystore
431
+ * This creates a regular externally-owned account (EOA) wallet
432
+ * @param subscriptionId - Optional subscription ID to associate with this wallet
433
+ * @returns Wallet address and private key (for immediate use, then should be discarded)
434
+ */
435
+ async createEOAPaymentWallet(subscriptionId) {
436
+ const newWallet = ethers2.Wallet.createRandom();
437
+ console.log(`Creating EOA payment wallet: ${newWallet.address}...`);
438
+ if (this.keystoreManager) {
439
+ await this.keystoreManager.addPaymentWallet(
440
+ newWallet.address,
441
+ newWallet.privateKey,
442
+ subscriptionId,
443
+ {
444
+ type: "EOA",
445
+ createdBy: this.wallet.address
446
+ }
447
+ );
448
+ console.log(`\u2713 Payment wallet saved to keystore`);
449
+ } else {
450
+ console.warn("\u26A0\uFE0F KeystoreManager not available, wallet not saved");
451
+ }
452
+ return {
453
+ walletAddress: newWallet.address,
454
+ privateKey: newWallet.privateKey
455
+ };
456
+ }
457
+ /**
458
+ * Get a payment wallet from keystore
459
+ */
460
+ async getPaymentWallet(walletAddress) {
461
+ if (!this.keystoreManager) {
462
+ throw new Error("KeystoreManager not available");
463
+ }
464
+ return this.keystoreManager.getPaymentWallet(walletAddress, this.provider);
465
+ }
466
+ /**
467
+ * List all payment wallets in keystore
468
+ */
469
+ listPaymentWallets() {
470
+ if (!this.keystoreManager) {
471
+ return [];
472
+ }
473
+ return this.keystoreManager.listPaymentWallets();
474
+ }
475
+ /**
476
+ * Check if a wallet address was created by WalletFactory
477
+ * @param walletFactoryAddress - Address of the WalletFactory contract
478
+ * @param walletAddress - Wallet address to validate
479
+ * @returns True if wallet was created by this factory
480
+ */
481
+ async isValidWallet(walletFactoryAddress, walletAddress) {
482
+ const walletFactory = WalletFactoryAbi__factory.connect(walletFactoryAddress, this.provider);
483
+ return walletFactory.isValidWallet(walletAddress);
484
+ }
485
+ /**
486
+ * Fund a payment wallet with ETH
487
+ * @param walletAddress - Address of the wallet to fund
488
+ * @param amount - Amount in ETH as string (e.g., "0.1")
489
+ */
490
+ async fundWallet(walletAddress, amount) {
491
+ const tx = await this.wallet.sendTransaction({
492
+ to: walletAddress,
493
+ value: ethers2.parseEther(amount)
494
+ });
495
+ const receipt = await tx.wait();
496
+ console.log(`\u2713 Funded ${walletAddress} with ${amount} ETH`);
497
+ console.log(` Transaction: ${receipt?.hash}`);
498
+ return receipt?.hash || "";
499
+ }
500
+ /**
501
+ * Get balance of a payment wallet
502
+ * @param walletAddress - Address of the wallet to check
503
+ */
504
+ async getWalletBalance(walletAddress) {
505
+ return this.provider.getBalance(walletAddress);
506
+ }
507
+ };
508
+ export {
509
+ KeystoreManager,
510
+ WalletManager
511
+ };
512
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/KeystoreManager.ts","../src/WalletManager.ts"],"sourcesContent":["import { ethers } from 'ethers';\nimport fs from 'fs/promises';\nimport path from 'path';\nimport type { NoosphereKeystore, KeystoreInfo, PaymentWalletInfo } from './types';\n\n/**\n * KeystoreManager manages EOA and payment wallets in a single encrypted keystore file\n * This follows the Hub's keystore structure\n */\nexport class KeystoreManager {\n private keystorePath: string;\n private password: string;\n private keystore: NoosphereKeystore | null = null;\n\n constructor(keystorePath: string, password: string) {\n this.keystorePath = keystorePath;\n this.password = password;\n }\n\n /**\n * Initialize a new keystore with an EOA\n * @param privateKey - Private key of the EOA (agent's main wallet)\n * @param provider - Ethereum provider\n */\n static async initialize(\n keystorePath: string,\n password: string,\n privateKey: string,\n provider: ethers.Provider\n ): Promise<KeystoreManager> {\n const wallet = new ethers.Wallet(privateKey, provider);\n\n // Encrypt EOA keystore\n console.log('Encrypting EOA keystore...');\n const eoaKeystore = await wallet.encrypt(password);\n\n const keystore: NoosphereKeystore = {\n version: '1.0.0',\n eoa: {\n address: wallet.address,\n keystore: eoaKeystore,\n },\n paymentWallets: {},\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n\n // Save keystore\n await fs.mkdir(path.dirname(keystorePath), { recursive: true });\n await fs.writeFile(keystorePath, JSON.stringify(keystore, null, 2));\n\n console.log(`✓ Keystore initialized: ${keystorePath}`);\n console.log(` EOA Address: ${wallet.address}`);\n\n const manager = new KeystoreManager(keystorePath, password);\n manager.keystore = keystore;\n return manager;\n }\n\n /**\n * Load existing keystore\n */\n async load(): Promise<void> {\n try {\n const data = await fs.readFile(this.keystorePath, 'utf-8');\n this.keystore = JSON.parse(data);\n console.log(`✓ Loaded keystore: ${this.keystorePath}`);\n console.log(` EOA: ${this.keystore!.eoa.address}`);\n console.log(` Payment Wallets: ${Object.keys(this.keystore!.paymentWallets).length}`);\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n throw new Error(\n `Keystore not found: ${this.keystorePath}\\n` +\n 'Initialize a new keystore with KeystoreManager.initialize()'\n );\n }\n throw error;\n }\n }\n\n /**\n * Get the EOA wallet\n */\n async getEOA(provider: ethers.Provider): Promise<ethers.Wallet> {\n if (!this.keystore) {\n throw new Error('Keystore not loaded. Call load() first.');\n }\n\n console.log('Decrypting EOA...');\n const wallet = await ethers.Wallet.fromEncryptedJson(this.keystore.eoa.keystore, this.password);\n\n return wallet.connect(provider) as ethers.Wallet;\n }\n\n /**\n * Get EOA address without decrypting\n */\n getEOAAddress(): string {\n if (!this.keystore) {\n throw new Error('Keystore not loaded. Call load() first.');\n }\n return this.keystore.eoa.address;\n }\n\n /**\n * Add a payment wallet to the keystore\n * @param walletAddress - Address of the payment wallet\n * @param privateKey - Private key of the payment wallet\n * @param subscriptionId - Optional subscription ID this wallet is for\n */\n async addPaymentWallet(\n walletAddress: string,\n privateKey: string,\n subscriptionId?: string,\n metadata?: Record<string, any>\n ): Promise<void> {\n if (!this.keystore) {\n throw new Error('Keystore not loaded. Call load() first.');\n }\n\n // Encrypt private key\n const encryptedKey = await this.encryptData(privateKey);\n\n this.keystore.paymentWallets[walletAddress] = {\n address: walletAddress,\n privateKey: encryptedKey,\n subscriptionId,\n createdAt: new Date().toISOString(),\n metadata,\n };\n\n this.keystore.updatedAt = new Date().toISOString();\n\n await this.save();\n\n console.log(`✓ Added payment wallet: ${walletAddress}`);\n if (subscriptionId) {\n console.log(` Subscription ID: ${subscriptionId}`);\n }\n }\n\n /**\n * Get a payment wallet\n */\n async getPaymentWallet(walletAddress: string, provider: ethers.Provider): Promise<ethers.Wallet> {\n if (!this.keystore) {\n throw new Error('Keystore not loaded. Call load() first.');\n }\n\n const walletData = this.keystore.paymentWallets[walletAddress];\n if (!walletData) {\n throw new Error(`Payment wallet not found: ${walletAddress}`);\n }\n\n // Decrypt private key\n const privateKey = await this.decryptData(walletData.privateKey);\n const wallet = new ethers.Wallet(privateKey, provider);\n\n if (wallet.address.toLowerCase() !== walletAddress.toLowerCase()) {\n throw new Error('Decrypted wallet address mismatch');\n }\n\n return wallet;\n }\n\n /**\n * List all payment wallet addresses\n */\n listPaymentWallets(): PaymentWalletInfo[] {\n if (!this.keystore) {\n throw new Error('Keystore not loaded. Call load() first.');\n }\n\n return Object.values(this.keystore.paymentWallets).map((w) => ({\n address: w.address,\n subscriptionId: w.subscriptionId,\n createdAt: w.createdAt,\n metadata: w.metadata,\n }));\n }\n\n /**\n * Remove a payment wallet\n */\n async removePaymentWallet(walletAddress: string): Promise<void> {\n if (!this.keystore) {\n throw new Error('Keystore not loaded. Call load() first.');\n }\n\n if (!this.keystore.paymentWallets[walletAddress]) {\n throw new Error(`Payment wallet not found: ${walletAddress}`);\n }\n\n delete this.keystore.paymentWallets[walletAddress];\n this.keystore.updatedAt = new Date().toISOString();\n\n await this.save();\n\n console.log(`✓ Removed payment wallet: ${walletAddress}`);\n }\n\n /**\n * Get keystore info without decrypting\n */\n getInfo(): KeystoreInfo {\n if (!this.keystore) {\n throw new Error('Keystore not loaded. Call load() first.');\n }\n\n return {\n version: this.keystore.version,\n eoaAddress: this.keystore.eoa.address,\n paymentWalletCount: Object.keys(this.keystore.paymentWallets).length,\n createdAt: this.keystore.createdAt,\n updatedAt: this.keystore.updatedAt,\n };\n }\n\n /**\n * Check if a payment wallet exists\n */\n hasPaymentWallet(walletAddress: string): boolean {\n if (!this.keystore) {\n return false;\n }\n return walletAddress in this.keystore.paymentWallets;\n }\n\n /**\n * Update EOA (re-encrypt with new password or new private key)\n */\n async updateEOA(newPrivateKey: string, provider: ethers.Provider): Promise<void> {\n if (!this.keystore) {\n throw new Error('Keystore not loaded. Call load() first.');\n }\n\n const wallet = new ethers.Wallet(newPrivateKey, provider);\n\n console.log('Re-encrypting EOA...');\n const newKeystore = await wallet.encrypt(this.password);\n\n this.keystore.eoa = {\n address: wallet.address,\n keystore: newKeystore,\n };\n\n this.keystore.updatedAt = new Date().toISOString();\n\n await this.save();\n\n console.log(`✓ Updated EOA: ${wallet.address}`);\n }\n\n /**\n * Save keystore to disk\n */\n private async save(): Promise<void> {\n if (!this.keystore) {\n throw new Error('No keystore to save');\n }\n\n await fs.writeFile(this.keystorePath, JSON.stringify(this.keystore, null, 2));\n }\n\n /**\n * Encrypt data using password\n * Uses a simple base64 encoding for now - in production, use proper encryption\n */\n private async encryptData(data: string): Promise<string> {\n // For simplicity, we'll use base64 encoding\n // In production, this should use proper AES encryption with the password\n const encoded = Buffer.from(data).toString('base64');\n\n // Wrap in a simple structure\n return JSON.stringify({\n version: '1.0',\n _data: encoded,\n });\n }\n\n /**\n * Decrypt data using password\n */\n private async decryptData(encryptedData: string): Promise<string> {\n const keystoreObj = JSON.parse(encryptedData);\n if (!keystoreObj._data) {\n throw new Error('Invalid encrypted data format');\n }\n\n // Simple decryption - in production, use proper encryption\n // For now, we'll use a simpler approach with AES\n return Buffer.from(keystoreObj._data, 'base64').toString();\n }\n\n /**\n * Export keystore for backup\n */\n async exportKeystore(): Promise<string> {\n if (!this.keystore) {\n throw new Error('Keystore not loaded. Call load() first.');\n }\n\n return JSON.stringify(this.keystore, null, 2);\n }\n\n /**\n * Import keystore from backup\n */\n static async importKeystore(\n keystorePath: string,\n password: string,\n keystoreJson: string\n ): Promise<KeystoreManager> {\n const keystore: NoosphereKeystore = JSON.parse(keystoreJson);\n\n // Validate keystore format\n if (!keystore.version || !keystore.eoa || !keystore.paymentWallets) {\n throw new Error('Invalid keystore format');\n }\n\n // Save imported keystore\n await fs.mkdir(path.dirname(keystorePath), { recursive: true });\n await fs.writeFile(keystorePath, JSON.stringify(keystore, null, 2));\n\n const manager = new KeystoreManager(keystorePath, password);\n manager.keystore = keystore;\n\n console.log(`✓ Imported keystore: ${keystorePath}`);\n console.log(` EOA: ${keystore.eoa.address}`);\n console.log(` Payment Wallets: ${Object.keys(keystore.paymentWallets).length}`);\n\n return manager;\n }\n\n /**\n * Change password (re-encrypt all wallets)\n */\n async changePassword(\n oldPassword: string,\n newPassword: string,\n provider: ethers.Provider\n ): Promise<void> {\n if (oldPassword !== this.password) {\n throw new Error('Old password is incorrect');\n }\n\n if (!this.keystore) {\n throw new Error('Keystore not loaded. Call load() first.');\n }\n\n console.log('Changing password...');\n\n // Decrypt and re-encrypt EOA\n const eoaWallet = await ethers.Wallet.fromEncryptedJson(\n this.keystore.eoa.keystore,\n oldPassword\n );\n const newEoaKeystore = await eoaWallet.encrypt(newPassword);\n\n this.keystore.eoa.keystore = newEoaKeystore;\n\n // Re-encrypt all payment wallets\n const walletAddresses = Object.keys(this.keystore.paymentWallets);\n for (const address of walletAddresses) {\n const walletData = this.keystore.paymentWallets[address];\n const decryptedKey = await this.decryptData(walletData.privateKey);\n\n // Re-encrypt with new password\n this.password = newPassword;\n const reEncrypted = await this.encryptData(decryptedKey);\n walletData.privateKey = reEncrypted;\n }\n\n this.password = newPassword;\n this.keystore.updatedAt = new Date().toISOString();\n\n await this.save();\n\n console.log('✓ Password changed successfully');\n }\n}\n","import { ethers } from 'ethers';\nimport fs from 'fs/promises';\nimport path from 'path';\nimport { KeystoreManager } from './KeystoreManager';\nimport { WalletFactoryAbi__factory } from '@noosphere/contracts';\n\nexport class WalletManager {\n private wallet: ethers.Wallet;\n private provider: ethers.Provider;\n private keystoreManager?: KeystoreManager;\n\n constructor(privateKey: string, provider: ethers.Provider, keystoreManager?: KeystoreManager) {\n this.wallet = new ethers.Wallet(privateKey, provider);\n this.provider = provider;\n this.keystoreManager = keystoreManager;\n }\n\n /**\n * Initialize WalletManager from KeystoreManager\n * This is the recommended way to create a WalletManager for production use\n */\n static async fromKeystoreManager(\n keystoreManager: KeystoreManager,\n provider: ethers.Provider\n ): Promise<WalletManager> {\n const wallet = await keystoreManager.getEOA(provider);\n const manager = new WalletManager(wallet.privateKey, provider, keystoreManager);\n console.log('✓ WalletManager initialized from keystore');\n return manager;\n }\n\n /**\n * Get the agent's wallet address\n */\n getAddress(): string {\n return this.wallet.address;\n }\n\n /**\n * Get the wallet instance\n */\n getWallet(): ethers.Wallet {\n return this.wallet;\n }\n\n /**\n * Generate deterministic payment wallet using HDNode derivation\n * @param subscriptionId - Subscription ID to derive wallet for\n */\n async getDeterministicPaymentWallet(subscriptionId: bigint): Promise<string> {\n // Derive child wallet using subscription ID as path\n const hdNode = ethers.HDNodeWallet.fromPhrase(\n await this.getMnemonic(),\n undefined,\n `m/44'/60'/0'/0/${subscriptionId.toString()}`\n );\n\n return hdNode.address;\n }\n\n /**\n * Get or generate mnemonic for HD wallet derivation\n */\n private async getMnemonic(): Promise<string> {\n const mnemonicPath = path.join(process.cwd(), '.noosphere', 'mnemonic.txt');\n\n try {\n // Try to load existing mnemonic\n const mnemonic = await fs.readFile(mnemonicPath, 'utf-8');\n return mnemonic.trim();\n } catch {\n // Generate new mnemonic\n const wallet = ethers.Wallet.createRandom();\n const mnemonic = wallet.mnemonic!.phrase;\n\n // Save to file\n await fs.mkdir(path.dirname(mnemonicPath), { recursive: true });\n await fs.writeFile(mnemonicPath, mnemonic);\n\n console.log('Generated new mnemonic and saved to', mnemonicPath);\n console.log('⚠️ IMPORTANT: Back up this mnemonic phrase securely!');\n\n return mnemonic;\n }\n }\n\n /**\n * Sign EIP-712 typed data for delegated subscription creation\n */\n async signTypedData(\n domain: ethers.TypedDataDomain,\n types: Record<string, ethers.TypedDataField[]>,\n value: Record<string, any>\n ): Promise<string> {\n return this.wallet.signTypedData(domain, types, value);\n }\n\n /**\n * Get current ETH balance\n */\n async getBalance(): Promise<bigint> {\n return this.provider.getBalance(this.wallet.address);\n }\n\n /**\n * Get ERC20 token balance\n */\n async getTokenBalance(tokenAddress: string): Promise<bigint> {\n const erc20Abi = ['function balanceOf(address owner) view returns (uint256)'];\n\n const contract = new ethers.Contract(tokenAddress, erc20Abi, this.provider);\n return contract.balanceOf(this.wallet.address);\n }\n\n /**\n * Load wallet from keystore file\n */\n static async fromKeystore(\n keystorePath: string,\n password: string,\n provider: ethers.Provider\n ): Promise<WalletManager> {\n const keystore = await fs.readFile(keystorePath, 'utf-8');\n const wallet = await ethers.Wallet.fromEncryptedJson(keystore, password);\n return new WalletManager(wallet.privateKey, provider);\n }\n\n /**\n * Save wallet to encrypted keystore file\n */\n async toKeystore(password: string, outputPath: string): Promise<void> {\n const keystore = await this.wallet.encrypt(password);\n await fs.mkdir(path.dirname(outputPath), { recursive: true });\n await fs.writeFile(outputPath, keystore);\n }\n\n /**\n * Create a new payment wallet using WalletFactory contract\n * @param walletFactoryAddress - Address of the WalletFactory contract\n * @param initialOwner - Address that will own the new wallet (typically subscription owner)\n * @param subscriptionId - Optional subscription ID to associate with this wallet\n * @returns Transaction receipt and new wallet address\n */\n async createPaymentWallet(\n walletFactoryAddress: string,\n initialOwner: string,\n subscriptionId?: string\n ): Promise<{ walletAddress: string; txHash: string }> {\n // Use TypeChain-generated factory from @noosphere/contracts\n const walletFactory = WalletFactoryAbi__factory.connect(walletFactoryAddress, this.wallet);\n\n console.log(`Creating payment wallet for owner: ${initialOwner}...`);\n\n // Call createWallet with type-safe method\n const tx = await walletFactory.createWallet(initialOwner);\n const receipt = await tx.wait();\n\n if (!receipt) {\n throw new Error('Transaction receipt not available');\n }\n\n // Parse WalletCreated event using TypeChain-generated interface\n const event = receipt.logs\n .map((log) => {\n try {\n return walletFactory.interface.parseLog({\n topics: [...log.topics],\n data: log.data,\n });\n } catch {\n return null;\n }\n })\n .find((e) => e && e.name === 'WalletCreated');\n\n if (!event) {\n throw new Error('WalletCreated event not found in transaction receipt');\n }\n\n const walletAddress = event.args.walletAddress;\n\n console.log(`✓ Payment wallet created: ${walletAddress}`);\n console.log(` Transaction: ${receipt.hash}`);\n\n // Note: We don't have the private key for WalletFactory-created wallets\n // These are smart contract wallets, not EOAs\n // They are controlled through the WalletFactory contract\n console.log(` ⚠️ This is a smart contract wallet (not an EOA)`);\n\n // Save to keystore if available\n if (this.keystoreManager && subscriptionId) {\n await this.keystoreManager.addPaymentWallet(\n walletAddress,\n '', // Smart contract wallet has no private key\n subscriptionId,\n {\n type: 'SmartContract',\n factoryAddress: walletFactoryAddress,\n }\n );\n console.log(` ✓ Wallet metadata saved to keystore`);\n }\n\n return {\n walletAddress,\n txHash: receipt.hash,\n };\n }\n\n /**\n * Create a new EOA payment wallet and save to keystore\n * This creates a regular externally-owned account (EOA) wallet\n * @param subscriptionId - Optional subscription ID to associate with this wallet\n * @returns Wallet address and private key (for immediate use, then should be discarded)\n */\n async createEOAPaymentWallet(\n subscriptionId?: string\n ): Promise<{ walletAddress: string; privateKey: string }> {\n // Generate new wallet\n const newWallet = ethers.Wallet.createRandom();\n\n console.log(`Creating EOA payment wallet: ${newWallet.address}...`);\n\n // Save to keystore if available\n if (this.keystoreManager) {\n await this.keystoreManager.addPaymentWallet(\n newWallet.address,\n newWallet.privateKey,\n subscriptionId,\n {\n type: 'EOA',\n createdBy: this.wallet.address,\n }\n );\n console.log(`✓ Payment wallet saved to keystore`);\n } else {\n console.warn('⚠️ KeystoreManager not available, wallet not saved');\n }\n\n return {\n walletAddress: newWallet.address,\n privateKey: newWallet.privateKey,\n };\n }\n\n /**\n * Get a payment wallet from keystore\n */\n async getPaymentWallet(walletAddress: string): Promise<ethers.Wallet> {\n if (!this.keystoreManager) {\n throw new Error('KeystoreManager not available');\n }\n\n return this.keystoreManager.getPaymentWallet(walletAddress, this.provider);\n }\n\n /**\n * List all payment wallets in keystore\n */\n listPaymentWallets(): Array<{ address: string; subscriptionId?: string }> {\n if (!this.keystoreManager) {\n return [];\n }\n\n return this.keystoreManager.listPaymentWallets();\n }\n\n /**\n * Check if a wallet address was created by WalletFactory\n * @param walletFactoryAddress - Address of the WalletFactory contract\n * @param walletAddress - Wallet address to validate\n * @returns True if wallet was created by this factory\n */\n async isValidWallet(walletFactoryAddress: string, walletAddress: string): Promise<boolean> {\n // Use TypeChain-generated factory from @noosphere/contracts\n const walletFactory = WalletFactoryAbi__factory.connect(walletFactoryAddress, this.provider);\n\n return walletFactory.isValidWallet(walletAddress);\n }\n\n /**\n * Fund a payment wallet with ETH\n * @param walletAddress - Address of the wallet to fund\n * @param amount - Amount in ETH as string (e.g., \"0.1\")\n */\n async fundWallet(walletAddress: string, amount: string): Promise<string> {\n const tx = await this.wallet.sendTransaction({\n to: walletAddress,\n value: ethers.parseEther(amount),\n });\n\n const receipt = await tx.wait();\n console.log(`✓ Funded ${walletAddress} with ${amount} ETH`);\n console.log(` Transaction: ${receipt?.hash}`);\n\n return receipt?.hash || '';\n }\n\n /**\n * Get balance of a payment wallet\n * @param walletAddress - Address of the wallet to check\n */\n async getWalletBalance(walletAddress: string): Promise<bigint> {\n return this.provider.getBalance(walletAddress);\n }\n}\n"],"mappings":";AAAA,SAAS,cAAc;AACvB,OAAO,QAAQ;AACf,OAAO,UAAU;AAOV,IAAM,kBAAN,MAAM,iBAAgB;AAAA,EAK3B,YAAY,cAAsB,UAAkB;AAFp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M,KAAK,OAAO,gBAAgB;AAAA,MAC3C,IAAI;AAAA,MACJ,OAAOA,QAAO,WAAW,MAAM;AAAA,IACjC,CAAC;AAED,UAAM,UAAU,MAAM,GAAG,KAAK;AAC9B,YAAQ,IAAI,iBAAY,aAAa,SAAS,MAAM,MAAM;AAC1D,YAAQ,IAAI,kBAAkB,SAAS,IAAI,EAAE;AAE7C,WAAO,SAAS,QAAQ;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,iBAAiB,eAAwC;AAC7D,WAAO,KAAK,SAAS,WAAW,aAAa;AAAA,EAC/C;AACF;","names":["ethers","fs","path"]}
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@noosphere/crypto",
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "Cryptographic utilities and wallet management for Noosphere SDK",
5
+ "main": "dist/index.cjs",
6
+ "module": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "require": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.cjs"
13
+ },
14
+ "import": {
15
+ "types": "./dist/index.d.mts",
16
+ "default": "./dist/index.js"
17
+ }
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "scripts": {
24
+ "build": "tsup",
25
+ "test": "jest",
26
+ "lint": "eslint src --ext .ts",
27
+ "format": "prettier --write \"src/**/*.ts\"",
28
+ "clean": "rm -rf dist",
29
+ "prepublishOnly": "npm run build"
30
+ },
31
+ "keywords": [
32
+ "noosphere",
33
+ "crypto",
34
+ "wallet",
35
+ "keystore",
36
+ "ethereum"
37
+ ],
38
+ "author": "Noosphere Team",
39
+ "license": "MIT",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "https://github.com/hpp-io/noosphere-sdk.git",
43
+ "directory": "packages/crypto"
44
+ },
45
+ "bugs": {
46
+ "url": "https://github.com/hpp-io/noosphere-sdk/issues"
47
+ },
48
+ "homepage": "https://github.com/hpp-io/noosphere-sdk/tree/main/packages/crypto#readme",
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "dependencies": {
53
+ "@noosphere/contracts": "^0.1.0",
54
+ "ethers": "^6.13.0"
55
+ },
56
+ "devDependencies": {
57
+ "@types/node": "^22.0.0",
58
+ "@types/jest": "^29.5.0",
59
+ "jest": "^29.7.0",
60
+ "ts-jest": "^29.1.0",
61
+ "typescript": "^5.5.0"
62
+ }
63
+ }