pwc-sdk-wallet 0.6.3

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 (46) hide show
  1. package/README.md +2062 -0
  2. package/dist/Vault.d.ts +493 -0
  3. package/dist/Vault.js +1090 -0
  4. package/dist/chain/ChainService.d.ts +84 -0
  5. package/dist/chain/ChainService.js +136 -0
  6. package/dist/chain/SolanaChainService.d.ts +94 -0
  7. package/dist/chain/SolanaChainService.js +167 -0
  8. package/dist/config/chains.d.ts +233 -0
  9. package/dist/config/chains.js +285 -0
  10. package/dist/config/constants.d.ts +102 -0
  11. package/dist/config/constants.js +109 -0
  12. package/dist/config/environment.d.ts +46 -0
  13. package/dist/config/environment.js +114 -0
  14. package/dist/config/gas.d.ts +107 -0
  15. package/dist/config/gas.js +123 -0
  16. package/dist/crypto/EncryptionService.d.ts +74 -0
  17. package/dist/crypto/EncryptionService.js +178 -0
  18. package/dist/index.d.ts +22 -0
  19. package/dist/index.js +96 -0
  20. package/dist/keyrings/HDKeyring.d.ts +72 -0
  21. package/dist/keyrings/HDKeyring.js +156 -0
  22. package/dist/keyrings/SimpleKeyring.d.ts +31 -0
  23. package/dist/keyrings/SimpleKeyring.js +49 -0
  24. package/dist/keyrings/SolanaKeyring.d.ts +71 -0
  25. package/dist/keyrings/SolanaKeyring.js +159 -0
  26. package/dist/services/BatchProcessor.d.ts +42 -0
  27. package/dist/services/BatchProcessor.js +188 -0
  28. package/dist/services/MultiTransferService.d.ts +78 -0
  29. package/dist/services/MultiTransferService.js +252 -0
  30. package/dist/services/QRCodeService.d.ts +193 -0
  31. package/dist/services/QRCodeService.js +299 -0
  32. package/dist/services/TokenUtils.d.ts +307 -0
  33. package/dist/services/TokenUtils.js +429 -0
  34. package/dist/services/nft/MetadataResolver.d.ts +57 -0
  35. package/dist/services/nft/MetadataResolver.js +162 -0
  36. package/dist/services/nft/NFTAPIService.d.ts +53 -0
  37. package/dist/services/nft/NFTAPIService.js +122 -0
  38. package/dist/services/nft/NFTService.d.ts +241 -0
  39. package/dist/services/nft/NFTService.js +910 -0
  40. package/dist/types/multiTransfer.d.ts +68 -0
  41. package/dist/types/multiTransfer.js +2 -0
  42. package/dist/types/nft/index.d.ts +68 -0
  43. package/dist/types/nft/index.js +2 -0
  44. package/dist/types/nft.d.ts +265 -0
  45. package/dist/types/nft.js +6 -0
  46. package/package.json +70 -0
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.EncryptionService = void 0;
37
+ const CryptoJS = __importStar(require("crypto-js"));
38
+ const bip39 = __importStar(require("bip39"));
39
+ const bip32_1 = require("bip32");
40
+ const ecc = __importStar(require("@bitcoinerlab/secp256k1"));
41
+ const buffer_1 = require("buffer");
42
+ const chains_1 = require("../config/chains");
43
+ const constants_1 = require("../config/constants");
44
+ const bip32 = (0, bip32_1.BIP32Factory)(ecc);
45
+ const SALT_LENGTH = constants_1.SECURITY_CONFIG.SALT_LENGTH;
46
+ const KEY_LENGTH = constants_1.SECURITY_CONFIG.AES_KEY_SIZE / 8; // Convert bits to bytes
47
+ const IV_LENGTH = constants_1.SECURITY_CONFIG.IV_LENGTH;
48
+ /**
49
+ * Service providing cryptographic operations including mnemonic generation,
50
+ * encryption/decryption, and key derivation for the wallet SDK.
51
+ */
52
+ class EncryptionService {
53
+ /**
54
+ * Generates a cryptographically secure mnemonic phrase.
55
+ * @returns A 24-word mnemonic phrase following BIP-39 standard
56
+ */
57
+ static generateMnemonic() {
58
+ return bip39.generateMnemonic(256);
59
+ }
60
+ /**
61
+ * Validates a mnemonic phrase to ensure it's properly formatted and contains valid words.
62
+ * @param mnemonic - The mnemonic phrase to validate (12, 15, 18, 21, or 24 words)
63
+ * @returns True if the mnemonic is valid, false otherwise
64
+ */
65
+ static validateMnemonic(mnemonic) {
66
+ return bip39.validateMnemonic(mnemonic);
67
+ }
68
+ /**
69
+ * Encrypts data using AES-256-CBC with PBKDF2 key derivation.
70
+ * @param data - The plaintext data to encrypt
71
+ * @param password - The password to use for key derivation
72
+ * @returns Promise resolving to the encrypted data structure
73
+ * @throws Error if encryption fails
74
+ */
75
+ static async encrypt(data, password) {
76
+ const salt = CryptoJS.lib.WordArray.random(SALT_LENGTH);
77
+ const iv = CryptoJS.lib.WordArray.random(IV_LENGTH);
78
+ const key = CryptoJS.PBKDF2(password, salt, {
79
+ keySize: KEY_LENGTH,
80
+ iterations: (0, constants_1.getPBKDF2Iterations)(),
81
+ hasher: CryptoJS.algo.SHA256,
82
+ });
83
+ const encrypted = CryptoJS.AES.encrypt(data, key, {
84
+ iv: iv,
85
+ mode: CryptoJS.mode.CBC,
86
+ padding: CryptoJS.pad.Pkcs7,
87
+ });
88
+ return {
89
+ encryptedData: encrypted.toString(),
90
+ iv: CryptoJS.enc.Base64.stringify(iv),
91
+ salt: CryptoJS.enc.Base64.stringify(salt),
92
+ };
93
+ }
94
+ /**
95
+ * Decrypts data that was encrypted using the encrypt method.
96
+ * @param encryptedData - The encrypted data structure containing data, iv, and salt
97
+ * @param password - The password used for the original encryption
98
+ * @returns Promise resolving to the decrypted plaintext data
99
+ * @throws Error if decryption fails due to incorrect password or corrupted data
100
+ */
101
+ static async decrypt(encryptedData, password) {
102
+ const salt = CryptoJS.enc.Base64.parse(encryptedData.salt);
103
+ const iv = CryptoJS.enc.Base64.parse(encryptedData.iv);
104
+ const key = CryptoJS.PBKDF2(password, salt, {
105
+ keySize: KEY_LENGTH,
106
+ iterations: (0, constants_1.getPBKDF2Iterations)(),
107
+ hasher: CryptoJS.algo.SHA256,
108
+ });
109
+ const decrypted = CryptoJS.AES.decrypt(encryptedData.encryptedData, key, {
110
+ iv: iv,
111
+ mode: CryptoJS.mode.CBC,
112
+ padding: CryptoJS.pad.Pkcs7,
113
+ });
114
+ const decryptedText = decrypted.toString(CryptoJS.enc.Utf8);
115
+ if (!decryptedText) {
116
+ throw new Error("Decryption failed. Invalid password or corrupted data.");
117
+ }
118
+ return decryptedText;
119
+ }
120
+ /**
121
+ * Converts a mnemonic phrase to a seed buffer using PBKDF2.
122
+ * @param mnemonic - The mnemonic phrase to convert
123
+ * @returns Promise resolving to the seed buffer
124
+ */
125
+ static async mnemonicToSeed(mnemonic) {
126
+ return bip39.mnemonicToSeed(mnemonic);
127
+ }
128
+ /**
129
+ * Derives a private key from a seed using BIP-32 derivation.
130
+ * @param seed - The seed buffer to derive from
131
+ * @param path - The derivation path to use (defaults to EVM path)
132
+ * @returns Promise resolving to the derived private key buffer
133
+ * @throws Error if private key derivation fails
134
+ */
135
+ static async derivePrivateKey(seed, path = chains_1.DERIVATION_PATHS.EVM) {
136
+ const root = bip32.fromSeed(seed);
137
+ const child = root.derivePath(path);
138
+ if (!child.privateKey) {
139
+ throw new Error('Could not derive private key.');
140
+ }
141
+ return buffer_1.Buffer.from(child.privateKey);
142
+ }
143
+ /**
144
+ * Attempts to clear sensitive data from memory.
145
+ * Note: JavaScript doesn't guarantee memory clearing, but this helps reduce exposure.
146
+ * @param data - The sensitive data to clear (string or buffer)
147
+ */
148
+ static clearSensitiveData(data) {
149
+ if (typeof data === 'string') {
150
+ // For strings, we can't directly clear memory, but we can help GC
151
+ // by removing references and using setTimeout to delay cleanup
152
+ setTimeout(() => {
153
+ // This helps reduce the time sensitive data stays in memory
154
+ }, 0);
155
+ }
156
+ else if (buffer_1.Buffer.isBuffer(data)) {
157
+ // For buffers, we can fill with zeros
158
+ data.fill(0);
159
+ }
160
+ }
161
+ /**
162
+ * Creates a temporary copy of sensitive data that gets cleared after use.
163
+ * This is a security measure to minimize the time sensitive data stays in memory.
164
+ * @param data - The sensitive data to use temporarily
165
+ * @param callback - Function to execute with the temporary data
166
+ * @returns The result of the callback function
167
+ */
168
+ static withTemporaryData(data, callback) {
169
+ try {
170
+ const result = callback(data);
171
+ return result;
172
+ }
173
+ finally {
174
+ this.clearSensitiveData(data);
175
+ }
176
+ }
177
+ }
178
+ exports.EncryptionService = EncryptionService;
@@ -0,0 +1,22 @@
1
+ export { Vault, type VaultConfig } from './Vault';
2
+ export type { Account } from './Vault';
3
+ export type { ChainId, ChainConfig } from './config/chains';
4
+ export type { EncryptedData } from './crypto/EncryptionService';
5
+ export type { Token } from './chain/ChainService';
6
+ export type { Recipient, MultiTransferOptions, MultiTransferResult, BatchResult, ValidationResult } from './types/multiTransfer';
7
+ export type { QRCodeData, WalletImportData, TransactionData } from './services/QRCodeService';
8
+ export { SUPPORTED_CHAINS, DERIVATION_PATHS, registerCustomChain, overrideChain, overrideChains, getChainConfig, setupChainConfigs, getAllAvailableChains, clearCustomChains, clearOverrides, clearOverride, getCustomChains, getOverrides, setGlobalRPCConfig, setGlobalExplorerConfig, clearGlobalConfigs } from './config/chains';
9
+ export { GAS_CONFIG, NETWORK_GAS_CONFIG, getNetworkGasConfig, calculateOptimalGasPrice, setGlobalGasConfig, setGlobalNetworkGasConfig, getGasConfig, clearGlobalGasConfigs } from './config/gas';
10
+ export { VANITY_WALLET_CONFIG, SECURITY_CONFIG, NETWORK_CONFIG, CACHE_CONFIG, VALIDATION_CONFIG } from './config/constants';
11
+ export { getEnvironmentConfig, validateEnvironmentConfig, getEnvVar, getEnvVarNumber, getEnvVarBigInt, getEnvVarBoolean } from './config/environment';
12
+ export { HDKeyring } from './keyrings/HDKeyring';
13
+ export { SimpleKeyring } from './keyrings/SimpleKeyring';
14
+ export { SolanaKeyring } from './keyrings/SolanaKeyring';
15
+ export { ChainService } from './chain/ChainService';
16
+ export { SolanaChainService } from './chain/SolanaChainService';
17
+ export { EncryptionService } from './crypto/EncryptionService';
18
+ export { MultiTransferService } from './services/MultiTransferService';
19
+ export { BatchProcessor } from './services/BatchProcessor';
20
+ export { QRCodeService } from './services/QRCodeService';
21
+ export * from './services/TokenUtils';
22
+ export * from './services/nft/NFTService';
package/dist/index.js ADDED
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ // --- Main SDK Exports ---
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
16
+ };
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.QRCodeService = exports.BatchProcessor = exports.MultiTransferService = exports.EncryptionService = exports.SolanaChainService = exports.ChainService = exports.SolanaKeyring = exports.SimpleKeyring = exports.HDKeyring = exports.getEnvVarBoolean = exports.getEnvVarBigInt = exports.getEnvVarNumber = exports.getEnvVar = exports.validateEnvironmentConfig = exports.getEnvironmentConfig = exports.VALIDATION_CONFIG = exports.CACHE_CONFIG = exports.NETWORK_CONFIG = exports.SECURITY_CONFIG = exports.VANITY_WALLET_CONFIG = exports.clearGlobalGasConfigs = exports.getGasConfig = exports.setGlobalNetworkGasConfig = exports.setGlobalGasConfig = exports.calculateOptimalGasPrice = exports.getNetworkGasConfig = exports.NETWORK_GAS_CONFIG = exports.GAS_CONFIG = exports.clearGlobalConfigs = exports.setGlobalExplorerConfig = exports.setGlobalRPCConfig = exports.getOverrides = exports.getCustomChains = exports.clearOverride = exports.clearOverrides = exports.clearCustomChains = exports.getAllAvailableChains = exports.setupChainConfigs = exports.getChainConfig = exports.overrideChains = exports.overrideChain = exports.registerCustomChain = exports.DERIVATION_PATHS = exports.SUPPORTED_CHAINS = exports.Vault = void 0;
19
+ // The primary `Vault` class is the main entry point for interacting with the SDK.
20
+ var Vault_1 = require("./Vault");
21
+ Object.defineProperty(exports, "Vault", { enumerable: true, get: function () { return Vault_1.Vault; } });
22
+ // --- Configuration ---
23
+ // Chain configuration exports
24
+ var chains_1 = require("./config/chains");
25
+ Object.defineProperty(exports, "SUPPORTED_CHAINS", { enumerable: true, get: function () { return chains_1.SUPPORTED_CHAINS; } });
26
+ Object.defineProperty(exports, "DERIVATION_PATHS", { enumerable: true, get: function () { return chains_1.DERIVATION_PATHS; } });
27
+ Object.defineProperty(exports, "registerCustomChain", { enumerable: true, get: function () { return chains_1.registerCustomChain; } });
28
+ Object.defineProperty(exports, "overrideChain", { enumerable: true, get: function () { return chains_1.overrideChain; } });
29
+ Object.defineProperty(exports, "overrideChains", { enumerable: true, get: function () { return chains_1.overrideChains; } });
30
+ Object.defineProperty(exports, "getChainConfig", { enumerable: true, get: function () { return chains_1.getChainConfig; } });
31
+ Object.defineProperty(exports, "setupChainConfigs", { enumerable: true, get: function () { return chains_1.setupChainConfigs; } });
32
+ Object.defineProperty(exports, "getAllAvailableChains", { enumerable: true, get: function () { return chains_1.getAllAvailableChains; } });
33
+ Object.defineProperty(exports, "clearCustomChains", { enumerable: true, get: function () { return chains_1.clearCustomChains; } });
34
+ Object.defineProperty(exports, "clearOverrides", { enumerable: true, get: function () { return chains_1.clearOverrides; } });
35
+ Object.defineProperty(exports, "clearOverride", { enumerable: true, get: function () { return chains_1.clearOverride; } });
36
+ Object.defineProperty(exports, "getCustomChains", { enumerable: true, get: function () { return chains_1.getCustomChains; } });
37
+ Object.defineProperty(exports, "getOverrides", { enumerable: true, get: function () { return chains_1.getOverrides; } });
38
+ Object.defineProperty(exports, "setGlobalRPCConfig", { enumerable: true, get: function () { return chains_1.setGlobalRPCConfig; } });
39
+ Object.defineProperty(exports, "setGlobalExplorerConfig", { enumerable: true, get: function () { return chains_1.setGlobalExplorerConfig; } });
40
+ Object.defineProperty(exports, "clearGlobalConfigs", { enumerable: true, get: function () { return chains_1.clearGlobalConfigs; } });
41
+ // Gas configuration exports
42
+ var gas_1 = require("./config/gas");
43
+ Object.defineProperty(exports, "GAS_CONFIG", { enumerable: true, get: function () { return gas_1.GAS_CONFIG; } });
44
+ Object.defineProperty(exports, "NETWORK_GAS_CONFIG", { enumerable: true, get: function () { return gas_1.NETWORK_GAS_CONFIG; } });
45
+ Object.defineProperty(exports, "getNetworkGasConfig", { enumerable: true, get: function () { return gas_1.getNetworkGasConfig; } });
46
+ Object.defineProperty(exports, "calculateOptimalGasPrice", { enumerable: true, get: function () { return gas_1.calculateOptimalGasPrice; } });
47
+ Object.defineProperty(exports, "setGlobalGasConfig", { enumerable: true, get: function () { return gas_1.setGlobalGasConfig; } });
48
+ Object.defineProperty(exports, "setGlobalNetworkGasConfig", { enumerable: true, get: function () { return gas_1.setGlobalNetworkGasConfig; } });
49
+ Object.defineProperty(exports, "getGasConfig", { enumerable: true, get: function () { return gas_1.getGasConfig; } });
50
+ Object.defineProperty(exports, "clearGlobalGasConfigs", { enumerable: true, get: function () { return gas_1.clearGlobalGasConfigs; } });
51
+ // Constants exports
52
+ var constants_1 = require("./config/constants");
53
+ Object.defineProperty(exports, "VANITY_WALLET_CONFIG", { enumerable: true, get: function () { return constants_1.VANITY_WALLET_CONFIG; } });
54
+ Object.defineProperty(exports, "SECURITY_CONFIG", { enumerable: true, get: function () { return constants_1.SECURITY_CONFIG; } });
55
+ Object.defineProperty(exports, "NETWORK_CONFIG", { enumerable: true, get: function () { return constants_1.NETWORK_CONFIG; } });
56
+ Object.defineProperty(exports, "CACHE_CONFIG", { enumerable: true, get: function () { return constants_1.CACHE_CONFIG; } });
57
+ Object.defineProperty(exports, "VALIDATION_CONFIG", { enumerable: true, get: function () { return constants_1.VALIDATION_CONFIG; } });
58
+ // Environment configuration exports
59
+ var environment_1 = require("./config/environment");
60
+ Object.defineProperty(exports, "getEnvironmentConfig", { enumerable: true, get: function () { return environment_1.getEnvironmentConfig; } });
61
+ Object.defineProperty(exports, "validateEnvironmentConfig", { enumerable: true, get: function () { return environment_1.validateEnvironmentConfig; } });
62
+ Object.defineProperty(exports, "getEnvVar", { enumerable: true, get: function () { return environment_1.getEnvVar; } });
63
+ Object.defineProperty(exports, "getEnvVarNumber", { enumerable: true, get: function () { return environment_1.getEnvVarNumber; } });
64
+ Object.defineProperty(exports, "getEnvVarBigInt", { enumerable: true, get: function () { return environment_1.getEnvVarBigInt; } });
65
+ Object.defineProperty(exports, "getEnvVarBoolean", { enumerable: true, get: function () { return environment_1.getEnvVarBoolean; } });
66
+ // --- Lower-level Services (for advanced use cases) ---
67
+ // Note: Exposing these is optional. We expose them to allow for more flexibility.
68
+ // Keyring implementations
69
+ var HDKeyring_1 = require("./keyrings/HDKeyring");
70
+ Object.defineProperty(exports, "HDKeyring", { enumerable: true, get: function () { return HDKeyring_1.HDKeyring; } });
71
+ var SimpleKeyring_1 = require("./keyrings/SimpleKeyring");
72
+ Object.defineProperty(exports, "SimpleKeyring", { enumerable: true, get: function () { return SimpleKeyring_1.SimpleKeyring; } });
73
+ var SolanaKeyring_1 = require("./keyrings/SolanaKeyring");
74
+ Object.defineProperty(exports, "SolanaKeyring", { enumerable: true, get: function () { return SolanaKeyring_1.SolanaKeyring; } });
75
+ // Chain services
76
+ var ChainService_1 = require("./chain/ChainService");
77
+ Object.defineProperty(exports, "ChainService", { enumerable: true, get: function () { return ChainService_1.ChainService; } });
78
+ var SolanaChainService_1 = require("./chain/SolanaChainService");
79
+ Object.defineProperty(exports, "SolanaChainService", { enumerable: true, get: function () { return SolanaChainService_1.SolanaChainService; } });
80
+ // `EncryptionService` provides access to the underlying encryption/decryption methods.
81
+ var EncryptionService_1 = require("./crypto/EncryptionService");
82
+ Object.defineProperty(exports, "EncryptionService", { enumerable: true, get: function () { return EncryptionService_1.EncryptionService; } });
83
+ // Multi-transfer services
84
+ var MultiTransferService_1 = require("./services/MultiTransferService");
85
+ Object.defineProperty(exports, "MultiTransferService", { enumerable: true, get: function () { return MultiTransferService_1.MultiTransferService; } });
86
+ var BatchProcessor_1 = require("./services/BatchProcessor");
87
+ Object.defineProperty(exports, "BatchProcessor", { enumerable: true, get: function () { return BatchProcessor_1.BatchProcessor; } });
88
+ // QR code service
89
+ var QRCodeService_1 = require("./services/QRCodeService");
90
+ Object.defineProperty(exports, "QRCodeService", { enumerable: true, get: function () { return QRCodeService_1.QRCodeService; } });
91
+ __exportStar(require("./services/TokenUtils"), exports);
92
+ __exportStar(require("./services/nft/NFTService"), exports);
93
+ // --- React Native Components ---
94
+ // QR code components for React Native (uncomment when components are created)
95
+ // export { QRCodeDisplay } from './components/QRCodeDisplay';
96
+ // export { QRCodeScanner } from './components/QRCodeScanner';
@@ -0,0 +1,72 @@
1
+ /**
2
+ * HD (Hierarchical Deterministic) keyring for managing multiple accounts
3
+ * derived from a single mnemonic phrase using BIP-44 derivation paths.
4
+ * Supports EVM-compatible chains.
5
+ */
6
+ export declare class HDKeyring {
7
+ readonly type = "HD";
8
+ private mnemonic;
9
+ private seed;
10
+ private static seedCache;
11
+ accounts: string[];
12
+ /**
13
+ * Creates a new HDKeyring instance from a mnemonic phrase.
14
+ * @param mnemonic - The mnemonic phrase (12, 15, 18, 21, or 24 words)
15
+ * @throws Error if the mnemonic is invalid
16
+ */
17
+ constructor(mnemonic: string);
18
+ /**
19
+ * Initializes the keyring by generating the seed and creating the first account.
20
+ * This method must be called before using the keyring.
21
+ * @returns Promise that resolves when initialization is complete
22
+ * @throws Error if seed generation or account derivation fails
23
+ */
24
+ initialize(): Promise<void>;
25
+ /**
26
+ * Derives an account at a specific index using BIP-44 derivation.
27
+ * @param index - The account index to derive (0-based)
28
+ * @returns Promise resolving to an object containing the derived address and private key
29
+ * @throws Error if the keyring is not initialized or derivation fails
30
+ */
31
+ private deriveAccount;
32
+ /**
33
+ * Adds a new account derived from the mnemonic at the next available index.
34
+ * @returns Promise resolving to the address of the newly created account
35
+ * @throws Error if account derivation fails or duplicate address is generated
36
+ */
37
+ addNewAccount(): Promise<string>;
38
+ /**
39
+ * Gets the private key for a given address managed by this keyring.
40
+ * @param address - The account address to get the private key for
41
+ * @returns Promise resolving to the private key as a hex string
42
+ * @throws Error if the address is not found in this keyring
43
+ */
44
+ getPrivateKeyForAddress(address: string): Promise<string>;
45
+ /**
46
+ * Returns the mnemonic phrase. USE WITH CAUTION - this exposes sensitive data.
47
+ * @returns The mnemonic phrase as a string
48
+ */
49
+ getMnemonic(): string;
50
+ /**
51
+ * Serializes the keyring data for encryption and storage.
52
+ * @returns An object containing the keyring type, mnemonic, and account addresses
53
+ */
54
+ serialize(): any;
55
+ /**
56
+ * Deserializes data into an HDKeyring instance.
57
+ * @param data - The serialized keyring data
58
+ * @returns Promise resolving to a new HDKeyring instance
59
+ * @throws Error if the data is invalid or missing required fields
60
+ */
61
+ static deserialize(data: any): Promise<HDKeyring>;
62
+ /**
63
+ * Clears the seed cache to free up memory.
64
+ * Call this when you want to clear sensitive data from memory.
65
+ */
66
+ static clearSeedCache(): void;
67
+ /**
68
+ * Gets the cache size for debugging purposes.
69
+ * @returns Number of cached seeds
70
+ */
71
+ static getSeedCacheSize(): number;
72
+ }
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HDKeyring = void 0;
4
+ const EncryptionService_1 = require("../crypto/EncryptionService");
5
+ const chains_1 = require("../config/chains");
6
+ const ChainService_1 = require("../chain/ChainService");
7
+ /**
8
+ * HD (Hierarchical Deterministic) keyring for managing multiple accounts
9
+ * derived from a single mnemonic phrase using BIP-44 derivation paths.
10
+ * Supports EVM-compatible chains.
11
+ */
12
+ class HDKeyring {
13
+ /**
14
+ * Creates a new HDKeyring instance from a mnemonic phrase.
15
+ * @param mnemonic - The mnemonic phrase (12, 15, 18, 21, or 24 words)
16
+ * @throws Error if the mnemonic is invalid
17
+ */
18
+ constructor(mnemonic) {
19
+ this.type = 'HD';
20
+ this.seed = null;
21
+ // For now, we manage one account, but this can be extended.
22
+ this.accounts = [];
23
+ if (!EncryptionService_1.EncryptionService.validateMnemonic(mnemonic)) {
24
+ throw new Error('Invalid mnemonic');
25
+ }
26
+ this.mnemonic = mnemonic;
27
+ }
28
+ /**
29
+ * Initializes the keyring by generating the seed and creating the first account.
30
+ * This method must be called before using the keyring.
31
+ * @returns Promise that resolves when initialization is complete
32
+ * @throws Error if seed generation or account derivation fails
33
+ */
34
+ async initialize() {
35
+ // Check cache first
36
+ if (HDKeyring.seedCache.has(this.mnemonic)) {
37
+ this.seed = HDKeyring.seedCache.get(this.mnemonic);
38
+ }
39
+ else {
40
+ this.seed = await EncryptionService_1.EncryptionService.mnemonicToSeed(this.mnemonic);
41
+ // Cache the seed
42
+ HDKeyring.seedCache.set(this.mnemonic, this.seed);
43
+ }
44
+ const firstAccount = await this.deriveAccount(0);
45
+ this.accounts.push(firstAccount.address);
46
+ }
47
+ /**
48
+ * Derives an account at a specific index using BIP-44 derivation.
49
+ * @param index - The account index to derive (0-based)
50
+ * @returns Promise resolving to an object containing the derived address and private key
51
+ * @throws Error if the keyring is not initialized or derivation fails
52
+ */
53
+ async deriveAccount(index) {
54
+ if (!this.seed) {
55
+ throw new Error('Keyring not initialized. Call initialize() first.');
56
+ }
57
+ // This can be extended to support custom paths per index.
58
+ const path = `${chains_1.DERIVATION_PATHS.EVM.slice(0, -1)}${index}`;
59
+ const privateKeyBuffer = await EncryptionService_1.EncryptionService.derivePrivateKey(this.seed, path);
60
+ const privateKeyHex = privateKeyBuffer.toString('hex');
61
+ const address = ChainService_1.ChainService.getAddress(privateKeyHex);
62
+ return { address, privateKey: privateKeyHex };
63
+ }
64
+ /**
65
+ * Adds a new account derived from the mnemonic at the next available index.
66
+ * @returns Promise resolving to the address of the newly created account
67
+ * @throws Error if account derivation fails or duplicate address is generated
68
+ */
69
+ async addNewAccount() {
70
+ const newIndex = this.accounts.length;
71
+ const newAccount = await this.deriveAccount(newIndex);
72
+ if (this.accounts.includes(newAccount.address)) {
73
+ throw new Error('Duplicate account derived. Please check derivation path logic.');
74
+ }
75
+ this.accounts.push(newAccount.address);
76
+ return newAccount.address;
77
+ }
78
+ /**
79
+ * Gets the private key for a given address managed by this keyring.
80
+ * @param address - The account address to get the private key for
81
+ * @returns Promise resolving to the private key as a hex string
82
+ * @throws Error if the address is not found in this keyring
83
+ */
84
+ async getPrivateKeyForAddress(address) {
85
+ const index = this.accounts.indexOf(address);
86
+ if (index === -1) {
87
+ throw new Error('Address not found in this keyring.');
88
+ }
89
+ const account = await this.deriveAccount(index);
90
+ return account.privateKey;
91
+ }
92
+ /**
93
+ * Returns the mnemonic phrase. USE WITH CAUTION - this exposes sensitive data.
94
+ * @returns The mnemonic phrase as a string
95
+ */
96
+ getMnemonic() {
97
+ return this.mnemonic;
98
+ }
99
+ /**
100
+ * Serializes the keyring data for encryption and storage.
101
+ * @returns An object containing the keyring type, mnemonic, and account addresses
102
+ */
103
+ serialize() {
104
+ return {
105
+ type: this.type,
106
+ mnemonic: this.mnemonic,
107
+ accounts: this.accounts
108
+ };
109
+ }
110
+ /**
111
+ * Deserializes data into an HDKeyring instance.
112
+ * @param data - The serialized keyring data
113
+ * @returns Promise resolving to a new HDKeyring instance
114
+ * @throws Error if the data is invalid or missing required fields
115
+ */
116
+ static async deserialize(data) {
117
+ if (data.type !== 'HD' || !data.mnemonic) {
118
+ throw new Error('Invalid data for HDKeyring deserialization.');
119
+ }
120
+ const keyring = new HDKeyring(data.mnemonic);
121
+ // If accounts were persisted, restore them. Otherwise, initialize fresh.
122
+ if (data.accounts && data.accounts.length > 0) {
123
+ keyring.accounts = data.accounts;
124
+ // Cache the seed to avoid regenerating it on every load
125
+ if (HDKeyring.seedCache.has(keyring.mnemonic)) {
126
+ keyring.seed = HDKeyring.seedCache.get(keyring.mnemonic);
127
+ }
128
+ else {
129
+ keyring.seed = await EncryptionService_1.EncryptionService.mnemonicToSeed(keyring.mnemonic);
130
+ // Cache the seed
131
+ HDKeyring.seedCache.set(keyring.mnemonic, keyring.seed);
132
+ }
133
+ }
134
+ else {
135
+ await keyring.initialize();
136
+ }
137
+ return keyring;
138
+ }
139
+ /**
140
+ * Clears the seed cache to free up memory.
141
+ * Call this when you want to clear sensitive data from memory.
142
+ */
143
+ static clearSeedCache() {
144
+ HDKeyring.seedCache.clear();
145
+ }
146
+ /**
147
+ * Gets the cache size for debugging purposes.
148
+ * @returns Number of cached seeds
149
+ */
150
+ static getSeedCacheSize() {
151
+ return HDKeyring.seedCache.size;
152
+ }
153
+ }
154
+ exports.HDKeyring = HDKeyring;
155
+ // Cache để tránh tạo lại seed
156
+ HDKeyring.seedCache = new Map();
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Simple keyring for managing a single account from a private key.
3
+ * Used for importing existing accounts that are not derived from a mnemonic.
4
+ */
5
+ export declare class SimpleKeyring {
6
+ readonly type = "Simple";
7
+ private privateKey;
8
+ address: string;
9
+ /**
10
+ * Creates a new SimpleKeyring instance from a private key.
11
+ * @param privateKey - The private key to import (hex string without '0x' prefix)
12
+ */
13
+ constructor(privateKey: string);
14
+ /**
15
+ * Returns the private key. This should be used with extreme caution.
16
+ * @returns The private key as a hex string
17
+ */
18
+ getPrivateKey(): string;
19
+ /**
20
+ * Serializes the keyring into a plain object for encryption and storage.
21
+ * @returns An object containing the keyring type and private key
22
+ */
23
+ serialize(): any;
24
+ /**
25
+ * Deserializes a plain object back into a SimpleKeyring instance.
26
+ * @param data - The serialized keyring data
27
+ * @returns A new SimpleKeyring instance
28
+ * @throws Error if the data is invalid or missing required fields
29
+ */
30
+ static deserialize(data: any): SimpleKeyring;
31
+ }
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SimpleKeyring = void 0;
4
+ const ChainService_1 = require("../chain/ChainService");
5
+ /**
6
+ * Simple keyring for managing a single account from a private key.
7
+ * Used for importing existing accounts that are not derived from a mnemonic.
8
+ */
9
+ class SimpleKeyring {
10
+ /**
11
+ * Creates a new SimpleKeyring instance from a private key.
12
+ * @param privateKey - The private key to import (hex string without '0x' prefix)
13
+ */
14
+ constructor(privateKey) {
15
+ this.type = 'Simple';
16
+ this.privateKey = privateKey;
17
+ this.address = ChainService_1.ChainService.getAddress(privateKey);
18
+ }
19
+ /**
20
+ * Returns the private key. This should be used with extreme caution.
21
+ * @returns The private key as a hex string
22
+ */
23
+ getPrivateKey() {
24
+ return this.privateKey;
25
+ }
26
+ /**
27
+ * Serializes the keyring into a plain object for encryption and storage.
28
+ * @returns An object containing the keyring type and private key
29
+ */
30
+ serialize() {
31
+ return {
32
+ type: this.type,
33
+ privateKey: this.privateKey,
34
+ };
35
+ }
36
+ /**
37
+ * Deserializes a plain object back into a SimpleKeyring instance.
38
+ * @param data - The serialized keyring data
39
+ * @returns A new SimpleKeyring instance
40
+ * @throws Error if the data is invalid or missing required fields
41
+ */
42
+ static deserialize(data) {
43
+ if (data.type !== 'Simple' || !data.privateKey) {
44
+ throw new Error('Invalid data for SimpleKeyring deserialization.');
45
+ }
46
+ return new SimpleKeyring(data.privateKey);
47
+ }
48
+ }
49
+ exports.SimpleKeyring = SimpleKeyring;