@zubari/sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +324 -0
- package/dist/SecureStorage-jO783AhC.d.mts +89 -0
- package/dist/SecureStorage-jO783AhC.d.ts +89 -0
- package/dist/SwapService-C0G8IXW2.d.mts +35 -0
- package/dist/SwapService-DZD0OJI_.d.ts +35 -0
- package/dist/WalletManager-DJjdq89b.d.mts +6106 -0
- package/dist/WalletManager-TiAdzqrn.d.ts +6106 -0
- package/dist/index-BLuxEdLp.d.mts +156 -0
- package/dist/index-BLuxEdLp.d.ts +156 -0
- package/dist/index-DO3T2HVe.d.ts +135 -0
- package/dist/index-fXVD8_D0.d.mts +135 -0
- package/dist/index.d.mts +67 -0
- package/dist/index.d.ts +67 -0
- package/dist/index.js +2411 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +2386 -0
- package/dist/index.mjs.map +1 -0
- package/dist/protocols/index.d.mts +181 -0
- package/dist/protocols/index.d.ts +181 -0
- package/dist/protocols/index.js +415 -0
- package/dist/protocols/index.js.map +1 -0
- package/dist/protocols/index.mjs +410 -0
- package/dist/protocols/index.mjs.map +1 -0
- package/dist/react/index.d.mts +49 -0
- package/dist/react/index.d.ts +49 -0
- package/dist/react/index.js +1573 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/index.mjs +1570 -0
- package/dist/react/index.mjs.map +1 -0
- package/dist/services/index.d.mts +198 -0
- package/dist/services/index.d.ts +198 -0
- package/dist/services/index.js +554 -0
- package/dist/services/index.js.map +1 -0
- package/dist/services/index.mjs +547 -0
- package/dist/services/index.mjs.map +1 -0
- package/dist/storage/index.d.mts +57 -0
- package/dist/storage/index.d.ts +57 -0
- package/dist/storage/index.js +442 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/storage/index.mjs +435 -0
- package/dist/storage/index.mjs.map +1 -0
- package/dist/wallet/index.d.mts +8 -0
- package/dist/wallet/index.d.ts +8 -0
- package/dist/wallet/index.js +1678 -0
- package/dist/wallet/index.js.map +1 -0
- package/dist/wallet/index.mjs +1674 -0
- package/dist/wallet/index.mjs.map +1 -0
- package/package.json +136 -0
|
@@ -0,0 +1,1570 @@
|
|
|
1
|
+
import { useMemo, useState, useCallback, useEffect } from 'react';
|
|
2
|
+
import { Wallet, HDNodeWallet } from 'ethers';
|
|
3
|
+
import { createPublicClient, http, formatEther } from 'viem';
|
|
4
|
+
import { mainnet, sepolia } from 'viem/chains';
|
|
5
|
+
|
|
6
|
+
// src/react/useWalletManager.ts
|
|
7
|
+
|
|
8
|
+
// src/config/networks.ts
|
|
9
|
+
var NETWORKS = {
|
|
10
|
+
bitcoin: {
|
|
11
|
+
name: "Bitcoin",
|
|
12
|
+
chainId: 0,
|
|
13
|
+
coinType: 0,
|
|
14
|
+
// m/44'/0'
|
|
15
|
+
rpcUrl: "https://blockstream.info/api",
|
|
16
|
+
explorerUrl: "https://blockstream.info",
|
|
17
|
+
nativeCurrency: {
|
|
18
|
+
name: "Bitcoin",
|
|
19
|
+
symbol: "BTC",
|
|
20
|
+
decimals: 8
|
|
21
|
+
},
|
|
22
|
+
isEvm: false
|
|
23
|
+
},
|
|
24
|
+
ethereum: {
|
|
25
|
+
name: "Ethereum",
|
|
26
|
+
chainId: 1,
|
|
27
|
+
coinType: 60,
|
|
28
|
+
// m/44'/60'
|
|
29
|
+
rpcUrl: "https://eth.llamarpc.com",
|
|
30
|
+
explorerUrl: "https://etherscan.io",
|
|
31
|
+
nativeCurrency: {
|
|
32
|
+
name: "Ether",
|
|
33
|
+
symbol: "ETH",
|
|
34
|
+
decimals: 18
|
|
35
|
+
},
|
|
36
|
+
isEvm: true
|
|
37
|
+
},
|
|
38
|
+
ton: {
|
|
39
|
+
name: "TON",
|
|
40
|
+
chainId: -239,
|
|
41
|
+
coinType: 607,
|
|
42
|
+
// m/44'/607'
|
|
43
|
+
rpcUrl: "https://toncenter.com/api/v2",
|
|
44
|
+
explorerUrl: "https://tonscan.org",
|
|
45
|
+
nativeCurrency: {
|
|
46
|
+
name: "Toncoin",
|
|
47
|
+
symbol: "TON",
|
|
48
|
+
decimals: 9
|
|
49
|
+
},
|
|
50
|
+
isEvm: false
|
|
51
|
+
},
|
|
52
|
+
tron: {
|
|
53
|
+
name: "TRON",
|
|
54
|
+
chainId: 728126428,
|
|
55
|
+
coinType: 195,
|
|
56
|
+
// m/44'/195'
|
|
57
|
+
rpcUrl: "https://api.trongrid.io",
|
|
58
|
+
explorerUrl: "https://tronscan.org",
|
|
59
|
+
nativeCurrency: {
|
|
60
|
+
name: "TRON",
|
|
61
|
+
symbol: "TRX",
|
|
62
|
+
decimals: 6
|
|
63
|
+
},
|
|
64
|
+
isEvm: false
|
|
65
|
+
},
|
|
66
|
+
solana: {
|
|
67
|
+
name: "Solana",
|
|
68
|
+
chainId: 0,
|
|
69
|
+
coinType: 501,
|
|
70
|
+
// m/44'/501'
|
|
71
|
+
rpcUrl: "https://api.mainnet-beta.solana.com",
|
|
72
|
+
explorerUrl: "https://solscan.io",
|
|
73
|
+
nativeCurrency: {
|
|
74
|
+
name: "Solana",
|
|
75
|
+
symbol: "SOL",
|
|
76
|
+
decimals: 9
|
|
77
|
+
},
|
|
78
|
+
isEvm: false
|
|
79
|
+
},
|
|
80
|
+
spark: {
|
|
81
|
+
name: "Spark (Lightning)",
|
|
82
|
+
chainId: 0,
|
|
83
|
+
coinType: 998,
|
|
84
|
+
// m/44'/998'
|
|
85
|
+
rpcUrl: "",
|
|
86
|
+
explorerUrl: "",
|
|
87
|
+
nativeCurrency: {
|
|
88
|
+
name: "Bitcoin",
|
|
89
|
+
symbol: "BTC",
|
|
90
|
+
decimals: 8
|
|
91
|
+
},
|
|
92
|
+
isEvm: false
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
var TESTNET_NETWORKS = {
|
|
96
|
+
ethereum: {
|
|
97
|
+
name: "Sepolia",
|
|
98
|
+
chainId: 11155111,
|
|
99
|
+
// Using eth-sepolia.g.alchemy.com public endpoint (more reliable than rpc.sepolia.org)
|
|
100
|
+
// Fallback order: 1. Alchemy public, 2. Infura public, 3. BlockPi
|
|
101
|
+
rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
|
|
102
|
+
explorerUrl: "https://sepolia.etherscan.io"
|
|
103
|
+
},
|
|
104
|
+
solana: {
|
|
105
|
+
name: "Solana Devnet",
|
|
106
|
+
rpcUrl: "https://api.devnet.solana.com",
|
|
107
|
+
explorerUrl: "https://solscan.io?cluster=devnet"
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
var DERIVATION_PATHS = {
|
|
111
|
+
ethereum: "m/44'/60'/0'/0"};
|
|
112
|
+
function getNetworkConfig(network, isTestnet = false) {
|
|
113
|
+
const mainnetConfig = NETWORKS[network];
|
|
114
|
+
if (!isTestnet) return mainnetConfig;
|
|
115
|
+
const testnetOverrides = TESTNET_NETWORKS[network];
|
|
116
|
+
if (!testnetOverrides) return mainnetConfig;
|
|
117
|
+
return {
|
|
118
|
+
...mainnetConfig,
|
|
119
|
+
...testnetOverrides
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// src/security/KeyManager.ts
|
|
124
|
+
var KeyManager = class {
|
|
125
|
+
static ALGORITHM = "AES-GCM";
|
|
126
|
+
static KEY_LENGTH = 256;
|
|
127
|
+
static IV_LENGTH = 12;
|
|
128
|
+
static SALT_LENGTH = 16;
|
|
129
|
+
static PBKDF2_ITERATIONS = 1e5;
|
|
130
|
+
/**
|
|
131
|
+
* Encrypt a seed phrase with a password
|
|
132
|
+
*/
|
|
133
|
+
static async encryptSeed(seed, password) {
|
|
134
|
+
const encoder = new TextEncoder();
|
|
135
|
+
const seedData = encoder.encode(seed);
|
|
136
|
+
const salt = crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH));
|
|
137
|
+
const iv = crypto.getRandomValues(new Uint8Array(this.IV_LENGTH));
|
|
138
|
+
const key = await this.deriveKey(password, salt);
|
|
139
|
+
const encrypted = await crypto.subtle.encrypt(
|
|
140
|
+
{ name: this.ALGORITHM, iv },
|
|
141
|
+
key,
|
|
142
|
+
seedData
|
|
143
|
+
);
|
|
144
|
+
const combined = new Uint8Array(salt.length + iv.length + encrypted.byteLength);
|
|
145
|
+
combined.set(salt, 0);
|
|
146
|
+
combined.set(iv, salt.length);
|
|
147
|
+
combined.set(new Uint8Array(encrypted), salt.length + iv.length);
|
|
148
|
+
return btoa(String.fromCharCode(...combined));
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Decrypt a seed phrase with a password
|
|
152
|
+
*/
|
|
153
|
+
static async decryptSeed(encryptedData, password) {
|
|
154
|
+
const combined = new Uint8Array(
|
|
155
|
+
atob(encryptedData).split("").map((c) => c.charCodeAt(0))
|
|
156
|
+
);
|
|
157
|
+
const salt = combined.slice(0, this.SALT_LENGTH);
|
|
158
|
+
const iv = combined.slice(this.SALT_LENGTH, this.SALT_LENGTH + this.IV_LENGTH);
|
|
159
|
+
const encrypted = combined.slice(this.SALT_LENGTH + this.IV_LENGTH);
|
|
160
|
+
const key = await this.deriveKey(password, salt);
|
|
161
|
+
const decrypted = await crypto.subtle.decrypt(
|
|
162
|
+
{ name: this.ALGORITHM, iv },
|
|
163
|
+
key,
|
|
164
|
+
encrypted
|
|
165
|
+
);
|
|
166
|
+
const decoder = new TextDecoder();
|
|
167
|
+
return decoder.decode(decrypted);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Derive encryption key from password using PBKDF2
|
|
171
|
+
*/
|
|
172
|
+
static async deriveKey(password, salt) {
|
|
173
|
+
const encoder = new TextEncoder();
|
|
174
|
+
const passwordData = encoder.encode(password);
|
|
175
|
+
const keyMaterial = await crypto.subtle.importKey(
|
|
176
|
+
"raw",
|
|
177
|
+
passwordData,
|
|
178
|
+
"PBKDF2",
|
|
179
|
+
false,
|
|
180
|
+
["deriveKey"]
|
|
181
|
+
);
|
|
182
|
+
return crypto.subtle.deriveKey(
|
|
183
|
+
{
|
|
184
|
+
name: "PBKDF2",
|
|
185
|
+
salt: salt.buffer.slice(salt.byteOffset, salt.byteOffset + salt.byteLength),
|
|
186
|
+
iterations: this.PBKDF2_ITERATIONS,
|
|
187
|
+
hash: "SHA-256"
|
|
188
|
+
},
|
|
189
|
+
keyMaterial,
|
|
190
|
+
{ name: this.ALGORITHM, length: this.KEY_LENGTH },
|
|
191
|
+
false,
|
|
192
|
+
["encrypt", "decrypt"]
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Validate a BIP-39 seed phrase (basic validation)
|
|
197
|
+
*/
|
|
198
|
+
static validateSeedPhrase(seed) {
|
|
199
|
+
const words = seed.trim().split(/\s+/);
|
|
200
|
+
const validWordCounts = [12, 15, 18, 21, 24];
|
|
201
|
+
return validWordCounts.includes(words.length);
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Generate a random encryption key (for backup purposes)
|
|
205
|
+
*/
|
|
206
|
+
static generateBackupKey() {
|
|
207
|
+
const bytes = crypto.getRandomValues(new Uint8Array(32));
|
|
208
|
+
return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
// src/storage/SecureStorage.ts
|
|
213
|
+
var KeychainStorageAdapter = class {
|
|
214
|
+
serviceName;
|
|
215
|
+
constructor(serviceName = "com.zubari.wallet") {
|
|
216
|
+
this.serviceName = serviceName;
|
|
217
|
+
}
|
|
218
|
+
async setItem(key, value) {
|
|
219
|
+
if (typeof global !== "undefined" && global.KeychainModule) {
|
|
220
|
+
await global.KeychainModule.setItem(this.serviceName, key, value);
|
|
221
|
+
} else {
|
|
222
|
+
throw new Error("Keychain not available on this platform");
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
async getItem(key) {
|
|
226
|
+
if (typeof global !== "undefined" && global.KeychainModule) {
|
|
227
|
+
return global.KeychainModule.getItem(this.serviceName, key);
|
|
228
|
+
}
|
|
229
|
+
throw new Error("Keychain not available on this platform");
|
|
230
|
+
}
|
|
231
|
+
async removeItem(key) {
|
|
232
|
+
if (typeof global !== "undefined" && global.KeychainModule) {
|
|
233
|
+
await global.KeychainModule.removeItem(this.serviceName, key);
|
|
234
|
+
} else {
|
|
235
|
+
throw new Error("Keychain not available on this platform");
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
async hasItem(key) {
|
|
239
|
+
const value = await this.getItem(key);
|
|
240
|
+
return value !== null;
|
|
241
|
+
}
|
|
242
|
+
async clear() {
|
|
243
|
+
if (typeof global !== "undefined" && global.KeychainModule) {
|
|
244
|
+
await global.KeychainModule.clear(this.serviceName);
|
|
245
|
+
} else {
|
|
246
|
+
throw new Error("Keychain not available on this platform");
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
var KeystoreStorageAdapter = class {
|
|
251
|
+
alias;
|
|
252
|
+
constructor(alias = "zubari_wallet_keys") {
|
|
253
|
+
this.alias = alias;
|
|
254
|
+
}
|
|
255
|
+
async setItem(key, value) {
|
|
256
|
+
if (typeof global !== "undefined" && global.KeystoreModule) {
|
|
257
|
+
await global.KeystoreModule.setItem(this.alias, key, value);
|
|
258
|
+
} else {
|
|
259
|
+
throw new Error("Keystore not available on this platform");
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
async getItem(key) {
|
|
263
|
+
if (typeof global !== "undefined" && global.KeystoreModule) {
|
|
264
|
+
return global.KeystoreModule.getItem(this.alias, key);
|
|
265
|
+
}
|
|
266
|
+
throw new Error("Keystore not available on this platform");
|
|
267
|
+
}
|
|
268
|
+
async removeItem(key) {
|
|
269
|
+
if (typeof global !== "undefined" && global.KeystoreModule) {
|
|
270
|
+
await global.KeystoreModule.removeItem(this.alias, key);
|
|
271
|
+
} else {
|
|
272
|
+
throw new Error("Keystore not available on this platform");
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
async hasItem(key) {
|
|
276
|
+
const value = await this.getItem(key);
|
|
277
|
+
return value !== null;
|
|
278
|
+
}
|
|
279
|
+
async clear() {
|
|
280
|
+
if (typeof global !== "undefined" && global.KeystoreModule) {
|
|
281
|
+
await global.KeystoreModule.clear(this.alias);
|
|
282
|
+
} else {
|
|
283
|
+
throw new Error("Keystore not available on this platform");
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
var WebEncryptedStorageAdapter = class {
|
|
288
|
+
encryptionKey = null;
|
|
289
|
+
storagePrefix;
|
|
290
|
+
constructor(storagePrefix = "zubari_") {
|
|
291
|
+
this.storagePrefix = storagePrefix;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Initialize with a password-derived key
|
|
295
|
+
*/
|
|
296
|
+
async initialize(password) {
|
|
297
|
+
const encoder = new TextEncoder();
|
|
298
|
+
const salt = this.getSalt();
|
|
299
|
+
const keyMaterial = await crypto.subtle.importKey(
|
|
300
|
+
"raw",
|
|
301
|
+
encoder.encode(password),
|
|
302
|
+
"PBKDF2",
|
|
303
|
+
false,
|
|
304
|
+
["deriveKey"]
|
|
305
|
+
);
|
|
306
|
+
this.encryptionKey = await crypto.subtle.deriveKey(
|
|
307
|
+
{
|
|
308
|
+
name: "PBKDF2",
|
|
309
|
+
salt: salt.buffer,
|
|
310
|
+
iterations: 1e5,
|
|
311
|
+
hash: "SHA-256"
|
|
312
|
+
},
|
|
313
|
+
keyMaterial,
|
|
314
|
+
{ name: "AES-GCM", length: 256 },
|
|
315
|
+
false,
|
|
316
|
+
["encrypt", "decrypt"]
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
getSalt() {
|
|
320
|
+
const saltKey = `${this.storagePrefix}salt`;
|
|
321
|
+
let saltHex = localStorage.getItem(saltKey);
|
|
322
|
+
if (!saltHex) {
|
|
323
|
+
const salt = crypto.getRandomValues(new Uint8Array(16));
|
|
324
|
+
saltHex = Array.from(salt).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
325
|
+
localStorage.setItem(saltKey, saltHex);
|
|
326
|
+
}
|
|
327
|
+
return new Uint8Array(
|
|
328
|
+
saltHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
async setItem(key, value) {
|
|
332
|
+
if (!this.encryptionKey) {
|
|
333
|
+
throw new Error("Storage not initialized. Call initialize() first.");
|
|
334
|
+
}
|
|
335
|
+
const encoder = new TextEncoder();
|
|
336
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
337
|
+
const encrypted = await crypto.subtle.encrypt(
|
|
338
|
+
{ name: "AES-GCM", iv },
|
|
339
|
+
this.encryptionKey,
|
|
340
|
+
encoder.encode(value)
|
|
341
|
+
);
|
|
342
|
+
const combined = new Uint8Array(iv.length + encrypted.byteLength);
|
|
343
|
+
combined.set(iv);
|
|
344
|
+
combined.set(new Uint8Array(encrypted), iv.length);
|
|
345
|
+
const base64 = btoa(String.fromCharCode(...combined));
|
|
346
|
+
localStorage.setItem(`${this.storagePrefix}${key}`, base64);
|
|
347
|
+
}
|
|
348
|
+
async getItem(key) {
|
|
349
|
+
if (!this.encryptionKey) {
|
|
350
|
+
throw new Error("Storage not initialized. Call initialize() first.");
|
|
351
|
+
}
|
|
352
|
+
const base64 = localStorage.getItem(`${this.storagePrefix}${key}`);
|
|
353
|
+
if (!base64) return null;
|
|
354
|
+
try {
|
|
355
|
+
const combined = new Uint8Array(
|
|
356
|
+
atob(base64).split("").map((c) => c.charCodeAt(0))
|
|
357
|
+
);
|
|
358
|
+
const iv = combined.slice(0, 12);
|
|
359
|
+
const encrypted = combined.slice(12);
|
|
360
|
+
const decrypted = await crypto.subtle.decrypt(
|
|
361
|
+
{ name: "AES-GCM", iv },
|
|
362
|
+
this.encryptionKey,
|
|
363
|
+
encrypted
|
|
364
|
+
);
|
|
365
|
+
const decoder = new TextDecoder();
|
|
366
|
+
return decoder.decode(decrypted);
|
|
367
|
+
} catch {
|
|
368
|
+
return null;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
async removeItem(key) {
|
|
372
|
+
localStorage.removeItem(`${this.storagePrefix}${key}`);
|
|
373
|
+
}
|
|
374
|
+
async hasItem(key) {
|
|
375
|
+
return localStorage.getItem(`${this.storagePrefix}${key}`) !== null;
|
|
376
|
+
}
|
|
377
|
+
async clear() {
|
|
378
|
+
const keysToRemove = [];
|
|
379
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
380
|
+
const key = localStorage.key(i);
|
|
381
|
+
if (key?.startsWith(this.storagePrefix)) {
|
|
382
|
+
keysToRemove.push(key);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
keysToRemove.forEach((key) => localStorage.removeItem(key));
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
var MemoryStorageAdapter = class {
|
|
389
|
+
storage = /* @__PURE__ */ new Map();
|
|
390
|
+
async setItem(key, value) {
|
|
391
|
+
this.storage.set(key, value);
|
|
392
|
+
}
|
|
393
|
+
async getItem(key) {
|
|
394
|
+
return this.storage.get(key) || null;
|
|
395
|
+
}
|
|
396
|
+
async removeItem(key) {
|
|
397
|
+
this.storage.delete(key);
|
|
398
|
+
}
|
|
399
|
+
async hasItem(key) {
|
|
400
|
+
return this.storage.has(key);
|
|
401
|
+
}
|
|
402
|
+
async clear() {
|
|
403
|
+
this.storage.clear();
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
function createSecureStorage() {
|
|
407
|
+
if (typeof global !== "undefined" && global.nativeModuleProxy !== void 0) {
|
|
408
|
+
const Platform = global.Platform;
|
|
409
|
+
if (Platform?.OS === "ios") {
|
|
410
|
+
return new KeychainStorageAdapter();
|
|
411
|
+
} else if (Platform?.OS === "android") {
|
|
412
|
+
return new KeystoreStorageAdapter();
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
if (typeof window !== "undefined" && typeof localStorage !== "undefined") {
|
|
416
|
+
return new WebEncryptedStorageAdapter();
|
|
417
|
+
}
|
|
418
|
+
return new MemoryStorageAdapter();
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// src/services/WdkApiClient.ts
|
|
422
|
+
var WdkApiClient = class {
|
|
423
|
+
config;
|
|
424
|
+
constructor(config) {
|
|
425
|
+
this.config = {
|
|
426
|
+
baseUrl: config.baseUrl,
|
|
427
|
+
timeout: config.timeout || 3e4
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Generate a new BIP-39 seed phrase using Tether WDK
|
|
432
|
+
*/
|
|
433
|
+
async generateSeed() {
|
|
434
|
+
try {
|
|
435
|
+
const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/generate-seed`, {
|
|
436
|
+
method: "POST",
|
|
437
|
+
headers: {
|
|
438
|
+
"Content-Type": "application/json"
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
return await response.json();
|
|
442
|
+
} catch (error) {
|
|
443
|
+
return {
|
|
444
|
+
success: false,
|
|
445
|
+
error: error instanceof Error ? error.message : "Failed to generate seed"
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Validate a BIP-39 seed phrase
|
|
451
|
+
*/
|
|
452
|
+
async validateSeed(seed) {
|
|
453
|
+
try {
|
|
454
|
+
const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/validate-seed`, {
|
|
455
|
+
method: "POST",
|
|
456
|
+
headers: {
|
|
457
|
+
"Content-Type": "application/json"
|
|
458
|
+
},
|
|
459
|
+
body: JSON.stringify({ seed })
|
|
460
|
+
});
|
|
461
|
+
return await response.json();
|
|
462
|
+
} catch (error) {
|
|
463
|
+
return {
|
|
464
|
+
success: false,
|
|
465
|
+
error: error instanceof Error ? error.message : "Failed to validate seed"
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Derive address for a specific chain using Tether WDK
|
|
471
|
+
*/
|
|
472
|
+
async deriveAddress(seed, chain, network = "testnet") {
|
|
473
|
+
try {
|
|
474
|
+
const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/derive-address`, {
|
|
475
|
+
method: "POST",
|
|
476
|
+
headers: {
|
|
477
|
+
"Content-Type": "application/json"
|
|
478
|
+
},
|
|
479
|
+
body: JSON.stringify({ seed, chain, network })
|
|
480
|
+
});
|
|
481
|
+
return await response.json();
|
|
482
|
+
} catch (error) {
|
|
483
|
+
return {
|
|
484
|
+
success: false,
|
|
485
|
+
error: error instanceof Error ? error.message : "Failed to derive address"
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Derive addresses for all chains using Tether WDK
|
|
491
|
+
*/
|
|
492
|
+
async deriveAllAddresses(seed, network = "testnet") {
|
|
493
|
+
try {
|
|
494
|
+
const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/derive-all`, {
|
|
495
|
+
method: "POST",
|
|
496
|
+
headers: {
|
|
497
|
+
"Content-Type": "application/json"
|
|
498
|
+
},
|
|
499
|
+
body: JSON.stringify({ seed, network })
|
|
500
|
+
});
|
|
501
|
+
return await response.json();
|
|
502
|
+
} catch (error) {
|
|
503
|
+
return {
|
|
504
|
+
success: false,
|
|
505
|
+
error: error instanceof Error ? error.message : "Failed to derive addresses"
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
var DEFAULT_API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
|
|
511
|
+
var wdkApiClient = null;
|
|
512
|
+
function getWdkApiClient(baseUrl) {
|
|
513
|
+
if (!wdkApiClient || baseUrl && wdkApiClient["config"].baseUrl !== baseUrl) {
|
|
514
|
+
wdkApiClient = new WdkApiClient({
|
|
515
|
+
baseUrl: baseUrl || DEFAULT_API_URL
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
return wdkApiClient;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// src/services/WdkService.ts
|
|
522
|
+
var WdkManager;
|
|
523
|
+
var WalletManagerBtc;
|
|
524
|
+
var WalletManagerEvm;
|
|
525
|
+
var WalletManagerSolana;
|
|
526
|
+
var WalletManagerTon;
|
|
527
|
+
var WalletManagerTron;
|
|
528
|
+
var WalletManagerSpark;
|
|
529
|
+
var wdkLoaded = false;
|
|
530
|
+
var wdkLoadError = null;
|
|
531
|
+
var dynamicImport = new Function("specifier", "return import(specifier)");
|
|
532
|
+
async function loadWdkModules() {
|
|
533
|
+
if (wdkLoaded) return;
|
|
534
|
+
if (wdkLoadError) throw wdkLoadError;
|
|
535
|
+
try {
|
|
536
|
+
const [wdk, btc, evm, solana, ton, tron, spark] = await Promise.all([
|
|
537
|
+
dynamicImport("@tetherto/wdk"),
|
|
538
|
+
dynamicImport("@tetherto/wdk-wallet-btc"),
|
|
539
|
+
dynamicImport("@tetherto/wdk-wallet-evm"),
|
|
540
|
+
dynamicImport("@tetherto/wdk-wallet-solana"),
|
|
541
|
+
dynamicImport("@tetherto/wdk-wallet-ton"),
|
|
542
|
+
dynamicImport("@tetherto/wdk-wallet-tron"),
|
|
543
|
+
dynamicImport("@tetherto/wdk-wallet-spark")
|
|
544
|
+
]);
|
|
545
|
+
WdkManager = wdk.default;
|
|
546
|
+
WalletManagerBtc = btc.default;
|
|
547
|
+
WalletManagerEvm = evm.default;
|
|
548
|
+
WalletManagerSolana = solana.default;
|
|
549
|
+
WalletManagerTon = ton.default;
|
|
550
|
+
WalletManagerTron = tron.default;
|
|
551
|
+
WalletManagerSpark = spark.default;
|
|
552
|
+
wdkLoaded = true;
|
|
553
|
+
} catch (error) {
|
|
554
|
+
wdkLoadError = error instanceof Error ? error : new Error("Failed to load WDK modules");
|
|
555
|
+
console.error("Failed to load WDK modules:", error);
|
|
556
|
+
throw wdkLoadError;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
var DERIVATION_PATHS2 = {
|
|
560
|
+
bitcoin: "m/84'/0'/0'/0/0",
|
|
561
|
+
// BIP-84 for native SegWit
|
|
562
|
+
ethereum: "m/44'/60'/0'/0/0",
|
|
563
|
+
ton: "m/44'/607'/0'",
|
|
564
|
+
// Updated for v1.0.0-beta.6+
|
|
565
|
+
tron: "m/44'/195'/0'/0/0",
|
|
566
|
+
solana: "m/44'/501'/0'/0'",
|
|
567
|
+
// Updated for v1.0.0-beta.4+
|
|
568
|
+
spark: "m/44'/998'/0'/0/0"
|
|
569
|
+
};
|
|
570
|
+
var DEFAULT_RPC_URLS = {
|
|
571
|
+
mainnet: {
|
|
572
|
+
ethereum: "https://eth.llamarpc.com",
|
|
573
|
+
solana: "https://api.mainnet-beta.solana.com",
|
|
574
|
+
ton: "https://toncenter.com/api/v2/jsonRPC",
|
|
575
|
+
tron: "https://api.trongrid.io"
|
|
576
|
+
},
|
|
577
|
+
testnet: {
|
|
578
|
+
ethereum: "https://ethereum-sepolia-rpc.publicnode.com",
|
|
579
|
+
solana: "https://api.devnet.solana.com",
|
|
580
|
+
ton: "https://testnet.toncenter.com/api/v2/jsonRPC",
|
|
581
|
+
tron: "https://api.shasta.trongrid.io"
|
|
582
|
+
}
|
|
583
|
+
};
|
|
584
|
+
var WdkService = class {
|
|
585
|
+
seed = null;
|
|
586
|
+
config;
|
|
587
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
588
|
+
wallets = {};
|
|
589
|
+
constructor(config = {}) {
|
|
590
|
+
this.config = {
|
|
591
|
+
network: config.network || "testnet",
|
|
592
|
+
rpcUrls: config.rpcUrls
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Check if WDK modules are loaded
|
|
597
|
+
*/
|
|
598
|
+
static isLoaded() {
|
|
599
|
+
return wdkLoaded;
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* Ensure WDK modules are loaded
|
|
603
|
+
*/
|
|
604
|
+
async ensureLoaded() {
|
|
605
|
+
await loadWdkModules();
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Load WDK modules (call this before using sync methods)
|
|
609
|
+
*/
|
|
610
|
+
async loadModules() {
|
|
611
|
+
await loadWdkModules();
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* Generate a random BIP-39 seed phrase (12 words)
|
|
615
|
+
*/
|
|
616
|
+
async generateSeedPhrase() {
|
|
617
|
+
await this.ensureLoaded();
|
|
618
|
+
return WdkManager.getRandomSeedPhrase();
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* Validate a BIP-39 seed phrase
|
|
622
|
+
*/
|
|
623
|
+
async isValidSeed(seed) {
|
|
624
|
+
await this.ensureLoaded();
|
|
625
|
+
return WdkManager.isValidSeed(seed);
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Validate seed phrase (sync version - basic check)
|
|
629
|
+
*/
|
|
630
|
+
isValidSeedSync(seed) {
|
|
631
|
+
const words = seed.trim().split(/\s+/);
|
|
632
|
+
return words.length === 12 || words.length === 24;
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* Initialize the service with a seed phrase
|
|
636
|
+
*/
|
|
637
|
+
async initialize(seed) {
|
|
638
|
+
await this.ensureLoaded();
|
|
639
|
+
if (!WdkManager.isValidSeed(seed)) {
|
|
640
|
+
throw new Error("Invalid seed phrase");
|
|
641
|
+
}
|
|
642
|
+
this.seed = seed;
|
|
643
|
+
this.wallets = {};
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Get RPC URL for a chain
|
|
647
|
+
*/
|
|
648
|
+
getRpcUrl(chain) {
|
|
649
|
+
const networkUrls = DEFAULT_RPC_URLS[this.config.network];
|
|
650
|
+
if (this.config.rpcUrls?.[chain]) {
|
|
651
|
+
return this.config.rpcUrls[chain];
|
|
652
|
+
}
|
|
653
|
+
return networkUrls[chain] || "";
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Get or create wallet instance for a specific chain
|
|
657
|
+
*/
|
|
658
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
659
|
+
async getWallet(chain) {
|
|
660
|
+
if (!this.seed) {
|
|
661
|
+
throw new Error("WDK service not initialized. Call initialize() first.");
|
|
662
|
+
}
|
|
663
|
+
if (this.wallets[chain]) {
|
|
664
|
+
return this.wallets[chain];
|
|
665
|
+
}
|
|
666
|
+
const isTestnet = this.config.network === "testnet";
|
|
667
|
+
try {
|
|
668
|
+
switch (chain) {
|
|
669
|
+
case "ethereum": {
|
|
670
|
+
const rpcUrl = this.getRpcUrl("ethereum");
|
|
671
|
+
const wallet = new WalletManagerEvm(this.seed, { provider: rpcUrl });
|
|
672
|
+
this.wallets[chain] = wallet;
|
|
673
|
+
return wallet;
|
|
674
|
+
}
|
|
675
|
+
case "bitcoin": {
|
|
676
|
+
const wallet = new WalletManagerBtc(this.seed, {
|
|
677
|
+
network: isTestnet ? "testnet" : "bitcoin"
|
|
678
|
+
});
|
|
679
|
+
this.wallets[chain] = wallet;
|
|
680
|
+
return wallet;
|
|
681
|
+
}
|
|
682
|
+
case "solana": {
|
|
683
|
+
const rpcUrl = this.getRpcUrl("solana");
|
|
684
|
+
const wallet = new WalletManagerSolana(this.seed, {
|
|
685
|
+
rpcUrl
|
|
686
|
+
});
|
|
687
|
+
this.wallets[chain] = wallet;
|
|
688
|
+
return wallet;
|
|
689
|
+
}
|
|
690
|
+
case "ton": {
|
|
691
|
+
const url = this.getRpcUrl("ton");
|
|
692
|
+
const wallet = new WalletManagerTon(this.seed, {
|
|
693
|
+
tonClient: { url }
|
|
694
|
+
});
|
|
695
|
+
this.wallets[chain] = wallet;
|
|
696
|
+
return wallet;
|
|
697
|
+
}
|
|
698
|
+
case "tron": {
|
|
699
|
+
const fullHost = this.getRpcUrl("tron");
|
|
700
|
+
const wallet = new WalletManagerTron(this.seed, {
|
|
701
|
+
provider: fullHost
|
|
702
|
+
});
|
|
703
|
+
this.wallets[chain] = wallet;
|
|
704
|
+
return wallet;
|
|
705
|
+
}
|
|
706
|
+
case "spark": {
|
|
707
|
+
const wallet = new WalletManagerSpark(this.seed, {
|
|
708
|
+
network: isTestnet ? "TESTNET" : "MAINNET"
|
|
709
|
+
});
|
|
710
|
+
this.wallets[chain] = wallet;
|
|
711
|
+
return wallet;
|
|
712
|
+
}
|
|
713
|
+
default:
|
|
714
|
+
throw new Error(`Unsupported chain: ${chain}`);
|
|
715
|
+
}
|
|
716
|
+
} catch (error) {
|
|
717
|
+
console.error(`Failed to initialize ${chain} wallet:`, error);
|
|
718
|
+
throw error;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* Derive address for a specific chain
|
|
723
|
+
*/
|
|
724
|
+
async deriveAddress(chain) {
|
|
725
|
+
const path = DERIVATION_PATHS2[chain];
|
|
726
|
+
try {
|
|
727
|
+
const wallet = await this.getWallet(chain);
|
|
728
|
+
const account = await wallet.getAccount(0);
|
|
729
|
+
const address = await account.getAddress();
|
|
730
|
+
return {
|
|
731
|
+
chain,
|
|
732
|
+
address,
|
|
733
|
+
path
|
|
734
|
+
};
|
|
735
|
+
} catch (error) {
|
|
736
|
+
console.error(`Error deriving ${chain} address:`, error);
|
|
737
|
+
throw error;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Derive addresses for all supported chains
|
|
742
|
+
*/
|
|
743
|
+
async deriveAllAddresses() {
|
|
744
|
+
const chains = ["ethereum", "bitcoin", "ton", "tron", "solana", "spark"];
|
|
745
|
+
const addresses = {
|
|
746
|
+
ethereum: null,
|
|
747
|
+
bitcoin: null,
|
|
748
|
+
ton: null,
|
|
749
|
+
tron: null,
|
|
750
|
+
solana: null,
|
|
751
|
+
spark: null
|
|
752
|
+
};
|
|
753
|
+
const results = await Promise.allSettled(
|
|
754
|
+
chains.map(async (chain) => {
|
|
755
|
+
const result = await this.deriveAddress(chain);
|
|
756
|
+
return { chain, address: result.address };
|
|
757
|
+
})
|
|
758
|
+
);
|
|
759
|
+
for (const result of results) {
|
|
760
|
+
if (result.status === "fulfilled") {
|
|
761
|
+
addresses[result.value.chain] = result.value.address;
|
|
762
|
+
} else {
|
|
763
|
+
console.error("Failed to derive address:", result.reason);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
return addresses;
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Derive addresses for specific chains only
|
|
770
|
+
*/
|
|
771
|
+
async deriveAddressesForChains(chains) {
|
|
772
|
+
const addresses = {};
|
|
773
|
+
const results = await Promise.allSettled(
|
|
774
|
+
chains.map(async (chain) => {
|
|
775
|
+
const result = await this.deriveAddress(chain);
|
|
776
|
+
return { chain, address: result.address };
|
|
777
|
+
})
|
|
778
|
+
);
|
|
779
|
+
for (const result of results) {
|
|
780
|
+
if (result.status === "fulfilled") {
|
|
781
|
+
addresses[result.value.chain] = result.value.address;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
return addresses;
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Get fee rates for a specific chain
|
|
788
|
+
*/
|
|
789
|
+
async getFeeRates(chain) {
|
|
790
|
+
if (!this.seed) {
|
|
791
|
+
throw new Error("WDK service not initialized. Call initialize() first.");
|
|
792
|
+
}
|
|
793
|
+
try {
|
|
794
|
+
const wallet = await this.getWallet(chain);
|
|
795
|
+
const feeRates = await wallet.getFeeRates();
|
|
796
|
+
return {
|
|
797
|
+
slow: (feeRates.slow || feeRates.low || "0").toString(),
|
|
798
|
+
medium: (feeRates.medium || feeRates.normal || feeRates.standard || "0").toString(),
|
|
799
|
+
fast: (feeRates.fast || feeRates.high || "0").toString()
|
|
800
|
+
};
|
|
801
|
+
} catch (error) {
|
|
802
|
+
console.error(`Error fetching fee rates for ${chain}:`, error);
|
|
803
|
+
throw error;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Get the current network configuration
|
|
808
|
+
*/
|
|
809
|
+
getNetwork() {
|
|
810
|
+
return this.config.network;
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Check if service is initialized
|
|
814
|
+
*/
|
|
815
|
+
isInitialized() {
|
|
816
|
+
return this.seed !== null;
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* Clean up and dispose of wallet instances
|
|
820
|
+
*/
|
|
821
|
+
dispose() {
|
|
822
|
+
for (const wallet of Object.values(this.wallets)) {
|
|
823
|
+
if (wallet && typeof wallet.dispose === "function") {
|
|
824
|
+
try {
|
|
825
|
+
wallet.dispose();
|
|
826
|
+
} catch {
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
this.wallets = {};
|
|
831
|
+
this.seed = null;
|
|
832
|
+
}
|
|
833
|
+
};
|
|
834
|
+
|
|
835
|
+
// src/wallet/WalletManager.ts
|
|
836
|
+
var STORAGE_KEYS = {
|
|
837
|
+
ENCRYPTED_SEED: "encrypted_seed",
|
|
838
|
+
ACTIVE_WALLET: "active_wallet"
|
|
839
|
+
};
|
|
840
|
+
var SUPPORTED_CHAINS = ["ethereum", "bitcoin", "ton", "tron", "solana", "spark"];
|
|
841
|
+
var WalletManager = class _WalletManager {
|
|
842
|
+
config;
|
|
843
|
+
storage;
|
|
844
|
+
currentSeed = null;
|
|
845
|
+
derivedAddress = null;
|
|
846
|
+
derivedAddresses = {};
|
|
847
|
+
selectedChain = "ethereum";
|
|
848
|
+
wdkService;
|
|
849
|
+
constructor(config = {}) {
|
|
850
|
+
const isTestnet = config.network !== "mainnet";
|
|
851
|
+
const ethereumConfig = getNetworkConfig("ethereum", isTestnet);
|
|
852
|
+
this.config = {
|
|
853
|
+
network: config.network || "testnet",
|
|
854
|
+
rpcUrl: config.rpcUrl || ethereumConfig.rpcUrl,
|
|
855
|
+
storage: config.storage || createSecureStorage(),
|
|
856
|
+
enabledChains: config.enabledChains || SUPPORTED_CHAINS,
|
|
857
|
+
apiUrl: config.apiUrl || process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001"
|
|
858
|
+
};
|
|
859
|
+
this.storage = this.config.storage;
|
|
860
|
+
this.wdkService = new WdkService({
|
|
861
|
+
network: this.config.network
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
/**
|
|
865
|
+
* Generate a new BIP-39 seed phrase (12 words) using ethers.js
|
|
866
|
+
* For native WDK generation, use generateSeedWithWdk() instead
|
|
867
|
+
*/
|
|
868
|
+
static generateSeed() {
|
|
869
|
+
const wallet = Wallet.createRandom();
|
|
870
|
+
const mnemonic = wallet.mnemonic;
|
|
871
|
+
if (!mnemonic) {
|
|
872
|
+
throw new Error("Failed to generate mnemonic");
|
|
873
|
+
}
|
|
874
|
+
return mnemonic.phrase;
|
|
875
|
+
}
|
|
876
|
+
/**
|
|
877
|
+
* Generate a new BIP-39 seed phrase using native Tether WDK
|
|
878
|
+
* This is the recommended method for generating seed phrases
|
|
879
|
+
*/
|
|
880
|
+
async generateSeedWithWdk() {
|
|
881
|
+
return await this.wdkService.generateSeedPhrase();
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Validate seed phrase using native WDK (async, more accurate)
|
|
885
|
+
*/
|
|
886
|
+
async validateSeedWithWdk(seed) {
|
|
887
|
+
return await this.wdkService.isValidSeed(seed);
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Validate a BIP-39 seed phrase
|
|
891
|
+
*/
|
|
892
|
+
static validateSeed(seed) {
|
|
893
|
+
return KeyManager.validateSeedPhrase(seed);
|
|
894
|
+
}
|
|
895
|
+
/**
|
|
896
|
+
* Derive Ethereum address from seed phrase using BIP-44 path
|
|
897
|
+
* Path: m/44'/60'/0'/0/0
|
|
898
|
+
*/
|
|
899
|
+
static deriveAddress(seed) {
|
|
900
|
+
const hdNode = HDNodeWallet.fromPhrase(seed, void 0, "m/44'/60'/0'/0/0");
|
|
901
|
+
return hdNode.address;
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Get the HDNodeWallet for signing transactions
|
|
905
|
+
*/
|
|
906
|
+
static getWallet(seed) {
|
|
907
|
+
return HDNodeWallet.fromPhrase(seed, void 0, "m/44'/60'/0'/0/0");
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* Initialize storage with password (required for web platform)
|
|
911
|
+
*/
|
|
912
|
+
async initializeStorage(password) {
|
|
913
|
+
if (this.storage instanceof WebEncryptedStorageAdapter) {
|
|
914
|
+
await this.storage.initialize(password);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* Create a new wallet with generated seed
|
|
919
|
+
*/
|
|
920
|
+
async createWallet(password) {
|
|
921
|
+
const seed = _WalletManager.generateSeed();
|
|
922
|
+
const address = _WalletManager.deriveAddress(seed);
|
|
923
|
+
const encrypted = await KeyManager.encryptSeed(seed, password);
|
|
924
|
+
await this.storage.setItem(STORAGE_KEYS.ENCRYPTED_SEED, encrypted);
|
|
925
|
+
this.currentSeed = seed;
|
|
926
|
+
this.derivedAddress = address;
|
|
927
|
+
return { seed, address };
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Import an existing wallet from seed phrase
|
|
931
|
+
*/
|
|
932
|
+
async importWallet(seed, password) {
|
|
933
|
+
if (!_WalletManager.validateSeed(seed)) {
|
|
934
|
+
throw new Error("Invalid seed phrase");
|
|
935
|
+
}
|
|
936
|
+
const address = _WalletManager.deriveAddress(seed);
|
|
937
|
+
const encrypted = await KeyManager.encryptSeed(seed, password);
|
|
938
|
+
await this.storage.setItem(STORAGE_KEYS.ENCRYPTED_SEED, encrypted);
|
|
939
|
+
this.currentSeed = seed;
|
|
940
|
+
this.derivedAddress = address;
|
|
941
|
+
return { address };
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Unlock wallet with password
|
|
945
|
+
*/
|
|
946
|
+
async unlock(password) {
|
|
947
|
+
const encrypted = await this.storage.getItem(STORAGE_KEYS.ENCRYPTED_SEED);
|
|
948
|
+
if (!encrypted) {
|
|
949
|
+
throw new Error("No wallet found");
|
|
950
|
+
}
|
|
951
|
+
try {
|
|
952
|
+
const seed = await KeyManager.decryptSeed(encrypted, password);
|
|
953
|
+
const address = _WalletManager.deriveAddress(seed);
|
|
954
|
+
this.currentSeed = seed;
|
|
955
|
+
this.derivedAddress = address;
|
|
956
|
+
return { address };
|
|
957
|
+
} catch {
|
|
958
|
+
throw new Error("Invalid password");
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
/**
|
|
962
|
+
* Lock wallet (clear seed from memory)
|
|
963
|
+
*/
|
|
964
|
+
lock() {
|
|
965
|
+
this.currentSeed = null;
|
|
966
|
+
this.wdkService.dispose();
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* Check if wallet exists in storage
|
|
970
|
+
*/
|
|
971
|
+
async hasWallet() {
|
|
972
|
+
return this.storage.hasItem(STORAGE_KEYS.ENCRYPTED_SEED);
|
|
973
|
+
}
|
|
974
|
+
/**
|
|
975
|
+
* Delete wallet from storage
|
|
976
|
+
*/
|
|
977
|
+
async deleteWallet() {
|
|
978
|
+
await this.storage.removeItem(STORAGE_KEYS.ENCRYPTED_SEED);
|
|
979
|
+
this.currentSeed = null;
|
|
980
|
+
this.derivedAddress = null;
|
|
981
|
+
this.derivedAddresses = {};
|
|
982
|
+
this.wdkService.dispose();
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* Get current wallet state
|
|
986
|
+
*/
|
|
987
|
+
getState() {
|
|
988
|
+
return {
|
|
989
|
+
isInitialized: this.derivedAddress !== null,
|
|
990
|
+
isLocked: this.currentSeed === null && this.derivedAddress !== null,
|
|
991
|
+
address: this.derivedAddress,
|
|
992
|
+
balance: null
|
|
993
|
+
// Use fetchBalance for current balance
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
/**
|
|
997
|
+
* Get current address (if unlocked)
|
|
998
|
+
*/
|
|
999
|
+
getAddress() {
|
|
1000
|
+
return this.derivedAddress;
|
|
1001
|
+
}
|
|
1002
|
+
/**
|
|
1003
|
+
* Check if wallet is unlocked
|
|
1004
|
+
*/
|
|
1005
|
+
isUnlocked() {
|
|
1006
|
+
return this.currentSeed !== null;
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* Get the seed phrase (only if unlocked)
|
|
1010
|
+
*/
|
|
1011
|
+
getSeed() {
|
|
1012
|
+
return this.currentSeed;
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Fetch balance for current address with timeout handling
|
|
1016
|
+
*/
|
|
1017
|
+
async fetchBalance() {
|
|
1018
|
+
if (!this.derivedAddress) {
|
|
1019
|
+
throw new Error("Wallet not initialized");
|
|
1020
|
+
}
|
|
1021
|
+
const chain = this.config.network === "mainnet" ? mainnet : sepolia;
|
|
1022
|
+
const client = createPublicClient({
|
|
1023
|
+
chain,
|
|
1024
|
+
transport: http(this.config.rpcUrl, {
|
|
1025
|
+
timeout: 15e3,
|
|
1026
|
+
// 15 second timeout
|
|
1027
|
+
retryCount: 2,
|
|
1028
|
+
retryDelay: 1e3
|
|
1029
|
+
})
|
|
1030
|
+
});
|
|
1031
|
+
try {
|
|
1032
|
+
const balance = await client.getBalance({
|
|
1033
|
+
address: this.derivedAddress
|
|
1034
|
+
});
|
|
1035
|
+
return formatEther(balance);
|
|
1036
|
+
} catch (error) {
|
|
1037
|
+
console.warn("Failed to fetch balance:", error);
|
|
1038
|
+
return "0";
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
/**
|
|
1042
|
+
* Create viem public client for the current network
|
|
1043
|
+
*/
|
|
1044
|
+
getPublicClient() {
|
|
1045
|
+
const chain = this.config.network === "mainnet" ? mainnet : sepolia;
|
|
1046
|
+
return createPublicClient({
|
|
1047
|
+
chain,
|
|
1048
|
+
transport: http(this.config.rpcUrl, {
|
|
1049
|
+
timeout: 15e3,
|
|
1050
|
+
// 15 second timeout
|
|
1051
|
+
retryCount: 2,
|
|
1052
|
+
retryDelay: 1e3
|
|
1053
|
+
})
|
|
1054
|
+
});
|
|
1055
|
+
}
|
|
1056
|
+
/**
|
|
1057
|
+
* Get ethers wallet for signing (only if unlocked)
|
|
1058
|
+
*/
|
|
1059
|
+
getEthersWallet() {
|
|
1060
|
+
if (!this.currentSeed) return null;
|
|
1061
|
+
return _WalletManager.getWallet(this.currentSeed);
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Set active wallet preference
|
|
1065
|
+
*/
|
|
1066
|
+
async setActiveWalletPreference(wallet) {
|
|
1067
|
+
await this.storage.setItem(STORAGE_KEYS.ACTIVE_WALLET, wallet);
|
|
1068
|
+
}
|
|
1069
|
+
/**
|
|
1070
|
+
* Get active wallet preference
|
|
1071
|
+
*/
|
|
1072
|
+
async getActiveWalletPreference() {
|
|
1073
|
+
const stored = await this.storage.getItem(STORAGE_KEYS.ACTIVE_WALLET);
|
|
1074
|
+
return stored === "metamask" || stored === "wdk" ? stored : "metamask";
|
|
1075
|
+
}
|
|
1076
|
+
// ==========================================
|
|
1077
|
+
// Multi-Chain Support Methods (Powered by Tether WDK)
|
|
1078
|
+
// ==========================================
|
|
1079
|
+
/**
|
|
1080
|
+
* Derive address for a specific chain (async version)
|
|
1081
|
+
*
|
|
1082
|
+
* Calls the backend WDK API for proper derivation when available.
|
|
1083
|
+
* Falls back to local ethers-based derivation if API is unavailable.
|
|
1084
|
+
*/
|
|
1085
|
+
static async deriveAddressForChainAsync(seed, chain, network = "testnet", apiUrl) {
|
|
1086
|
+
try {
|
|
1087
|
+
const wdkApi = getWdkApiClient(apiUrl);
|
|
1088
|
+
const response = await wdkApi.deriveAddress(seed, chain, network);
|
|
1089
|
+
if (response.success && response.address) {
|
|
1090
|
+
return response.address;
|
|
1091
|
+
}
|
|
1092
|
+
console.warn(`WDK API failed for ${chain}, using local derivation:`, response.error);
|
|
1093
|
+
} catch (error) {
|
|
1094
|
+
console.warn(`WDK API unavailable for ${chain}, using local derivation:`, error);
|
|
1095
|
+
}
|
|
1096
|
+
return _WalletManager.deriveAddressForChain(seed, chain);
|
|
1097
|
+
}
|
|
1098
|
+
/**
|
|
1099
|
+
* Format address for non-WDK chains (fallback)
|
|
1100
|
+
*
|
|
1101
|
+
* Note: This fallback produces PLACEHOLDER addresses derived from the seed.
|
|
1102
|
+
* For real blockchain interaction, use the WDK API via deriveAddressForChainAsync().
|
|
1103
|
+
* These addresses should NOT be used for receiving funds without verification.
|
|
1104
|
+
*/
|
|
1105
|
+
static formatAddressForChain(address, chain) {
|
|
1106
|
+
if (chain === "ethereum") {
|
|
1107
|
+
return address;
|
|
1108
|
+
}
|
|
1109
|
+
const addressBytes = address.toLowerCase().replace("0x", "");
|
|
1110
|
+
switch (chain) {
|
|
1111
|
+
case "bitcoin": {
|
|
1112
|
+
const btcChars = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
|
|
1113
|
+
let btcAddr = "tb1q";
|
|
1114
|
+
for (let i = 0; i < 38; i++) {
|
|
1115
|
+
const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) % btcChars.length;
|
|
1116
|
+
btcAddr += btcChars[idx];
|
|
1117
|
+
}
|
|
1118
|
+
return btcAddr;
|
|
1119
|
+
}
|
|
1120
|
+
case "ton": {
|
|
1121
|
+
const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
1122
|
+
let tonAddr = "EQ";
|
|
1123
|
+
for (let i = 0; i < 46; i++) {
|
|
1124
|
+
const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) * 4 % base64Chars.length;
|
|
1125
|
+
tonAddr += base64Chars[idx];
|
|
1126
|
+
}
|
|
1127
|
+
return tonAddr;
|
|
1128
|
+
}
|
|
1129
|
+
case "tron": {
|
|
1130
|
+
const base58Chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
1131
|
+
let tronAddr = "T";
|
|
1132
|
+
for (let i = 0; i < 33; i++) {
|
|
1133
|
+
const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) * 3 % base58Chars.length;
|
|
1134
|
+
tronAddr += base58Chars[idx];
|
|
1135
|
+
}
|
|
1136
|
+
return tronAddr;
|
|
1137
|
+
}
|
|
1138
|
+
case "solana": {
|
|
1139
|
+
const base58Chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
1140
|
+
let solAddr = "";
|
|
1141
|
+
for (let i = 0; i < 44; i++) {
|
|
1142
|
+
const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) * 3 % base58Chars.length;
|
|
1143
|
+
solAddr += base58Chars[idx];
|
|
1144
|
+
}
|
|
1145
|
+
return solAddr;
|
|
1146
|
+
}
|
|
1147
|
+
case "spark": {
|
|
1148
|
+
const bech32Chars = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
|
|
1149
|
+
let sparkAddr = "sp1q";
|
|
1150
|
+
for (let i = 0; i < 58; i++) {
|
|
1151
|
+
const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) % bech32Chars.length;
|
|
1152
|
+
sparkAddr += bech32Chars[idx];
|
|
1153
|
+
}
|
|
1154
|
+
return sparkAddr;
|
|
1155
|
+
}
|
|
1156
|
+
default:
|
|
1157
|
+
return address;
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
/**
|
|
1161
|
+
* Derive address for a specific chain (sync version for backwards compatibility)
|
|
1162
|
+
* Uses ethers for basic derivation, use deriveAddressForChainAsync for WDK
|
|
1163
|
+
*
|
|
1164
|
+
* Note: For non-Ethereum chains, this produces placeholder addresses that are
|
|
1165
|
+
* deterministic but not cryptographically valid. Use WDK API for real addresses.
|
|
1166
|
+
*/
|
|
1167
|
+
static deriveAddressForChain(seed, chain) {
|
|
1168
|
+
const ethPath = DERIVATION_PATHS["ethereum"];
|
|
1169
|
+
const ethNode = HDNodeWallet.fromPhrase(seed, void 0, `${ethPath}/0`);
|
|
1170
|
+
if (chain === "ethereum") {
|
|
1171
|
+
return ethNode.address;
|
|
1172
|
+
}
|
|
1173
|
+
return _WalletManager.formatAddressForChain(ethNode.address, chain);
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* Derive addresses for all enabled chains (sync version)
|
|
1177
|
+
*/
|
|
1178
|
+
deriveAllAddresses() {
|
|
1179
|
+
if (!this.currentSeed) {
|
|
1180
|
+
throw new Error("Wallet is locked");
|
|
1181
|
+
}
|
|
1182
|
+
const addresses = {};
|
|
1183
|
+
for (const chain of this.config.enabledChains) {
|
|
1184
|
+
addresses[chain] = _WalletManager.deriveAddressForChain(this.currentSeed, chain);
|
|
1185
|
+
}
|
|
1186
|
+
this.derivedAddresses = addresses;
|
|
1187
|
+
return addresses;
|
|
1188
|
+
}
|
|
1189
|
+
/**
|
|
1190
|
+
* Derive addresses for all enabled chains using native Tether WDK (recommended)
|
|
1191
|
+
* This uses the WDK directly without needing a backend API.
|
|
1192
|
+
* Returns REAL cryptographically valid addresses for all chains.
|
|
1193
|
+
*/
|
|
1194
|
+
async deriveAllAddressesWithWdk() {
|
|
1195
|
+
if (!this.currentSeed) {
|
|
1196
|
+
throw new Error("Wallet is locked");
|
|
1197
|
+
}
|
|
1198
|
+
try {
|
|
1199
|
+
await this.wdkService.initialize(this.currentSeed);
|
|
1200
|
+
const enabledChainsSet = new Set(this.config.enabledChains);
|
|
1201
|
+
const wdkAddresses = await this.wdkService.deriveAllAddresses();
|
|
1202
|
+
const addresses = {};
|
|
1203
|
+
for (const [chain, address] of Object.entries(wdkAddresses)) {
|
|
1204
|
+
if (enabledChainsSet.has(chain) && address) {
|
|
1205
|
+
addresses[chain] = address;
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
this.derivedAddresses = addresses;
|
|
1209
|
+
return addresses;
|
|
1210
|
+
} catch (error) {
|
|
1211
|
+
console.error("Native WDK derivation failed:", error);
|
|
1212
|
+
throw error;
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
/**
|
|
1216
|
+
* Derive addresses for all enabled chains using Tether WDK
|
|
1217
|
+
* Tries native WDK first, then falls back to API, then to placeholders
|
|
1218
|
+
*/
|
|
1219
|
+
async deriveAllAddressesAsync() {
|
|
1220
|
+
if (!this.currentSeed) {
|
|
1221
|
+
throw new Error("Wallet is locked");
|
|
1222
|
+
}
|
|
1223
|
+
try {
|
|
1224
|
+
return await this.deriveAllAddressesWithWdk();
|
|
1225
|
+
} catch (wdkError) {
|
|
1226
|
+
console.warn("Native WDK failed, trying API:", wdkError);
|
|
1227
|
+
}
|
|
1228
|
+
try {
|
|
1229
|
+
const wdkApi = getWdkApiClient(this.config.apiUrl);
|
|
1230
|
+
const response = await wdkApi.deriveAllAddresses(this.currentSeed, this.config.network);
|
|
1231
|
+
if (response.success && response.addresses) {
|
|
1232
|
+
const addresses = {};
|
|
1233
|
+
for (const chain of this.config.enabledChains) {
|
|
1234
|
+
const address = response.addresses[chain];
|
|
1235
|
+
if (address) {
|
|
1236
|
+
addresses[chain] = address;
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
this.derivedAddresses = addresses;
|
|
1240
|
+
return addresses;
|
|
1241
|
+
}
|
|
1242
|
+
console.warn("WDK API call failed:", response.error);
|
|
1243
|
+
} catch (apiError) {
|
|
1244
|
+
console.warn("WDK API unavailable:", apiError);
|
|
1245
|
+
}
|
|
1246
|
+
console.warn("WARNING: Using placeholder addresses. These are NOT valid for receiving funds!");
|
|
1247
|
+
return this.deriveAllAddresses();
|
|
1248
|
+
}
|
|
1249
|
+
/**
|
|
1250
|
+
* Get address for a specific chain
|
|
1251
|
+
*/
|
|
1252
|
+
getAddressForChain(chain) {
|
|
1253
|
+
if (!this.currentSeed) {
|
|
1254
|
+
return this.derivedAddresses[chain] || null;
|
|
1255
|
+
}
|
|
1256
|
+
if (!this.derivedAddresses[chain]) {
|
|
1257
|
+
this.derivedAddresses[chain] = _WalletManager.deriveAddressForChain(this.currentSeed, chain);
|
|
1258
|
+
}
|
|
1259
|
+
return this.derivedAddresses[chain] || null;
|
|
1260
|
+
}
|
|
1261
|
+
/**
|
|
1262
|
+
* Get all derived addresses
|
|
1263
|
+
*/
|
|
1264
|
+
getAllAddresses() {
|
|
1265
|
+
return { ...this.derivedAddresses };
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* Set the selected chain
|
|
1269
|
+
*/
|
|
1270
|
+
setSelectedChain(chain) {
|
|
1271
|
+
if (!this.config.enabledChains.includes(chain)) {
|
|
1272
|
+
throw new Error(`Chain ${chain} is not enabled`);
|
|
1273
|
+
}
|
|
1274
|
+
this.selectedChain = chain;
|
|
1275
|
+
}
|
|
1276
|
+
/**
|
|
1277
|
+
* Get the currently selected chain
|
|
1278
|
+
*/
|
|
1279
|
+
getSelectedChain() {
|
|
1280
|
+
return this.selectedChain;
|
|
1281
|
+
}
|
|
1282
|
+
/**
|
|
1283
|
+
* Get enabled chains
|
|
1284
|
+
*/
|
|
1285
|
+
getEnabledChains() {
|
|
1286
|
+
return [...this.config.enabledChains];
|
|
1287
|
+
}
|
|
1288
|
+
/**
|
|
1289
|
+
* Get chain configuration
|
|
1290
|
+
*/
|
|
1291
|
+
getChainConfig(chain) {
|
|
1292
|
+
return getNetworkConfig(chain, this.config.network === "testnet");
|
|
1293
|
+
}
|
|
1294
|
+
/**
|
|
1295
|
+
* Fetch balance for a specific chain
|
|
1296
|
+
* Note: Currently only Ethereum is implemented
|
|
1297
|
+
*/
|
|
1298
|
+
async fetchBalanceForChain(chain) {
|
|
1299
|
+
const address = this.getAddressForChain(chain);
|
|
1300
|
+
if (!address) {
|
|
1301
|
+
throw new Error(`No address for chain ${chain}`);
|
|
1302
|
+
}
|
|
1303
|
+
const networkConfig = this.getChainConfig(chain);
|
|
1304
|
+
let balance = "0";
|
|
1305
|
+
if (chain === "ethereum") {
|
|
1306
|
+
const viemChain = this.config.network === "mainnet" ? mainnet : sepolia;
|
|
1307
|
+
const client = createPublicClient({
|
|
1308
|
+
chain: viemChain,
|
|
1309
|
+
transport: http(this.config.rpcUrl, {
|
|
1310
|
+
timeout: 15e3,
|
|
1311
|
+
// 15 second timeout
|
|
1312
|
+
retryCount: 2,
|
|
1313
|
+
retryDelay: 1e3
|
|
1314
|
+
})
|
|
1315
|
+
});
|
|
1316
|
+
try {
|
|
1317
|
+
const rawBalance = await client.getBalance({
|
|
1318
|
+
address
|
|
1319
|
+
});
|
|
1320
|
+
balance = formatEther(rawBalance);
|
|
1321
|
+
} catch (error) {
|
|
1322
|
+
console.warn(`Failed to fetch ${chain} balance:`, error);
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
return {
|
|
1326
|
+
chain,
|
|
1327
|
+
symbol: networkConfig.nativeCurrency.symbol,
|
|
1328
|
+
balance,
|
|
1329
|
+
balanceUsd: 0,
|
|
1330
|
+
// TODO: Implement price fetching
|
|
1331
|
+
address,
|
|
1332
|
+
decimals: networkConfig.nativeCurrency.decimals
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* Fetch balances for all enabled chains
|
|
1337
|
+
*/
|
|
1338
|
+
async fetchAllBalances() {
|
|
1339
|
+
const balances = [];
|
|
1340
|
+
for (const chain of this.config.enabledChains) {
|
|
1341
|
+
try {
|
|
1342
|
+
const balance = await this.fetchBalanceForChain(chain);
|
|
1343
|
+
balances.push(balance);
|
|
1344
|
+
} catch (error) {
|
|
1345
|
+
console.error(`Failed to fetch balance for ${chain}:`, error);
|
|
1346
|
+
const networkConfig = this.getChainConfig(chain);
|
|
1347
|
+
balances.push({
|
|
1348
|
+
chain,
|
|
1349
|
+
symbol: networkConfig.nativeCurrency.symbol,
|
|
1350
|
+
balance: "0",
|
|
1351
|
+
balanceUsd: 0,
|
|
1352
|
+
address: this.getAddressForChain(chain) || "",
|
|
1353
|
+
decimals: networkConfig.nativeCurrency.decimals
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
return balances;
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* Get extended wallet state with multi-chain info
|
|
1361
|
+
*/
|
|
1362
|
+
getExtendedState() {
|
|
1363
|
+
return {
|
|
1364
|
+
isInitialized: this.derivedAddress !== null,
|
|
1365
|
+
isLocked: this.currentSeed === null && this.derivedAddress !== null,
|
|
1366
|
+
address: this.derivedAddress,
|
|
1367
|
+
balance: null,
|
|
1368
|
+
addresses: this.derivedAddresses,
|
|
1369
|
+
selectedChain: this.selectedChain
|
|
1370
|
+
};
|
|
1371
|
+
}
|
|
1372
|
+
};
|
|
1373
|
+
|
|
1374
|
+
// src/react/useWalletManager.ts
|
|
1375
|
+
function useWalletManager(options = {}) {
|
|
1376
|
+
const { autoCheckWallet = true, ...config } = options;
|
|
1377
|
+
const manager = useMemo(() => new WalletManager(config), [
|
|
1378
|
+
config.network,
|
|
1379
|
+
config.rpcUrl
|
|
1380
|
+
]);
|
|
1381
|
+
const [state, setState] = useState({
|
|
1382
|
+
isInitialized: false,
|
|
1383
|
+
isLocked: true,
|
|
1384
|
+
address: null,
|
|
1385
|
+
balance: null
|
|
1386
|
+
});
|
|
1387
|
+
const [isLoading, setIsLoading] = useState(false);
|
|
1388
|
+
const [error, setError] = useState(null);
|
|
1389
|
+
const [selectedChain, setSelectedChainState] = useState("ethereum");
|
|
1390
|
+
const [chainBalances, setChainBalances] = useState([]);
|
|
1391
|
+
const updateState = useCallback(() => {
|
|
1392
|
+
setState(manager.getExtendedState());
|
|
1393
|
+
}, [manager]);
|
|
1394
|
+
useEffect(() => {
|
|
1395
|
+
if (autoCheckWallet) {
|
|
1396
|
+
manager.hasWallet().then((exists) => {
|
|
1397
|
+
if (exists) {
|
|
1398
|
+
setState((prev) => ({
|
|
1399
|
+
...prev,
|
|
1400
|
+
isInitialized: true,
|
|
1401
|
+
isLocked: true
|
|
1402
|
+
}));
|
|
1403
|
+
}
|
|
1404
|
+
});
|
|
1405
|
+
}
|
|
1406
|
+
}, [manager, autoCheckWallet]);
|
|
1407
|
+
const createWallet = useCallback(
|
|
1408
|
+
async (password) => {
|
|
1409
|
+
setIsLoading(true);
|
|
1410
|
+
setError(null);
|
|
1411
|
+
try {
|
|
1412
|
+
await manager.initializeStorage(password);
|
|
1413
|
+
const result = await manager.createWallet(password);
|
|
1414
|
+
try {
|
|
1415
|
+
await manager.deriveAllAddressesAsync();
|
|
1416
|
+
} catch {
|
|
1417
|
+
manager.deriveAllAddresses();
|
|
1418
|
+
}
|
|
1419
|
+
updateState();
|
|
1420
|
+
return result;
|
|
1421
|
+
} catch (err) {
|
|
1422
|
+
const message = err instanceof Error ? err.message : "Failed to create wallet";
|
|
1423
|
+
setError(message);
|
|
1424
|
+
throw err;
|
|
1425
|
+
} finally {
|
|
1426
|
+
setIsLoading(false);
|
|
1427
|
+
}
|
|
1428
|
+
},
|
|
1429
|
+
[manager, updateState]
|
|
1430
|
+
);
|
|
1431
|
+
const importWallet = useCallback(
|
|
1432
|
+
async (seed, password) => {
|
|
1433
|
+
setIsLoading(true);
|
|
1434
|
+
setError(null);
|
|
1435
|
+
try {
|
|
1436
|
+
await manager.initializeStorage(password);
|
|
1437
|
+
await manager.importWallet(seed, password);
|
|
1438
|
+
try {
|
|
1439
|
+
await manager.deriveAllAddressesAsync();
|
|
1440
|
+
} catch {
|
|
1441
|
+
manager.deriveAllAddresses();
|
|
1442
|
+
}
|
|
1443
|
+
updateState();
|
|
1444
|
+
} catch (err) {
|
|
1445
|
+
const message = err instanceof Error ? err.message : "Failed to import wallet";
|
|
1446
|
+
setError(message);
|
|
1447
|
+
throw err;
|
|
1448
|
+
} finally {
|
|
1449
|
+
setIsLoading(false);
|
|
1450
|
+
}
|
|
1451
|
+
},
|
|
1452
|
+
[manager, updateState]
|
|
1453
|
+
);
|
|
1454
|
+
const unlock = useCallback(
|
|
1455
|
+
async (password) => {
|
|
1456
|
+
setIsLoading(true);
|
|
1457
|
+
setError(null);
|
|
1458
|
+
try {
|
|
1459
|
+
await manager.initializeStorage(password);
|
|
1460
|
+
await manager.unlock(password);
|
|
1461
|
+
try {
|
|
1462
|
+
await manager.deriveAllAddressesAsync();
|
|
1463
|
+
} catch {
|
|
1464
|
+
manager.deriveAllAddresses();
|
|
1465
|
+
}
|
|
1466
|
+
updateState();
|
|
1467
|
+
} catch (err) {
|
|
1468
|
+
const message = err instanceof Error ? err.message : "Invalid password";
|
|
1469
|
+
setError(message);
|
|
1470
|
+
throw err;
|
|
1471
|
+
} finally {
|
|
1472
|
+
setIsLoading(false);
|
|
1473
|
+
}
|
|
1474
|
+
},
|
|
1475
|
+
[manager, updateState]
|
|
1476
|
+
);
|
|
1477
|
+
const lock = useCallback(() => {
|
|
1478
|
+
manager.lock();
|
|
1479
|
+
setChainBalances([]);
|
|
1480
|
+
updateState();
|
|
1481
|
+
}, [manager, updateState]);
|
|
1482
|
+
const deleteWallet = useCallback(async () => {
|
|
1483
|
+
setIsLoading(true);
|
|
1484
|
+
setError(null);
|
|
1485
|
+
try {
|
|
1486
|
+
await manager.deleteWallet();
|
|
1487
|
+
setChainBalances([]);
|
|
1488
|
+
setState({
|
|
1489
|
+
isInitialized: false,
|
|
1490
|
+
isLocked: true,
|
|
1491
|
+
address: null,
|
|
1492
|
+
balance: null
|
|
1493
|
+
});
|
|
1494
|
+
} catch (err) {
|
|
1495
|
+
const message = err instanceof Error ? err.message : "Failed to delete wallet";
|
|
1496
|
+
setError(message);
|
|
1497
|
+
throw err;
|
|
1498
|
+
} finally {
|
|
1499
|
+
setIsLoading(false);
|
|
1500
|
+
}
|
|
1501
|
+
}, [manager]);
|
|
1502
|
+
const fetchBalance = useCallback(async () => {
|
|
1503
|
+
setIsLoading(true);
|
|
1504
|
+
try {
|
|
1505
|
+
const balance = await manager.fetchBalance();
|
|
1506
|
+
setState((prev) => ({ ...prev, balance }));
|
|
1507
|
+
return balance;
|
|
1508
|
+
} catch (err) {
|
|
1509
|
+
console.warn("Failed to fetch balance:", err);
|
|
1510
|
+
setState((prev) => ({ ...prev, balance: "0" }));
|
|
1511
|
+
return "0";
|
|
1512
|
+
} finally {
|
|
1513
|
+
setIsLoading(false);
|
|
1514
|
+
}
|
|
1515
|
+
}, [manager]);
|
|
1516
|
+
const fetchAllBalances = useCallback(async () => {
|
|
1517
|
+
setIsLoading(true);
|
|
1518
|
+
try {
|
|
1519
|
+
const balances = await manager.fetchAllBalances();
|
|
1520
|
+
setChainBalances(balances);
|
|
1521
|
+
return balances;
|
|
1522
|
+
} catch (err) {
|
|
1523
|
+
console.warn("Failed to fetch all balances:", err);
|
|
1524
|
+
return [];
|
|
1525
|
+
} finally {
|
|
1526
|
+
setIsLoading(false);
|
|
1527
|
+
}
|
|
1528
|
+
}, [manager]);
|
|
1529
|
+
const setSelectedChain = useCallback((chain) => {
|
|
1530
|
+
manager.setSelectedChain(chain);
|
|
1531
|
+
setSelectedChainState(chain);
|
|
1532
|
+
}, [manager]);
|
|
1533
|
+
const getAddressForChain = useCallback(
|
|
1534
|
+
(chain) => manager.getAddressForChain(chain),
|
|
1535
|
+
[manager]
|
|
1536
|
+
);
|
|
1537
|
+
const getAllAddresses = useCallback(
|
|
1538
|
+
() => manager.getAllAddresses(),
|
|
1539
|
+
[manager]
|
|
1540
|
+
);
|
|
1541
|
+
const hasWallet = useCallback(() => manager.hasWallet(), [manager]);
|
|
1542
|
+
const getSeed = useCallback(() => manager.getSeed(), [manager]);
|
|
1543
|
+
return {
|
|
1544
|
+
state,
|
|
1545
|
+
isLoading,
|
|
1546
|
+
error,
|
|
1547
|
+
createWallet,
|
|
1548
|
+
importWallet,
|
|
1549
|
+
unlock,
|
|
1550
|
+
lock,
|
|
1551
|
+
deleteWallet,
|
|
1552
|
+
fetchBalance,
|
|
1553
|
+
// Multi-chain
|
|
1554
|
+
selectedChain,
|
|
1555
|
+
setSelectedChain,
|
|
1556
|
+
chainBalances,
|
|
1557
|
+
fetchAllBalances,
|
|
1558
|
+
getAddressForChain,
|
|
1559
|
+
getAllAddresses,
|
|
1560
|
+
supportedChains: SUPPORTED_CHAINS,
|
|
1561
|
+
// Utilities
|
|
1562
|
+
hasWallet,
|
|
1563
|
+
getSeed,
|
|
1564
|
+
manager
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
export { SUPPORTED_CHAINS, useWalletManager };
|
|
1569
|
+
//# sourceMappingURL=index.mjs.map
|
|
1570
|
+
//# sourceMappingURL=index.mjs.map
|