@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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +324 -0
  3. package/dist/SecureStorage-jO783AhC.d.mts +89 -0
  4. package/dist/SecureStorage-jO783AhC.d.ts +89 -0
  5. package/dist/SwapService-C0G8IXW2.d.mts +35 -0
  6. package/dist/SwapService-DZD0OJI_.d.ts +35 -0
  7. package/dist/WalletManager-DJjdq89b.d.mts +6106 -0
  8. package/dist/WalletManager-TiAdzqrn.d.ts +6106 -0
  9. package/dist/index-BLuxEdLp.d.mts +156 -0
  10. package/dist/index-BLuxEdLp.d.ts +156 -0
  11. package/dist/index-DO3T2HVe.d.ts +135 -0
  12. package/dist/index-fXVD8_D0.d.mts +135 -0
  13. package/dist/index.d.mts +67 -0
  14. package/dist/index.d.ts +67 -0
  15. package/dist/index.js +2411 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/index.mjs +2386 -0
  18. package/dist/index.mjs.map +1 -0
  19. package/dist/protocols/index.d.mts +181 -0
  20. package/dist/protocols/index.d.ts +181 -0
  21. package/dist/protocols/index.js +415 -0
  22. package/dist/protocols/index.js.map +1 -0
  23. package/dist/protocols/index.mjs +410 -0
  24. package/dist/protocols/index.mjs.map +1 -0
  25. package/dist/react/index.d.mts +49 -0
  26. package/dist/react/index.d.ts +49 -0
  27. package/dist/react/index.js +1573 -0
  28. package/dist/react/index.js.map +1 -0
  29. package/dist/react/index.mjs +1570 -0
  30. package/dist/react/index.mjs.map +1 -0
  31. package/dist/services/index.d.mts +198 -0
  32. package/dist/services/index.d.ts +198 -0
  33. package/dist/services/index.js +554 -0
  34. package/dist/services/index.js.map +1 -0
  35. package/dist/services/index.mjs +547 -0
  36. package/dist/services/index.mjs.map +1 -0
  37. package/dist/storage/index.d.mts +57 -0
  38. package/dist/storage/index.d.ts +57 -0
  39. package/dist/storage/index.js +442 -0
  40. package/dist/storage/index.js.map +1 -0
  41. package/dist/storage/index.mjs +435 -0
  42. package/dist/storage/index.mjs.map +1 -0
  43. package/dist/wallet/index.d.mts +8 -0
  44. package/dist/wallet/index.d.ts +8 -0
  45. package/dist/wallet/index.js +1678 -0
  46. package/dist/wallet/index.js.map +1 -0
  47. package/dist/wallet/index.mjs +1674 -0
  48. package/dist/wallet/index.mjs.map +1 -0
  49. package/package.json +136 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,2386 @@
1
+ import { Wallet, HDNodeWallet } from 'ethers';
2
+ import { createPublicClient, http, formatEther } from 'viem';
3
+ import { mainnet, sepolia } from 'viem/chains';
4
+ import { useMemo, useState, useCallback, useEffect } from 'react';
5
+
6
+ // src/config/networks.ts
7
+ var NETWORKS = {
8
+ bitcoin: {
9
+ name: "Bitcoin",
10
+ chainId: 0,
11
+ coinType: 0,
12
+ // m/44'/0'
13
+ rpcUrl: "https://blockstream.info/api",
14
+ explorerUrl: "https://blockstream.info",
15
+ nativeCurrency: {
16
+ name: "Bitcoin",
17
+ symbol: "BTC",
18
+ decimals: 8
19
+ },
20
+ isEvm: false
21
+ },
22
+ ethereum: {
23
+ name: "Ethereum",
24
+ chainId: 1,
25
+ coinType: 60,
26
+ // m/44'/60'
27
+ rpcUrl: "https://eth.llamarpc.com",
28
+ explorerUrl: "https://etherscan.io",
29
+ nativeCurrency: {
30
+ name: "Ether",
31
+ symbol: "ETH",
32
+ decimals: 18
33
+ },
34
+ isEvm: true
35
+ },
36
+ ton: {
37
+ name: "TON",
38
+ chainId: -239,
39
+ coinType: 607,
40
+ // m/44'/607'
41
+ rpcUrl: "https://toncenter.com/api/v2",
42
+ explorerUrl: "https://tonscan.org",
43
+ nativeCurrency: {
44
+ name: "Toncoin",
45
+ symbol: "TON",
46
+ decimals: 9
47
+ },
48
+ isEvm: false
49
+ },
50
+ tron: {
51
+ name: "TRON",
52
+ chainId: 728126428,
53
+ coinType: 195,
54
+ // m/44'/195'
55
+ rpcUrl: "https://api.trongrid.io",
56
+ explorerUrl: "https://tronscan.org",
57
+ nativeCurrency: {
58
+ name: "TRON",
59
+ symbol: "TRX",
60
+ decimals: 6
61
+ },
62
+ isEvm: false
63
+ },
64
+ solana: {
65
+ name: "Solana",
66
+ chainId: 0,
67
+ coinType: 501,
68
+ // m/44'/501'
69
+ rpcUrl: "https://api.mainnet-beta.solana.com",
70
+ explorerUrl: "https://solscan.io",
71
+ nativeCurrency: {
72
+ name: "Solana",
73
+ symbol: "SOL",
74
+ decimals: 9
75
+ },
76
+ isEvm: false
77
+ },
78
+ spark: {
79
+ name: "Spark (Lightning)",
80
+ chainId: 0,
81
+ coinType: 998,
82
+ // m/44'/998'
83
+ rpcUrl: "",
84
+ explorerUrl: "",
85
+ nativeCurrency: {
86
+ name: "Bitcoin",
87
+ symbol: "BTC",
88
+ decimals: 8
89
+ },
90
+ isEvm: false
91
+ }
92
+ };
93
+ var TESTNET_NETWORKS = {
94
+ ethereum: {
95
+ name: "Sepolia",
96
+ chainId: 11155111,
97
+ // Using eth-sepolia.g.alchemy.com public endpoint (more reliable than rpc.sepolia.org)
98
+ // Fallback order: 1. Alchemy public, 2. Infura public, 3. BlockPi
99
+ rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
100
+ explorerUrl: "https://sepolia.etherscan.io"
101
+ },
102
+ solana: {
103
+ name: "Solana Devnet",
104
+ rpcUrl: "https://api.devnet.solana.com",
105
+ explorerUrl: "https://solscan.io?cluster=devnet"
106
+ }
107
+ };
108
+ var DERIVATION_PATHS = {
109
+ bitcoin: "m/44'/0'/0'/0",
110
+ ethereum: "m/44'/60'/0'/0",
111
+ ton: "m/44'/607'/0'/0",
112
+ tron: "m/44'/195'/0'/0",
113
+ solana: "m/44'/501'/0'/0",
114
+ spark: "m/44'/998'/0'/0"
115
+ };
116
+ function getNetworkConfig(network, isTestnet = false) {
117
+ const mainnetConfig = NETWORKS[network];
118
+ if (!isTestnet) return mainnetConfig;
119
+ const testnetOverrides = TESTNET_NETWORKS[network];
120
+ if (!testnetOverrides) return mainnetConfig;
121
+ return {
122
+ ...mainnetConfig,
123
+ ...testnetOverrides
124
+ };
125
+ }
126
+
127
+ // src/config/contracts.ts
128
+ var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
129
+ var ZUBARI_CONTRACTS = {
130
+ testnet: {
131
+ // Ethereum Sepolia (11155111) - Deployed 2024-12-09
132
+ registry: "0xEdDf443D48832f23D4A0bED4C4c5eF200B38A7d3",
133
+ nft: "0xdc37e25650D685e4c38124aC314477Ea5f508a9e",
134
+ marketplace: ZERO_ADDRESS,
135
+ // Not yet deployed
136
+ tips: "0xFDc353edC63Cd3D4bba35bB43861369516a9Dc85",
137
+ subscriptions: "0x8C05F8aD2F295fB7f3596043a7c37C98A5F7fAB8",
138
+ payouts: "0x804Fe503936E8b8d3D5Dbb62AF4fB6Fe7265Fb2c",
139
+ entryPoint: "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",
140
+ paymaster: ZERO_ADDRESS,
141
+ // Not yet deployed
142
+ accountFactory: ZERO_ADDRESS,
143
+ // Not yet deployed
144
+ usdt: "0xaA8E23Fb1079EA71e0a56F48a2aA51851D8433D0",
145
+ // USDT on Sepolia
146
+ weth: "0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14"
147
+ },
148
+ mainnet: {
149
+ // Ethereum Mainnet (1)
150
+ registry: ZERO_ADDRESS,
151
+ nft: ZERO_ADDRESS,
152
+ marketplace: ZERO_ADDRESS,
153
+ tips: ZERO_ADDRESS,
154
+ subscriptions: ZERO_ADDRESS,
155
+ payouts: ZERO_ADDRESS,
156
+ entryPoint: "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789",
157
+ paymaster: ZERO_ADDRESS,
158
+ accountFactory: ZERO_ADDRESS,
159
+ usdt: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
160
+ // USDT on Ethereum
161
+ weth: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
162
+ }
163
+ };
164
+ var PLATFORM_CONFIG = {
165
+ // Platform fee in basis points (300 = 3%)
166
+ tipFeeBps: 300,
167
+ // Maximum royalty in basis points (1000 = 10%)
168
+ maxRoyaltyBps: 1e3,
169
+ // Default slippage tolerance for swaps (50 = 0.5%)
170
+ defaultSlippageBps: 50,
171
+ // Voucher validity in seconds (30 days)
172
+ voucherValiditySecs: 30 * 24 * 60 * 60,
173
+ // Swap deadline in seconds (30 minutes)
174
+ swapDeadlineSecs: 30 * 60
175
+ };
176
+ var NFT_VOUCHER_DOMAIN = {
177
+ name: "ZubariNFT",
178
+ version: "1"
179
+ };
180
+ var NFT_VOUCHER_TYPES = {
181
+ NFTVoucher: [
182
+ { name: "tokenId", type: "bytes32" },
183
+ { name: "uri", type: "string" },
184
+ { name: "creator", type: "address" },
185
+ { name: "royaltyBps", type: "uint256" },
186
+ { name: "deadline", type: "uint256" }
187
+ ]
188
+ };
189
+ function getContractAddresses(network) {
190
+ return ZUBARI_CONTRACTS[network];
191
+ }
192
+
193
+ // src/wallet/ZubariWallet.ts
194
+ var ZubariWallet = class {
195
+ seed;
196
+ config;
197
+ accounts = /* @__PURE__ */ new Map();
198
+ initialized = false;
199
+ constructor(seed, config) {
200
+ this.seed = seed;
201
+ this.config = {
202
+ network: config.network || "mainnet",
203
+ enabledNetworks: config.enabledNetworks || ["ethereum"],
204
+ gasless: config.gasless ?? false,
205
+ paymasterUrl: config.paymasterUrl,
206
+ bundlerUrl: config.bundlerUrl,
207
+ rpcUrls: config.rpcUrls
208
+ };
209
+ }
210
+ /**
211
+ * Initialize the wallet by deriving accounts for all enabled networks
212
+ */
213
+ async initialize() {
214
+ if (this.initialized) return;
215
+ for (const network of this.config.enabledNetworks) {
216
+ await this.deriveAccount(network);
217
+ }
218
+ this.initialized = true;
219
+ }
220
+ /**
221
+ * Derive account for a specific network using BIP-44
222
+ */
223
+ async deriveAccount(network, index = 0) {
224
+ getNetworkConfig(network, this.config.network === "testnet");
225
+ const basePath = DERIVATION_PATHS[network];
226
+ const derivationPath = `${basePath}/${index}`;
227
+ const account = {
228
+ network,
229
+ address: "",
230
+ // Will be derived using WDK
231
+ publicKey: "",
232
+ derivationPath
233
+ };
234
+ this.accounts.set(network, account);
235
+ return account;
236
+ }
237
+ /**
238
+ * Get account for a specific network
239
+ */
240
+ async getAccount(network, index = 0) {
241
+ const existing = this.accounts.get(network);
242
+ if (existing && existing.derivationPath.endsWith(`/${index}`)) {
243
+ return existing;
244
+ }
245
+ return this.deriveAccount(network, index);
246
+ }
247
+ /**
248
+ * Get address for a specific network
249
+ */
250
+ async getAddress(network) {
251
+ const account = await this.getAccount(network);
252
+ return account.address;
253
+ }
254
+ /**
255
+ * Get all addresses for enabled networks
256
+ */
257
+ async getAllAddresses() {
258
+ const addresses = {};
259
+ for (const network of this.config.enabledNetworks) {
260
+ addresses[network] = await this.getAddress(network);
261
+ }
262
+ return addresses;
263
+ }
264
+ /**
265
+ * Get balance for a specific network
266
+ */
267
+ async getBalance(network) {
268
+ const networkConfig = getNetworkConfig(network, this.config.network === "testnet");
269
+ return {
270
+ network,
271
+ native: {
272
+ symbol: networkConfig.nativeCurrency.symbol,
273
+ balance: BigInt(0),
274
+ balanceFormatted: "0",
275
+ balanceUsd: 0
276
+ },
277
+ tokens: []
278
+ };
279
+ }
280
+ /**
281
+ * Get balances for all enabled networks
282
+ */
283
+ async getAllBalances() {
284
+ const balances = [];
285
+ for (const network of this.config.enabledNetworks) {
286
+ balances.push(await this.getBalance(network));
287
+ }
288
+ return balances;
289
+ }
290
+ /**
291
+ * Get total portfolio value in USD
292
+ */
293
+ async getTotalPortfolioUsd() {
294
+ const balances = await this.getAllBalances();
295
+ let total = 0;
296
+ for (const balance of balances) {
297
+ total += balance.native.balanceUsd;
298
+ for (const token of balance.tokens) {
299
+ total += token.balanceUsd;
300
+ }
301
+ }
302
+ return total;
303
+ }
304
+ /**
305
+ * Send native currency on a specific network
306
+ */
307
+ async send(network, params) {
308
+ const { to, amount, gasless } = params;
309
+ gasless ?? (this.config.gasless && network === "ethereum");
310
+ return {
311
+ hash: "",
312
+ network,
313
+ status: "pending"
314
+ };
315
+ }
316
+ /**
317
+ * Send ERC-20 token on EVM networks
318
+ */
319
+ async sendToken(network, token, to, amount) {
320
+ const networkConfig = getNetworkConfig(network, this.config.network === "testnet");
321
+ if (!networkConfig.isEvm) {
322
+ throw new Error(`sendToken is only supported on EVM networks. ${network} is not an EVM chain.`);
323
+ }
324
+ return {
325
+ hash: "",
326
+ network,
327
+ status: "pending"
328
+ };
329
+ }
330
+ /**
331
+ * Send Bitcoin on-chain using WalletManagerBtc
332
+ * @param to - Destination address (bc1q... for native segwit)
333
+ * @param amount - Amount in satoshis
334
+ */
335
+ async sendBitcoin(to, amount) {
336
+ if (!this.isValidBitcoinAddress(to)) {
337
+ throw new Error("Invalid Bitcoin address. Expected bc1q... (native segwit) format.");
338
+ }
339
+ return this.send("bitcoin", { to, amount });
340
+ }
341
+ /**
342
+ * Validate Bitcoin address format
343
+ */
344
+ isValidBitcoinAddress(address) {
345
+ if (address.startsWith("bc1q") || address.startsWith("tb1q")) {
346
+ return address.length >= 42 && address.length <= 62;
347
+ }
348
+ if (address.startsWith("1") || address.startsWith("m") || address.startsWith("n")) {
349
+ return address.length >= 25 && address.length <= 34;
350
+ }
351
+ if (address.startsWith("3") || address.startsWith("2")) {
352
+ return address.length >= 25 && address.length <= 34;
353
+ }
354
+ return false;
355
+ }
356
+ /**
357
+ * Get Bitcoin address (native segwit bc1q...)
358
+ */
359
+ async getBitcoinAddress() {
360
+ const account = await this.getAccount("bitcoin");
361
+ return account.address;
362
+ }
363
+ /**
364
+ * Pay Lightning invoice via Spark network
365
+ * Uses WDK WalletManagerSpark (m/44'/998')
366
+ * @param invoice - Lightning invoice string (lnbc...)
367
+ */
368
+ async sendLightning(invoice) {
369
+ if (!this.isValidLightningInvoice(invoice)) {
370
+ throw new Error("Invalid Lightning invoice format. Expected lnbc... or lntb...");
371
+ }
372
+ const invoiceDetails = this.decodeLightningInvoice(invoice);
373
+ return {
374
+ hash: "",
375
+ // Will be payment hash from Spark
376
+ network: "spark",
377
+ status: "pending",
378
+ metadata: {
379
+ invoice,
380
+ amount: invoiceDetails.amount,
381
+ destination: invoiceDetails.destination
382
+ }
383
+ };
384
+ }
385
+ /**
386
+ * Create Lightning invoice via Spark
387
+ * @param amount - Amount in millisatoshis
388
+ * @param memo - Optional payment memo
389
+ * @returns Lightning invoice string (lnbc...)
390
+ */
391
+ async createLightningInvoice(amount, memo) {
392
+ if (amount <= 0) {
393
+ throw new Error("Invoice amount must be greater than 0");
394
+ }
395
+ const isTestnet = this.config.network === "testnet";
396
+ const prefix = isTestnet ? "lntb" : "lnbc";
397
+ return `${prefix}${amount}m1...`;
398
+ }
399
+ /**
400
+ * Validate Lightning invoice format
401
+ */
402
+ isValidLightningInvoice(invoice) {
403
+ const lowerInvoice = invoice.toLowerCase();
404
+ return lowerInvoice.startsWith("lnbc") || // Mainnet
405
+ lowerInvoice.startsWith("lntb") || // Testnet
406
+ lowerInvoice.startsWith("lnbcrt");
407
+ }
408
+ /**
409
+ * Decode Lightning invoice (basic parsing)
410
+ */
411
+ decodeLightningInvoice(invoice) {
412
+ return {
413
+ amount: BigInt(0),
414
+ destination: "",
415
+ expiry: 3600
416
+ };
417
+ }
418
+ /**
419
+ * Get Lightning (Spark) balance
420
+ */
421
+ async getLightningBalance() {
422
+ return {
423
+ available: BigInt(0),
424
+ pending: BigInt(0)
425
+ };
426
+ }
427
+ /**
428
+ * Get configuration
429
+ */
430
+ getConfig() {
431
+ return { ...this.config };
432
+ }
433
+ /**
434
+ * Check if wallet is initialized
435
+ */
436
+ isInitialized() {
437
+ return this.initialized;
438
+ }
439
+ /**
440
+ * Get contract addresses for current network
441
+ */
442
+ getContractAddresses() {
443
+ return getContractAddresses(this.config.network);
444
+ }
445
+ };
446
+
447
+ // src/security/KeyManager.ts
448
+ var KeyManager = class {
449
+ static ALGORITHM = "AES-GCM";
450
+ static KEY_LENGTH = 256;
451
+ static IV_LENGTH = 12;
452
+ static SALT_LENGTH = 16;
453
+ static PBKDF2_ITERATIONS = 1e5;
454
+ /**
455
+ * Encrypt a seed phrase with a password
456
+ */
457
+ static async encryptSeed(seed, password) {
458
+ const encoder = new TextEncoder();
459
+ const seedData = encoder.encode(seed);
460
+ const salt = crypto.getRandomValues(new Uint8Array(this.SALT_LENGTH));
461
+ const iv = crypto.getRandomValues(new Uint8Array(this.IV_LENGTH));
462
+ const key = await this.deriveKey(password, salt);
463
+ const encrypted = await crypto.subtle.encrypt(
464
+ { name: this.ALGORITHM, iv },
465
+ key,
466
+ seedData
467
+ );
468
+ const combined = new Uint8Array(salt.length + iv.length + encrypted.byteLength);
469
+ combined.set(salt, 0);
470
+ combined.set(iv, salt.length);
471
+ combined.set(new Uint8Array(encrypted), salt.length + iv.length);
472
+ return btoa(String.fromCharCode(...combined));
473
+ }
474
+ /**
475
+ * Decrypt a seed phrase with a password
476
+ */
477
+ static async decryptSeed(encryptedData, password) {
478
+ const combined = new Uint8Array(
479
+ atob(encryptedData).split("").map((c) => c.charCodeAt(0))
480
+ );
481
+ const salt = combined.slice(0, this.SALT_LENGTH);
482
+ const iv = combined.slice(this.SALT_LENGTH, this.SALT_LENGTH + this.IV_LENGTH);
483
+ const encrypted = combined.slice(this.SALT_LENGTH + this.IV_LENGTH);
484
+ const key = await this.deriveKey(password, salt);
485
+ const decrypted = await crypto.subtle.decrypt(
486
+ { name: this.ALGORITHM, iv },
487
+ key,
488
+ encrypted
489
+ );
490
+ const decoder = new TextDecoder();
491
+ return decoder.decode(decrypted);
492
+ }
493
+ /**
494
+ * Derive encryption key from password using PBKDF2
495
+ */
496
+ static async deriveKey(password, salt) {
497
+ const encoder = new TextEncoder();
498
+ const passwordData = encoder.encode(password);
499
+ const keyMaterial = await crypto.subtle.importKey(
500
+ "raw",
501
+ passwordData,
502
+ "PBKDF2",
503
+ false,
504
+ ["deriveKey"]
505
+ );
506
+ return crypto.subtle.deriveKey(
507
+ {
508
+ name: "PBKDF2",
509
+ salt: salt.buffer.slice(salt.byteOffset, salt.byteOffset + salt.byteLength),
510
+ iterations: this.PBKDF2_ITERATIONS,
511
+ hash: "SHA-256"
512
+ },
513
+ keyMaterial,
514
+ { name: this.ALGORITHM, length: this.KEY_LENGTH },
515
+ false,
516
+ ["encrypt", "decrypt"]
517
+ );
518
+ }
519
+ /**
520
+ * Validate a BIP-39 seed phrase (basic validation)
521
+ */
522
+ static validateSeedPhrase(seed) {
523
+ const words = seed.trim().split(/\s+/);
524
+ const validWordCounts = [12, 15, 18, 21, 24];
525
+ return validWordCounts.includes(words.length);
526
+ }
527
+ /**
528
+ * Generate a random encryption key (for backup purposes)
529
+ */
530
+ static generateBackupKey() {
531
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
532
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
533
+ }
534
+ };
535
+
536
+ // src/storage/SecureStorage.ts
537
+ var KeychainStorageAdapter = class {
538
+ serviceName;
539
+ constructor(serviceName = "com.zubari.wallet") {
540
+ this.serviceName = serviceName;
541
+ }
542
+ async setItem(key, value) {
543
+ if (typeof global !== "undefined" && global.KeychainModule) {
544
+ await global.KeychainModule.setItem(this.serviceName, key, value);
545
+ } else {
546
+ throw new Error("Keychain not available on this platform");
547
+ }
548
+ }
549
+ async getItem(key) {
550
+ if (typeof global !== "undefined" && global.KeychainModule) {
551
+ return global.KeychainModule.getItem(this.serviceName, key);
552
+ }
553
+ throw new Error("Keychain not available on this platform");
554
+ }
555
+ async removeItem(key) {
556
+ if (typeof global !== "undefined" && global.KeychainModule) {
557
+ await global.KeychainModule.removeItem(this.serviceName, key);
558
+ } else {
559
+ throw new Error("Keychain not available on this platform");
560
+ }
561
+ }
562
+ async hasItem(key) {
563
+ const value = await this.getItem(key);
564
+ return value !== null;
565
+ }
566
+ async clear() {
567
+ if (typeof global !== "undefined" && global.KeychainModule) {
568
+ await global.KeychainModule.clear(this.serviceName);
569
+ } else {
570
+ throw new Error("Keychain not available on this platform");
571
+ }
572
+ }
573
+ };
574
+ var KeystoreStorageAdapter = class {
575
+ alias;
576
+ constructor(alias = "zubari_wallet_keys") {
577
+ this.alias = alias;
578
+ }
579
+ async setItem(key, value) {
580
+ if (typeof global !== "undefined" && global.KeystoreModule) {
581
+ await global.KeystoreModule.setItem(this.alias, key, value);
582
+ } else {
583
+ throw new Error("Keystore not available on this platform");
584
+ }
585
+ }
586
+ async getItem(key) {
587
+ if (typeof global !== "undefined" && global.KeystoreModule) {
588
+ return global.KeystoreModule.getItem(this.alias, key);
589
+ }
590
+ throw new Error("Keystore not available on this platform");
591
+ }
592
+ async removeItem(key) {
593
+ if (typeof global !== "undefined" && global.KeystoreModule) {
594
+ await global.KeystoreModule.removeItem(this.alias, key);
595
+ } else {
596
+ throw new Error("Keystore not available on this platform");
597
+ }
598
+ }
599
+ async hasItem(key) {
600
+ const value = await this.getItem(key);
601
+ return value !== null;
602
+ }
603
+ async clear() {
604
+ if (typeof global !== "undefined" && global.KeystoreModule) {
605
+ await global.KeystoreModule.clear(this.alias);
606
+ } else {
607
+ throw new Error("Keystore not available on this platform");
608
+ }
609
+ }
610
+ };
611
+ var WebEncryptedStorageAdapter = class {
612
+ encryptionKey = null;
613
+ storagePrefix;
614
+ constructor(storagePrefix = "zubari_") {
615
+ this.storagePrefix = storagePrefix;
616
+ }
617
+ /**
618
+ * Initialize with a password-derived key
619
+ */
620
+ async initialize(password) {
621
+ const encoder = new TextEncoder();
622
+ const salt = this.getSalt();
623
+ const keyMaterial = await crypto.subtle.importKey(
624
+ "raw",
625
+ encoder.encode(password),
626
+ "PBKDF2",
627
+ false,
628
+ ["deriveKey"]
629
+ );
630
+ this.encryptionKey = await crypto.subtle.deriveKey(
631
+ {
632
+ name: "PBKDF2",
633
+ salt: salt.buffer,
634
+ iterations: 1e5,
635
+ hash: "SHA-256"
636
+ },
637
+ keyMaterial,
638
+ { name: "AES-GCM", length: 256 },
639
+ false,
640
+ ["encrypt", "decrypt"]
641
+ );
642
+ }
643
+ getSalt() {
644
+ const saltKey = `${this.storagePrefix}salt`;
645
+ let saltHex = localStorage.getItem(saltKey);
646
+ if (!saltHex) {
647
+ const salt = crypto.getRandomValues(new Uint8Array(16));
648
+ saltHex = Array.from(salt).map((b) => b.toString(16).padStart(2, "0")).join("");
649
+ localStorage.setItem(saltKey, saltHex);
650
+ }
651
+ return new Uint8Array(
652
+ saltHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))
653
+ );
654
+ }
655
+ async setItem(key, value) {
656
+ if (!this.encryptionKey) {
657
+ throw new Error("Storage not initialized. Call initialize() first.");
658
+ }
659
+ const encoder = new TextEncoder();
660
+ const iv = crypto.getRandomValues(new Uint8Array(12));
661
+ const encrypted = await crypto.subtle.encrypt(
662
+ { name: "AES-GCM", iv },
663
+ this.encryptionKey,
664
+ encoder.encode(value)
665
+ );
666
+ const combined = new Uint8Array(iv.length + encrypted.byteLength);
667
+ combined.set(iv);
668
+ combined.set(new Uint8Array(encrypted), iv.length);
669
+ const base64 = btoa(String.fromCharCode(...combined));
670
+ localStorage.setItem(`${this.storagePrefix}${key}`, base64);
671
+ }
672
+ async getItem(key) {
673
+ if (!this.encryptionKey) {
674
+ throw new Error("Storage not initialized. Call initialize() first.");
675
+ }
676
+ const base64 = localStorage.getItem(`${this.storagePrefix}${key}`);
677
+ if (!base64) return null;
678
+ try {
679
+ const combined = new Uint8Array(
680
+ atob(base64).split("").map((c) => c.charCodeAt(0))
681
+ );
682
+ const iv = combined.slice(0, 12);
683
+ const encrypted = combined.slice(12);
684
+ const decrypted = await crypto.subtle.decrypt(
685
+ { name: "AES-GCM", iv },
686
+ this.encryptionKey,
687
+ encrypted
688
+ );
689
+ const decoder = new TextDecoder();
690
+ return decoder.decode(decrypted);
691
+ } catch {
692
+ return null;
693
+ }
694
+ }
695
+ async removeItem(key) {
696
+ localStorage.removeItem(`${this.storagePrefix}${key}`);
697
+ }
698
+ async hasItem(key) {
699
+ return localStorage.getItem(`${this.storagePrefix}${key}`) !== null;
700
+ }
701
+ async clear() {
702
+ const keysToRemove = [];
703
+ for (let i = 0; i < localStorage.length; i++) {
704
+ const key = localStorage.key(i);
705
+ if (key?.startsWith(this.storagePrefix)) {
706
+ keysToRemove.push(key);
707
+ }
708
+ }
709
+ keysToRemove.forEach((key) => localStorage.removeItem(key));
710
+ }
711
+ };
712
+ var MemoryStorageAdapter = class {
713
+ storage = /* @__PURE__ */ new Map();
714
+ async setItem(key, value) {
715
+ this.storage.set(key, value);
716
+ }
717
+ async getItem(key) {
718
+ return this.storage.get(key) || null;
719
+ }
720
+ async removeItem(key) {
721
+ this.storage.delete(key);
722
+ }
723
+ async hasItem(key) {
724
+ return this.storage.has(key);
725
+ }
726
+ async clear() {
727
+ this.storage.clear();
728
+ }
729
+ };
730
+ function createSecureStorage() {
731
+ if (typeof global !== "undefined" && global.nativeModuleProxy !== void 0) {
732
+ const Platform = global.Platform;
733
+ if (Platform?.OS === "ios") {
734
+ return new KeychainStorageAdapter();
735
+ } else if (Platform?.OS === "android") {
736
+ return new KeystoreStorageAdapter();
737
+ }
738
+ }
739
+ if (typeof window !== "undefined" && typeof localStorage !== "undefined") {
740
+ return new WebEncryptedStorageAdapter();
741
+ }
742
+ return new MemoryStorageAdapter();
743
+ }
744
+
745
+ // src/services/WdkApiClient.ts
746
+ var WdkApiClient = class {
747
+ config;
748
+ constructor(config) {
749
+ this.config = {
750
+ baseUrl: config.baseUrl,
751
+ timeout: config.timeout || 3e4
752
+ };
753
+ }
754
+ /**
755
+ * Generate a new BIP-39 seed phrase using Tether WDK
756
+ */
757
+ async generateSeed() {
758
+ try {
759
+ const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/generate-seed`, {
760
+ method: "POST",
761
+ headers: {
762
+ "Content-Type": "application/json"
763
+ }
764
+ });
765
+ return await response.json();
766
+ } catch (error) {
767
+ return {
768
+ success: false,
769
+ error: error instanceof Error ? error.message : "Failed to generate seed"
770
+ };
771
+ }
772
+ }
773
+ /**
774
+ * Validate a BIP-39 seed phrase
775
+ */
776
+ async validateSeed(seed) {
777
+ try {
778
+ const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/validate-seed`, {
779
+ method: "POST",
780
+ headers: {
781
+ "Content-Type": "application/json"
782
+ },
783
+ body: JSON.stringify({ seed })
784
+ });
785
+ return await response.json();
786
+ } catch (error) {
787
+ return {
788
+ success: false,
789
+ error: error instanceof Error ? error.message : "Failed to validate seed"
790
+ };
791
+ }
792
+ }
793
+ /**
794
+ * Derive address for a specific chain using Tether WDK
795
+ */
796
+ async deriveAddress(seed, chain, network = "testnet") {
797
+ try {
798
+ const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/derive-address`, {
799
+ method: "POST",
800
+ headers: {
801
+ "Content-Type": "application/json"
802
+ },
803
+ body: JSON.stringify({ seed, chain, network })
804
+ });
805
+ return await response.json();
806
+ } catch (error) {
807
+ return {
808
+ success: false,
809
+ error: error instanceof Error ? error.message : "Failed to derive address"
810
+ };
811
+ }
812
+ }
813
+ /**
814
+ * Derive addresses for all chains using Tether WDK
815
+ */
816
+ async deriveAllAddresses(seed, network = "testnet") {
817
+ try {
818
+ const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/derive-all`, {
819
+ method: "POST",
820
+ headers: {
821
+ "Content-Type": "application/json"
822
+ },
823
+ body: JSON.stringify({ seed, network })
824
+ });
825
+ return await response.json();
826
+ } catch (error) {
827
+ return {
828
+ success: false,
829
+ error: error instanceof Error ? error.message : "Failed to derive addresses"
830
+ };
831
+ }
832
+ }
833
+ };
834
+ var DEFAULT_API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
835
+ var wdkApiClient = null;
836
+ function getWdkApiClient(baseUrl) {
837
+ if (!wdkApiClient || baseUrl && wdkApiClient["config"].baseUrl !== baseUrl) {
838
+ wdkApiClient = new WdkApiClient({
839
+ baseUrl: baseUrl || DEFAULT_API_URL
840
+ });
841
+ }
842
+ return wdkApiClient;
843
+ }
844
+
845
+ // src/services/WdkService.ts
846
+ var WdkManager;
847
+ var WalletManagerBtc;
848
+ var WalletManagerEvm;
849
+ var WalletManagerSolana;
850
+ var WalletManagerTon;
851
+ var WalletManagerTron;
852
+ var WalletManagerSpark;
853
+ var wdkLoaded = false;
854
+ var wdkLoadError = null;
855
+ var dynamicImport = new Function("specifier", "return import(specifier)");
856
+ async function loadWdkModules() {
857
+ if (wdkLoaded) return;
858
+ if (wdkLoadError) throw wdkLoadError;
859
+ try {
860
+ const [wdk, btc, evm, solana, ton, tron, spark] = await Promise.all([
861
+ dynamicImport("@tetherto/wdk"),
862
+ dynamicImport("@tetherto/wdk-wallet-btc"),
863
+ dynamicImport("@tetherto/wdk-wallet-evm"),
864
+ dynamicImport("@tetherto/wdk-wallet-solana"),
865
+ dynamicImport("@tetherto/wdk-wallet-ton"),
866
+ dynamicImport("@tetherto/wdk-wallet-tron"),
867
+ dynamicImport("@tetherto/wdk-wallet-spark")
868
+ ]);
869
+ WdkManager = wdk.default;
870
+ WalletManagerBtc = btc.default;
871
+ WalletManagerEvm = evm.default;
872
+ WalletManagerSolana = solana.default;
873
+ WalletManagerTon = ton.default;
874
+ WalletManagerTron = tron.default;
875
+ WalletManagerSpark = spark.default;
876
+ wdkLoaded = true;
877
+ } catch (error) {
878
+ wdkLoadError = error instanceof Error ? error : new Error("Failed to load WDK modules");
879
+ console.error("Failed to load WDK modules:", error);
880
+ throw wdkLoadError;
881
+ }
882
+ }
883
+ var DERIVATION_PATHS2 = {
884
+ bitcoin: "m/84'/0'/0'/0/0",
885
+ // BIP-84 for native SegWit
886
+ ethereum: "m/44'/60'/0'/0/0",
887
+ ton: "m/44'/607'/0'",
888
+ // Updated for v1.0.0-beta.6+
889
+ tron: "m/44'/195'/0'/0/0",
890
+ solana: "m/44'/501'/0'/0'",
891
+ // Updated for v1.0.0-beta.4+
892
+ spark: "m/44'/998'/0'/0/0"
893
+ };
894
+ var DEFAULT_RPC_URLS = {
895
+ mainnet: {
896
+ ethereum: "https://eth.llamarpc.com",
897
+ solana: "https://api.mainnet-beta.solana.com",
898
+ ton: "https://toncenter.com/api/v2/jsonRPC",
899
+ tron: "https://api.trongrid.io"
900
+ },
901
+ testnet: {
902
+ ethereum: "https://ethereum-sepolia-rpc.publicnode.com",
903
+ solana: "https://api.devnet.solana.com",
904
+ ton: "https://testnet.toncenter.com/api/v2/jsonRPC",
905
+ tron: "https://api.shasta.trongrid.io"
906
+ }
907
+ };
908
+ var WdkService = class {
909
+ seed = null;
910
+ config;
911
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
912
+ wallets = {};
913
+ constructor(config = {}) {
914
+ this.config = {
915
+ network: config.network || "testnet",
916
+ rpcUrls: config.rpcUrls
917
+ };
918
+ }
919
+ /**
920
+ * Check if WDK modules are loaded
921
+ */
922
+ static isLoaded() {
923
+ return wdkLoaded;
924
+ }
925
+ /**
926
+ * Ensure WDK modules are loaded
927
+ */
928
+ async ensureLoaded() {
929
+ await loadWdkModules();
930
+ }
931
+ /**
932
+ * Load WDK modules (call this before using sync methods)
933
+ */
934
+ async loadModules() {
935
+ await loadWdkModules();
936
+ }
937
+ /**
938
+ * Generate a random BIP-39 seed phrase (12 words)
939
+ */
940
+ async generateSeedPhrase() {
941
+ await this.ensureLoaded();
942
+ return WdkManager.getRandomSeedPhrase();
943
+ }
944
+ /**
945
+ * Validate a BIP-39 seed phrase
946
+ */
947
+ async isValidSeed(seed) {
948
+ await this.ensureLoaded();
949
+ return WdkManager.isValidSeed(seed);
950
+ }
951
+ /**
952
+ * Validate seed phrase (sync version - basic check)
953
+ */
954
+ isValidSeedSync(seed) {
955
+ const words = seed.trim().split(/\s+/);
956
+ return words.length === 12 || words.length === 24;
957
+ }
958
+ /**
959
+ * Initialize the service with a seed phrase
960
+ */
961
+ async initialize(seed) {
962
+ await this.ensureLoaded();
963
+ if (!WdkManager.isValidSeed(seed)) {
964
+ throw new Error("Invalid seed phrase");
965
+ }
966
+ this.seed = seed;
967
+ this.wallets = {};
968
+ }
969
+ /**
970
+ * Get RPC URL for a chain
971
+ */
972
+ getRpcUrl(chain) {
973
+ const networkUrls = DEFAULT_RPC_URLS[this.config.network];
974
+ if (this.config.rpcUrls?.[chain]) {
975
+ return this.config.rpcUrls[chain];
976
+ }
977
+ return networkUrls[chain] || "";
978
+ }
979
+ /**
980
+ * Get or create wallet instance for a specific chain
981
+ */
982
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
983
+ async getWallet(chain) {
984
+ if (!this.seed) {
985
+ throw new Error("WDK service not initialized. Call initialize() first.");
986
+ }
987
+ if (this.wallets[chain]) {
988
+ return this.wallets[chain];
989
+ }
990
+ const isTestnet = this.config.network === "testnet";
991
+ try {
992
+ switch (chain) {
993
+ case "ethereum": {
994
+ const rpcUrl = this.getRpcUrl("ethereum");
995
+ const wallet = new WalletManagerEvm(this.seed, { provider: rpcUrl });
996
+ this.wallets[chain] = wallet;
997
+ return wallet;
998
+ }
999
+ case "bitcoin": {
1000
+ const wallet = new WalletManagerBtc(this.seed, {
1001
+ network: isTestnet ? "testnet" : "bitcoin"
1002
+ });
1003
+ this.wallets[chain] = wallet;
1004
+ return wallet;
1005
+ }
1006
+ case "solana": {
1007
+ const rpcUrl = this.getRpcUrl("solana");
1008
+ const wallet = new WalletManagerSolana(this.seed, {
1009
+ rpcUrl
1010
+ });
1011
+ this.wallets[chain] = wallet;
1012
+ return wallet;
1013
+ }
1014
+ case "ton": {
1015
+ const url = this.getRpcUrl("ton");
1016
+ const wallet = new WalletManagerTon(this.seed, {
1017
+ tonClient: { url }
1018
+ });
1019
+ this.wallets[chain] = wallet;
1020
+ return wallet;
1021
+ }
1022
+ case "tron": {
1023
+ const fullHost = this.getRpcUrl("tron");
1024
+ const wallet = new WalletManagerTron(this.seed, {
1025
+ provider: fullHost
1026
+ });
1027
+ this.wallets[chain] = wallet;
1028
+ return wallet;
1029
+ }
1030
+ case "spark": {
1031
+ const wallet = new WalletManagerSpark(this.seed, {
1032
+ network: isTestnet ? "TESTNET" : "MAINNET"
1033
+ });
1034
+ this.wallets[chain] = wallet;
1035
+ return wallet;
1036
+ }
1037
+ default:
1038
+ throw new Error(`Unsupported chain: ${chain}`);
1039
+ }
1040
+ } catch (error) {
1041
+ console.error(`Failed to initialize ${chain} wallet:`, error);
1042
+ throw error;
1043
+ }
1044
+ }
1045
+ /**
1046
+ * Derive address for a specific chain
1047
+ */
1048
+ async deriveAddress(chain) {
1049
+ const path = DERIVATION_PATHS2[chain];
1050
+ try {
1051
+ const wallet = await this.getWallet(chain);
1052
+ const account = await wallet.getAccount(0);
1053
+ const address = await account.getAddress();
1054
+ return {
1055
+ chain,
1056
+ address,
1057
+ path
1058
+ };
1059
+ } catch (error) {
1060
+ console.error(`Error deriving ${chain} address:`, error);
1061
+ throw error;
1062
+ }
1063
+ }
1064
+ /**
1065
+ * Derive addresses for all supported chains
1066
+ */
1067
+ async deriveAllAddresses() {
1068
+ const chains = ["ethereum", "bitcoin", "ton", "tron", "solana", "spark"];
1069
+ const addresses = {
1070
+ ethereum: null,
1071
+ bitcoin: null,
1072
+ ton: null,
1073
+ tron: null,
1074
+ solana: null,
1075
+ spark: null
1076
+ };
1077
+ const results = await Promise.allSettled(
1078
+ chains.map(async (chain) => {
1079
+ const result = await this.deriveAddress(chain);
1080
+ return { chain, address: result.address };
1081
+ })
1082
+ );
1083
+ for (const result of results) {
1084
+ if (result.status === "fulfilled") {
1085
+ addresses[result.value.chain] = result.value.address;
1086
+ } else {
1087
+ console.error("Failed to derive address:", result.reason);
1088
+ }
1089
+ }
1090
+ return addresses;
1091
+ }
1092
+ /**
1093
+ * Derive addresses for specific chains only
1094
+ */
1095
+ async deriveAddressesForChains(chains) {
1096
+ const addresses = {};
1097
+ const results = await Promise.allSettled(
1098
+ chains.map(async (chain) => {
1099
+ const result = await this.deriveAddress(chain);
1100
+ return { chain, address: result.address };
1101
+ })
1102
+ );
1103
+ for (const result of results) {
1104
+ if (result.status === "fulfilled") {
1105
+ addresses[result.value.chain] = result.value.address;
1106
+ }
1107
+ }
1108
+ return addresses;
1109
+ }
1110
+ /**
1111
+ * Get fee rates for a specific chain
1112
+ */
1113
+ async getFeeRates(chain) {
1114
+ if (!this.seed) {
1115
+ throw new Error("WDK service not initialized. Call initialize() first.");
1116
+ }
1117
+ try {
1118
+ const wallet = await this.getWallet(chain);
1119
+ const feeRates = await wallet.getFeeRates();
1120
+ return {
1121
+ slow: (feeRates.slow || feeRates.low || "0").toString(),
1122
+ medium: (feeRates.medium || feeRates.normal || feeRates.standard || "0").toString(),
1123
+ fast: (feeRates.fast || feeRates.high || "0").toString()
1124
+ };
1125
+ } catch (error) {
1126
+ console.error(`Error fetching fee rates for ${chain}:`, error);
1127
+ throw error;
1128
+ }
1129
+ }
1130
+ /**
1131
+ * Get the current network configuration
1132
+ */
1133
+ getNetwork() {
1134
+ return this.config.network;
1135
+ }
1136
+ /**
1137
+ * Check if service is initialized
1138
+ */
1139
+ isInitialized() {
1140
+ return this.seed !== null;
1141
+ }
1142
+ /**
1143
+ * Clean up and dispose of wallet instances
1144
+ */
1145
+ dispose() {
1146
+ for (const wallet of Object.values(this.wallets)) {
1147
+ if (wallet && typeof wallet.dispose === "function") {
1148
+ try {
1149
+ wallet.dispose();
1150
+ } catch {
1151
+ }
1152
+ }
1153
+ }
1154
+ this.wallets = {};
1155
+ this.seed = null;
1156
+ }
1157
+ };
1158
+
1159
+ // src/wallet/WalletManager.ts
1160
+ var STORAGE_KEYS = {
1161
+ ENCRYPTED_SEED: "encrypted_seed",
1162
+ ACTIVE_WALLET: "active_wallet"
1163
+ };
1164
+ var SUPPORTED_CHAINS = ["ethereum", "bitcoin", "ton", "tron", "solana", "spark"];
1165
+ var WalletManager = class _WalletManager {
1166
+ config;
1167
+ storage;
1168
+ currentSeed = null;
1169
+ derivedAddress = null;
1170
+ derivedAddresses = {};
1171
+ selectedChain = "ethereum";
1172
+ wdkService;
1173
+ constructor(config = {}) {
1174
+ const isTestnet = config.network !== "mainnet";
1175
+ const ethereumConfig = getNetworkConfig("ethereum", isTestnet);
1176
+ this.config = {
1177
+ network: config.network || "testnet",
1178
+ rpcUrl: config.rpcUrl || ethereumConfig.rpcUrl,
1179
+ storage: config.storage || createSecureStorage(),
1180
+ enabledChains: config.enabledChains || SUPPORTED_CHAINS,
1181
+ apiUrl: config.apiUrl || process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001"
1182
+ };
1183
+ this.storage = this.config.storage;
1184
+ this.wdkService = new WdkService({
1185
+ network: this.config.network
1186
+ });
1187
+ }
1188
+ /**
1189
+ * Generate a new BIP-39 seed phrase (12 words) using ethers.js
1190
+ * For native WDK generation, use generateSeedWithWdk() instead
1191
+ */
1192
+ static generateSeed() {
1193
+ const wallet = Wallet.createRandom();
1194
+ const mnemonic = wallet.mnemonic;
1195
+ if (!mnemonic) {
1196
+ throw new Error("Failed to generate mnemonic");
1197
+ }
1198
+ return mnemonic.phrase;
1199
+ }
1200
+ /**
1201
+ * Generate a new BIP-39 seed phrase using native Tether WDK
1202
+ * This is the recommended method for generating seed phrases
1203
+ */
1204
+ async generateSeedWithWdk() {
1205
+ return await this.wdkService.generateSeedPhrase();
1206
+ }
1207
+ /**
1208
+ * Validate seed phrase using native WDK (async, more accurate)
1209
+ */
1210
+ async validateSeedWithWdk(seed) {
1211
+ return await this.wdkService.isValidSeed(seed);
1212
+ }
1213
+ /**
1214
+ * Validate a BIP-39 seed phrase
1215
+ */
1216
+ static validateSeed(seed) {
1217
+ return KeyManager.validateSeedPhrase(seed);
1218
+ }
1219
+ /**
1220
+ * Derive Ethereum address from seed phrase using BIP-44 path
1221
+ * Path: m/44'/60'/0'/0/0
1222
+ */
1223
+ static deriveAddress(seed) {
1224
+ const hdNode = HDNodeWallet.fromPhrase(seed, void 0, "m/44'/60'/0'/0/0");
1225
+ return hdNode.address;
1226
+ }
1227
+ /**
1228
+ * Get the HDNodeWallet for signing transactions
1229
+ */
1230
+ static getWallet(seed) {
1231
+ return HDNodeWallet.fromPhrase(seed, void 0, "m/44'/60'/0'/0/0");
1232
+ }
1233
+ /**
1234
+ * Initialize storage with password (required for web platform)
1235
+ */
1236
+ async initializeStorage(password) {
1237
+ if (this.storage instanceof WebEncryptedStorageAdapter) {
1238
+ await this.storage.initialize(password);
1239
+ }
1240
+ }
1241
+ /**
1242
+ * Create a new wallet with generated seed
1243
+ */
1244
+ async createWallet(password) {
1245
+ const seed = _WalletManager.generateSeed();
1246
+ const address = _WalletManager.deriveAddress(seed);
1247
+ const encrypted = await KeyManager.encryptSeed(seed, password);
1248
+ await this.storage.setItem(STORAGE_KEYS.ENCRYPTED_SEED, encrypted);
1249
+ this.currentSeed = seed;
1250
+ this.derivedAddress = address;
1251
+ return { seed, address };
1252
+ }
1253
+ /**
1254
+ * Import an existing wallet from seed phrase
1255
+ */
1256
+ async importWallet(seed, password) {
1257
+ if (!_WalletManager.validateSeed(seed)) {
1258
+ throw new Error("Invalid seed phrase");
1259
+ }
1260
+ const address = _WalletManager.deriveAddress(seed);
1261
+ const encrypted = await KeyManager.encryptSeed(seed, password);
1262
+ await this.storage.setItem(STORAGE_KEYS.ENCRYPTED_SEED, encrypted);
1263
+ this.currentSeed = seed;
1264
+ this.derivedAddress = address;
1265
+ return { address };
1266
+ }
1267
+ /**
1268
+ * Unlock wallet with password
1269
+ */
1270
+ async unlock(password) {
1271
+ const encrypted = await this.storage.getItem(STORAGE_KEYS.ENCRYPTED_SEED);
1272
+ if (!encrypted) {
1273
+ throw new Error("No wallet found");
1274
+ }
1275
+ try {
1276
+ const seed = await KeyManager.decryptSeed(encrypted, password);
1277
+ const address = _WalletManager.deriveAddress(seed);
1278
+ this.currentSeed = seed;
1279
+ this.derivedAddress = address;
1280
+ return { address };
1281
+ } catch {
1282
+ throw new Error("Invalid password");
1283
+ }
1284
+ }
1285
+ /**
1286
+ * Lock wallet (clear seed from memory)
1287
+ */
1288
+ lock() {
1289
+ this.currentSeed = null;
1290
+ this.wdkService.dispose();
1291
+ }
1292
+ /**
1293
+ * Check if wallet exists in storage
1294
+ */
1295
+ async hasWallet() {
1296
+ return this.storage.hasItem(STORAGE_KEYS.ENCRYPTED_SEED);
1297
+ }
1298
+ /**
1299
+ * Delete wallet from storage
1300
+ */
1301
+ async deleteWallet() {
1302
+ await this.storage.removeItem(STORAGE_KEYS.ENCRYPTED_SEED);
1303
+ this.currentSeed = null;
1304
+ this.derivedAddress = null;
1305
+ this.derivedAddresses = {};
1306
+ this.wdkService.dispose();
1307
+ }
1308
+ /**
1309
+ * Get current wallet state
1310
+ */
1311
+ getState() {
1312
+ return {
1313
+ isInitialized: this.derivedAddress !== null,
1314
+ isLocked: this.currentSeed === null && this.derivedAddress !== null,
1315
+ address: this.derivedAddress,
1316
+ balance: null
1317
+ // Use fetchBalance for current balance
1318
+ };
1319
+ }
1320
+ /**
1321
+ * Get current address (if unlocked)
1322
+ */
1323
+ getAddress() {
1324
+ return this.derivedAddress;
1325
+ }
1326
+ /**
1327
+ * Check if wallet is unlocked
1328
+ */
1329
+ isUnlocked() {
1330
+ return this.currentSeed !== null;
1331
+ }
1332
+ /**
1333
+ * Get the seed phrase (only if unlocked)
1334
+ */
1335
+ getSeed() {
1336
+ return this.currentSeed;
1337
+ }
1338
+ /**
1339
+ * Fetch balance for current address with timeout handling
1340
+ */
1341
+ async fetchBalance() {
1342
+ if (!this.derivedAddress) {
1343
+ throw new Error("Wallet not initialized");
1344
+ }
1345
+ const chain = this.config.network === "mainnet" ? mainnet : sepolia;
1346
+ const client = createPublicClient({
1347
+ chain,
1348
+ transport: http(this.config.rpcUrl, {
1349
+ timeout: 15e3,
1350
+ // 15 second timeout
1351
+ retryCount: 2,
1352
+ retryDelay: 1e3
1353
+ })
1354
+ });
1355
+ try {
1356
+ const balance = await client.getBalance({
1357
+ address: this.derivedAddress
1358
+ });
1359
+ return formatEther(balance);
1360
+ } catch (error) {
1361
+ console.warn("Failed to fetch balance:", error);
1362
+ return "0";
1363
+ }
1364
+ }
1365
+ /**
1366
+ * Create viem public client for the current network
1367
+ */
1368
+ getPublicClient() {
1369
+ const chain = this.config.network === "mainnet" ? mainnet : sepolia;
1370
+ return createPublicClient({
1371
+ chain,
1372
+ transport: http(this.config.rpcUrl, {
1373
+ timeout: 15e3,
1374
+ // 15 second timeout
1375
+ retryCount: 2,
1376
+ retryDelay: 1e3
1377
+ })
1378
+ });
1379
+ }
1380
+ /**
1381
+ * Get ethers wallet for signing (only if unlocked)
1382
+ */
1383
+ getEthersWallet() {
1384
+ if (!this.currentSeed) return null;
1385
+ return _WalletManager.getWallet(this.currentSeed);
1386
+ }
1387
+ /**
1388
+ * Set active wallet preference
1389
+ */
1390
+ async setActiveWalletPreference(wallet) {
1391
+ await this.storage.setItem(STORAGE_KEYS.ACTIVE_WALLET, wallet);
1392
+ }
1393
+ /**
1394
+ * Get active wallet preference
1395
+ */
1396
+ async getActiveWalletPreference() {
1397
+ const stored = await this.storage.getItem(STORAGE_KEYS.ACTIVE_WALLET);
1398
+ return stored === "metamask" || stored === "wdk" ? stored : "metamask";
1399
+ }
1400
+ // ==========================================
1401
+ // Multi-Chain Support Methods (Powered by Tether WDK)
1402
+ // ==========================================
1403
+ /**
1404
+ * Derive address for a specific chain (async version)
1405
+ *
1406
+ * Calls the backend WDK API for proper derivation when available.
1407
+ * Falls back to local ethers-based derivation if API is unavailable.
1408
+ */
1409
+ static async deriveAddressForChainAsync(seed, chain, network = "testnet", apiUrl) {
1410
+ try {
1411
+ const wdkApi = getWdkApiClient(apiUrl);
1412
+ const response = await wdkApi.deriveAddress(seed, chain, network);
1413
+ if (response.success && response.address) {
1414
+ return response.address;
1415
+ }
1416
+ console.warn(`WDK API failed for ${chain}, using local derivation:`, response.error);
1417
+ } catch (error) {
1418
+ console.warn(`WDK API unavailable for ${chain}, using local derivation:`, error);
1419
+ }
1420
+ return _WalletManager.deriveAddressForChain(seed, chain);
1421
+ }
1422
+ /**
1423
+ * Format address for non-WDK chains (fallback)
1424
+ *
1425
+ * Note: This fallback produces PLACEHOLDER addresses derived from the seed.
1426
+ * For real blockchain interaction, use the WDK API via deriveAddressForChainAsync().
1427
+ * These addresses should NOT be used for receiving funds without verification.
1428
+ */
1429
+ static formatAddressForChain(address, chain) {
1430
+ if (chain === "ethereum") {
1431
+ return address;
1432
+ }
1433
+ const addressBytes = address.toLowerCase().replace("0x", "");
1434
+ switch (chain) {
1435
+ case "bitcoin": {
1436
+ const btcChars = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
1437
+ let btcAddr = "tb1q";
1438
+ for (let i = 0; i < 38; i++) {
1439
+ const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) % btcChars.length;
1440
+ btcAddr += btcChars[idx];
1441
+ }
1442
+ return btcAddr;
1443
+ }
1444
+ case "ton": {
1445
+ const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1446
+ let tonAddr = "EQ";
1447
+ for (let i = 0; i < 46; i++) {
1448
+ const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) * 4 % base64Chars.length;
1449
+ tonAddr += base64Chars[idx];
1450
+ }
1451
+ return tonAddr;
1452
+ }
1453
+ case "tron": {
1454
+ const base58Chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
1455
+ let tronAddr = "T";
1456
+ for (let i = 0; i < 33; i++) {
1457
+ const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) * 3 % base58Chars.length;
1458
+ tronAddr += base58Chars[idx];
1459
+ }
1460
+ return tronAddr;
1461
+ }
1462
+ case "solana": {
1463
+ const base58Chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
1464
+ let solAddr = "";
1465
+ for (let i = 0; i < 44; i++) {
1466
+ const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) * 3 % base58Chars.length;
1467
+ solAddr += base58Chars[idx];
1468
+ }
1469
+ return solAddr;
1470
+ }
1471
+ case "spark": {
1472
+ const bech32Chars = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
1473
+ let sparkAddr = "sp1q";
1474
+ for (let i = 0; i < 58; i++) {
1475
+ const idx = parseInt(addressBytes.charAt(i % 40) || "0", 16) % bech32Chars.length;
1476
+ sparkAddr += bech32Chars[idx];
1477
+ }
1478
+ return sparkAddr;
1479
+ }
1480
+ default:
1481
+ return address;
1482
+ }
1483
+ }
1484
+ /**
1485
+ * Derive address for a specific chain (sync version for backwards compatibility)
1486
+ * Uses ethers for basic derivation, use deriveAddressForChainAsync for WDK
1487
+ *
1488
+ * Note: For non-Ethereum chains, this produces placeholder addresses that are
1489
+ * deterministic but not cryptographically valid. Use WDK API for real addresses.
1490
+ */
1491
+ static deriveAddressForChain(seed, chain) {
1492
+ const ethPath = DERIVATION_PATHS["ethereum"];
1493
+ const ethNode = HDNodeWallet.fromPhrase(seed, void 0, `${ethPath}/0`);
1494
+ if (chain === "ethereum") {
1495
+ return ethNode.address;
1496
+ }
1497
+ return _WalletManager.formatAddressForChain(ethNode.address, chain);
1498
+ }
1499
+ /**
1500
+ * Derive addresses for all enabled chains (sync version)
1501
+ */
1502
+ deriveAllAddresses() {
1503
+ if (!this.currentSeed) {
1504
+ throw new Error("Wallet is locked");
1505
+ }
1506
+ const addresses = {};
1507
+ for (const chain of this.config.enabledChains) {
1508
+ addresses[chain] = _WalletManager.deriveAddressForChain(this.currentSeed, chain);
1509
+ }
1510
+ this.derivedAddresses = addresses;
1511
+ return addresses;
1512
+ }
1513
+ /**
1514
+ * Derive addresses for all enabled chains using native Tether WDK (recommended)
1515
+ * This uses the WDK directly without needing a backend API.
1516
+ * Returns REAL cryptographically valid addresses for all chains.
1517
+ */
1518
+ async deriveAllAddressesWithWdk() {
1519
+ if (!this.currentSeed) {
1520
+ throw new Error("Wallet is locked");
1521
+ }
1522
+ try {
1523
+ await this.wdkService.initialize(this.currentSeed);
1524
+ const enabledChainsSet = new Set(this.config.enabledChains);
1525
+ const wdkAddresses = await this.wdkService.deriveAllAddresses();
1526
+ const addresses = {};
1527
+ for (const [chain, address] of Object.entries(wdkAddresses)) {
1528
+ if (enabledChainsSet.has(chain) && address) {
1529
+ addresses[chain] = address;
1530
+ }
1531
+ }
1532
+ this.derivedAddresses = addresses;
1533
+ return addresses;
1534
+ } catch (error) {
1535
+ console.error("Native WDK derivation failed:", error);
1536
+ throw error;
1537
+ }
1538
+ }
1539
+ /**
1540
+ * Derive addresses for all enabled chains using Tether WDK
1541
+ * Tries native WDK first, then falls back to API, then to placeholders
1542
+ */
1543
+ async deriveAllAddressesAsync() {
1544
+ if (!this.currentSeed) {
1545
+ throw new Error("Wallet is locked");
1546
+ }
1547
+ try {
1548
+ return await this.deriveAllAddressesWithWdk();
1549
+ } catch (wdkError) {
1550
+ console.warn("Native WDK failed, trying API:", wdkError);
1551
+ }
1552
+ try {
1553
+ const wdkApi = getWdkApiClient(this.config.apiUrl);
1554
+ const response = await wdkApi.deriveAllAddresses(this.currentSeed, this.config.network);
1555
+ if (response.success && response.addresses) {
1556
+ const addresses = {};
1557
+ for (const chain of this.config.enabledChains) {
1558
+ const address = response.addresses[chain];
1559
+ if (address) {
1560
+ addresses[chain] = address;
1561
+ }
1562
+ }
1563
+ this.derivedAddresses = addresses;
1564
+ return addresses;
1565
+ }
1566
+ console.warn("WDK API call failed:", response.error);
1567
+ } catch (apiError) {
1568
+ console.warn("WDK API unavailable:", apiError);
1569
+ }
1570
+ console.warn("WARNING: Using placeholder addresses. These are NOT valid for receiving funds!");
1571
+ return this.deriveAllAddresses();
1572
+ }
1573
+ /**
1574
+ * Get address for a specific chain
1575
+ */
1576
+ getAddressForChain(chain) {
1577
+ if (!this.currentSeed) {
1578
+ return this.derivedAddresses[chain] || null;
1579
+ }
1580
+ if (!this.derivedAddresses[chain]) {
1581
+ this.derivedAddresses[chain] = _WalletManager.deriveAddressForChain(this.currentSeed, chain);
1582
+ }
1583
+ return this.derivedAddresses[chain] || null;
1584
+ }
1585
+ /**
1586
+ * Get all derived addresses
1587
+ */
1588
+ getAllAddresses() {
1589
+ return { ...this.derivedAddresses };
1590
+ }
1591
+ /**
1592
+ * Set the selected chain
1593
+ */
1594
+ setSelectedChain(chain) {
1595
+ if (!this.config.enabledChains.includes(chain)) {
1596
+ throw new Error(`Chain ${chain} is not enabled`);
1597
+ }
1598
+ this.selectedChain = chain;
1599
+ }
1600
+ /**
1601
+ * Get the currently selected chain
1602
+ */
1603
+ getSelectedChain() {
1604
+ return this.selectedChain;
1605
+ }
1606
+ /**
1607
+ * Get enabled chains
1608
+ */
1609
+ getEnabledChains() {
1610
+ return [...this.config.enabledChains];
1611
+ }
1612
+ /**
1613
+ * Get chain configuration
1614
+ */
1615
+ getChainConfig(chain) {
1616
+ return getNetworkConfig(chain, this.config.network === "testnet");
1617
+ }
1618
+ /**
1619
+ * Fetch balance for a specific chain
1620
+ * Note: Currently only Ethereum is implemented
1621
+ */
1622
+ async fetchBalanceForChain(chain) {
1623
+ const address = this.getAddressForChain(chain);
1624
+ if (!address) {
1625
+ throw new Error(`No address for chain ${chain}`);
1626
+ }
1627
+ const networkConfig = this.getChainConfig(chain);
1628
+ let balance = "0";
1629
+ if (chain === "ethereum") {
1630
+ const viemChain = this.config.network === "mainnet" ? mainnet : sepolia;
1631
+ const client = createPublicClient({
1632
+ chain: viemChain,
1633
+ transport: http(this.config.rpcUrl, {
1634
+ timeout: 15e3,
1635
+ // 15 second timeout
1636
+ retryCount: 2,
1637
+ retryDelay: 1e3
1638
+ })
1639
+ });
1640
+ try {
1641
+ const rawBalance = await client.getBalance({
1642
+ address
1643
+ });
1644
+ balance = formatEther(rawBalance);
1645
+ } catch (error) {
1646
+ console.warn(`Failed to fetch ${chain} balance:`, error);
1647
+ }
1648
+ }
1649
+ return {
1650
+ chain,
1651
+ symbol: networkConfig.nativeCurrency.symbol,
1652
+ balance,
1653
+ balanceUsd: 0,
1654
+ // TODO: Implement price fetching
1655
+ address,
1656
+ decimals: networkConfig.nativeCurrency.decimals
1657
+ };
1658
+ }
1659
+ /**
1660
+ * Fetch balances for all enabled chains
1661
+ */
1662
+ async fetchAllBalances() {
1663
+ const balances = [];
1664
+ for (const chain of this.config.enabledChains) {
1665
+ try {
1666
+ const balance = await this.fetchBalanceForChain(chain);
1667
+ balances.push(balance);
1668
+ } catch (error) {
1669
+ console.error(`Failed to fetch balance for ${chain}:`, error);
1670
+ const networkConfig = this.getChainConfig(chain);
1671
+ balances.push({
1672
+ chain,
1673
+ symbol: networkConfig.nativeCurrency.symbol,
1674
+ balance: "0",
1675
+ balanceUsd: 0,
1676
+ address: this.getAddressForChain(chain) || "",
1677
+ decimals: networkConfig.nativeCurrency.decimals
1678
+ });
1679
+ }
1680
+ }
1681
+ return balances;
1682
+ }
1683
+ /**
1684
+ * Get extended wallet state with multi-chain info
1685
+ */
1686
+ getExtendedState() {
1687
+ return {
1688
+ isInitialized: this.derivedAddress !== null,
1689
+ isLocked: this.currentSeed === null && this.derivedAddress !== null,
1690
+ address: this.derivedAddress,
1691
+ balance: null,
1692
+ addresses: this.derivedAddresses,
1693
+ selectedChain: this.selectedChain
1694
+ };
1695
+ }
1696
+ };
1697
+
1698
+ // src/protocols/NFTProtocol.ts
1699
+ var ZubariNFTProtocol = class {
1700
+ contractAddress;
1701
+ _marketplaceAddress;
1702
+ chainId;
1703
+ constructor(contractAddress, marketplaceAddress, chainId) {
1704
+ this.contractAddress = contractAddress;
1705
+ this._marketplaceAddress = marketplaceAddress;
1706
+ this.chainId = chainId;
1707
+ }
1708
+ /**
1709
+ * Create a lazy mint voucher for off-chain NFT creation
1710
+ * The voucher can be redeemed on-chain when purchased
1711
+ */
1712
+ async createLazyMintVoucher(metadata, creatorAddress, signer) {
1713
+ if (metadata.royaltyBps > PLATFORM_CONFIG.maxRoyaltyBps) {
1714
+ throw new Error(`Royalty cannot exceed ${PLATFORM_CONFIG.maxRoyaltyBps / 100}%`);
1715
+ }
1716
+ const tokenId = this.generateTokenId();
1717
+ const deadline = Math.floor(Date.now() / 1e3) + PLATFORM_CONFIG.voucherValiditySecs;
1718
+ const voucherData = {
1719
+ tokenId,
1720
+ uri: metadata.image,
1721
+ // Will be IPFS URI
1722
+ creator: creatorAddress,
1723
+ royaltyBps: metadata.royaltyBps,
1724
+ deadline
1725
+ };
1726
+ const domain = {
1727
+ ...NFT_VOUCHER_DOMAIN,
1728
+ chainId: this.chainId,
1729
+ verifyingContract: this.contractAddress
1730
+ };
1731
+ const signature = await signer.signTypedData(domain, NFT_VOUCHER_TYPES, voucherData);
1732
+ return {
1733
+ ...voucherData,
1734
+ signature
1735
+ };
1736
+ }
1737
+ /**
1738
+ * Redeem a lazy mint voucher to mint the NFT on-chain
1739
+ */
1740
+ async redeemVoucher(voucher, _buyerAddress) {
1741
+ if (voucher.deadline < Math.floor(Date.now() / 1e3)) {
1742
+ throw new Error("Voucher has expired");
1743
+ }
1744
+ return {
1745
+ hash: "",
1746
+ network: "ethereum",
1747
+ status: "pending"
1748
+ };
1749
+ }
1750
+ /**
1751
+ * List an NFT for sale on the marketplace
1752
+ */
1753
+ async listForSale(_params) {
1754
+ return {
1755
+ hash: "",
1756
+ network: "ethereum",
1757
+ status: "pending"
1758
+ };
1759
+ }
1760
+ /**
1761
+ * Buy an NFT from the marketplace
1762
+ */
1763
+ async buyNFT(_listingId, _price) {
1764
+ return {
1765
+ hash: "",
1766
+ network: "ethereum",
1767
+ status: "pending"
1768
+ };
1769
+ }
1770
+ /**
1771
+ * Transfer an NFT to another address
1772
+ */
1773
+ async transfer(_tokenId, _to) {
1774
+ return {
1775
+ hash: "",
1776
+ network: "ethereum",
1777
+ status: "pending"
1778
+ };
1779
+ }
1780
+ /**
1781
+ * Get NFTs owned by an address
1782
+ */
1783
+ async getOwnedNFTs(_address) {
1784
+ return [];
1785
+ }
1786
+ /**
1787
+ * Generate a random tokenId (32 bytes hex)
1788
+ */
1789
+ generateTokenId() {
1790
+ const bytes = new Uint8Array(32);
1791
+ crypto.getRandomValues(bytes);
1792
+ return "0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
1793
+ }
1794
+ };
1795
+
1796
+ // src/protocols/TipsProtocol.ts
1797
+ var ZubariTipsProtocol = class {
1798
+ contractAddress;
1799
+ chainId;
1800
+ gaslessEnabled;
1801
+ constructor(contractAddress, chainId, gaslessEnabled = false) {
1802
+ this.contractAddress = contractAddress;
1803
+ this.chainId = chainId;
1804
+ this.gaslessEnabled = gaslessEnabled;
1805
+ }
1806
+ /**
1807
+ * Send a tip to a creator
1808
+ */
1809
+ async sendTip(tip) {
1810
+ const { recipient, amount, token, message } = tip;
1811
+ const platformFee = amount * BigInt(PLATFORM_CONFIG.tipFeeBps) / BigInt(1e4);
1812
+ const creatorAmount = amount - platformFee;
1813
+ if (amount <= 0n) {
1814
+ throw new Error("Tip amount must be greater than 0");
1815
+ }
1816
+ const txResult = {
1817
+ hash: ""};
1818
+ return {
1819
+ txHash: txResult.hash,
1820
+ tipId: "",
1821
+ // Will be returned from contract event
1822
+ recipient,
1823
+ amount: creatorAmount,
1824
+ platformFee,
1825
+ timestamp: Math.floor(Date.now() / 1e3)
1826
+ };
1827
+ }
1828
+ /**
1829
+ * Send tips to multiple creators in a single transaction
1830
+ */
1831
+ async sendBatchTips(tips) {
1832
+ if (tips.length === 0) {
1833
+ throw new Error("At least one tip is required");
1834
+ }
1835
+ tips.reduce((sum, tip) => sum + tip.amount, BigInt(0));
1836
+ return tips.map((tip) => ({
1837
+ txHash: "",
1838
+ tipId: "",
1839
+ recipient: tip.recipient,
1840
+ amount: tip.amount - tip.amount * BigInt(PLATFORM_CONFIG.tipFeeBps) / BigInt(1e4),
1841
+ platformFee: tip.amount * BigInt(PLATFORM_CONFIG.tipFeeBps) / BigInt(1e4),
1842
+ timestamp: Math.floor(Date.now() / 1e3)
1843
+ }));
1844
+ }
1845
+ /**
1846
+ * Get tips received by an address
1847
+ */
1848
+ async getTipsReceived(address) {
1849
+ return [];
1850
+ }
1851
+ /**
1852
+ * Get tips sent by an address
1853
+ */
1854
+ async getTipsSent(address) {
1855
+ return [];
1856
+ }
1857
+ /**
1858
+ * Get tip statistics for a creator
1859
+ */
1860
+ async getCreatorTipStats(creator) {
1861
+ return {
1862
+ totalReceived: BigInt(0),
1863
+ tipCount: 0,
1864
+ uniqueTippers: 0
1865
+ };
1866
+ }
1867
+ /**
1868
+ * Get platform fee in basis points
1869
+ */
1870
+ getPlatformFeeBps() {
1871
+ return PLATFORM_CONFIG.tipFeeBps;
1872
+ }
1873
+ };
1874
+
1875
+ // src/protocols/SubscriptionProtocol.ts
1876
+ var ZubariSubscriptionProtocol = class {
1877
+ contractAddress;
1878
+ chainId;
1879
+ constructor(contractAddress, chainId) {
1880
+ this.contractAddress = contractAddress;
1881
+ this.chainId = chainId;
1882
+ }
1883
+ /**
1884
+ * Create a new subscription plan
1885
+ */
1886
+ async createPlan(plan) {
1887
+ if (!plan.name || plan.name.length === 0) {
1888
+ throw new Error("Plan name is required");
1889
+ }
1890
+ if (plan.price <= 0n) {
1891
+ throw new Error("Plan price must be greater than 0");
1892
+ }
1893
+ if (plan.duration <= 0) {
1894
+ throw new Error("Plan duration must be greater than 0");
1895
+ }
1896
+ const planId = this.generatePlanId(plan.name);
1897
+ return planId;
1898
+ }
1899
+ /**
1900
+ * Update an existing subscription plan
1901
+ */
1902
+ async updatePlan(planId, updates) {
1903
+ return {
1904
+ hash: "",
1905
+ network: "ethereum",
1906
+ status: "pending"
1907
+ };
1908
+ }
1909
+ /**
1910
+ * Subscribe to a creator's plan
1911
+ */
1912
+ async subscribe(creator, planId, months = 1) {
1913
+ if (months <= 0) {
1914
+ throw new Error("Subscription duration must be at least 1 month");
1915
+ }
1916
+ const now = Math.floor(Date.now() / 1e3);
1917
+ const durationSeconds = months * 30 * 24 * 60 * 60;
1918
+ return {
1919
+ subscriptionId: "",
1920
+ planId,
1921
+ creator,
1922
+ subscriber: "",
1923
+ // Current user address
1924
+ startTime: now,
1925
+ endTime: now + durationSeconds,
1926
+ autoRenew: false,
1927
+ status: "active"
1928
+ };
1929
+ }
1930
+ /**
1931
+ * Cancel an active subscription
1932
+ */
1933
+ async cancel(subscriptionId) {
1934
+ return {
1935
+ hash: "",
1936
+ network: "ethereum",
1937
+ status: "pending"
1938
+ };
1939
+ }
1940
+ /**
1941
+ * Check if an address is subscribed to a creator
1942
+ */
1943
+ async isSubscribed(creator, subscriber) {
1944
+ return false;
1945
+ }
1946
+ /**
1947
+ * Get active subscriptions for a subscriber
1948
+ */
1949
+ async getActiveSubscriptions(subscriber) {
1950
+ return [];
1951
+ }
1952
+ /**
1953
+ * Get all subscribers for a creator
1954
+ */
1955
+ async getSubscribers(creator) {
1956
+ return [];
1957
+ }
1958
+ /**
1959
+ * Get a specific plan by ID
1960
+ */
1961
+ async getPlan(planId) {
1962
+ return null;
1963
+ }
1964
+ /**
1965
+ * Get all plans for a creator
1966
+ */
1967
+ async getCreatorPlans(creator) {
1968
+ return [];
1969
+ }
1970
+ /**
1971
+ * Generate a unique plan ID
1972
+ */
1973
+ generatePlanId(name) {
1974
+ const bytes = new Uint8Array(16);
1975
+ crypto.getRandomValues(bytes);
1976
+ return "0x" + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
1977
+ }
1978
+ };
1979
+
1980
+ // src/protocols/PayoutsProtocol.ts
1981
+ var ZubariPayoutsProtocol = class {
1982
+ contractAddress;
1983
+ chainId;
1984
+ constructor(contractAddress, chainId) {
1985
+ this.contractAddress = contractAddress;
1986
+ this.chainId = chainId;
1987
+ }
1988
+ /**
1989
+ * Get pending earnings breakdown for the current user
1990
+ */
1991
+ async getPendingEarnings() {
1992
+ return {
1993
+ tips: BigInt(0),
1994
+ subscriptions: BigInt(0),
1995
+ nftSales: BigInt(0),
1996
+ royalties: BigInt(0),
1997
+ total: BigInt(0)
1998
+ };
1999
+ }
2000
+ /**
2001
+ * Get historical earnings for a time period
2002
+ */
2003
+ async getEarningsHistory(period = "all") {
2004
+ return [];
2005
+ }
2006
+ /**
2007
+ * Claim all pending earnings
2008
+ */
2009
+ async claimEarnings() {
2010
+ return {
2011
+ hash: "",
2012
+ network: "ethereum",
2013
+ status: "pending"
2014
+ };
2015
+ }
2016
+ /**
2017
+ * Claim specific amount of earnings
2018
+ */
2019
+ async claimPartialEarnings(amount) {
2020
+ if (amount <= 0n) {
2021
+ throw new Error("Amount must be greater than 0");
2022
+ }
2023
+ return {
2024
+ hash: "",
2025
+ network: "ethereum",
2026
+ status: "pending"
2027
+ };
2028
+ }
2029
+ /**
2030
+ * Setup revenue split with collaborators
2031
+ * Basis points must sum to 10000 (100%)
2032
+ */
2033
+ async setupRevenueSplit(splits) {
2034
+ const totalBps = splits.reduce((sum, split) => sum + split.basisPoints, 0);
2035
+ if (totalBps !== 1e4) {
2036
+ throw new Error("Revenue splits must sum to 100% (10000 basis points)");
2037
+ }
2038
+ for (const split of splits) {
2039
+ if (split.basisPoints <= 0) {
2040
+ throw new Error("Each split must have positive basis points");
2041
+ }
2042
+ if (!split.recipient || split.recipient.length === 0) {
2043
+ throw new Error("Each split must have a valid recipient address");
2044
+ }
2045
+ }
2046
+ return {
2047
+ hash: "",
2048
+ network: "ethereum",
2049
+ status: "pending"
2050
+ };
2051
+ }
2052
+ /**
2053
+ * Get current revenue split configuration
2054
+ */
2055
+ async getRevenueSplit() {
2056
+ return [];
2057
+ }
2058
+ /**
2059
+ * Remove revenue split (creator gets 100%)
2060
+ */
2061
+ async removeRevenueSplit() {
2062
+ return {
2063
+ hash: "",
2064
+ network: "ethereum",
2065
+ status: "pending"
2066
+ };
2067
+ }
2068
+ /**
2069
+ * Convert earnings to stablecoin (USDT)
2070
+ */
2071
+ async convertToStable(token, amount) {
2072
+ if (amount <= 0n) {
2073
+ throw new Error("Amount must be greater than 0");
2074
+ }
2075
+ return {
2076
+ hash: "",
2077
+ network: "ethereum",
2078
+ status: "pending"
2079
+ };
2080
+ }
2081
+ };
2082
+
2083
+ // src/services/SwapService.ts
2084
+ var SwapService = class {
2085
+ _chainId;
2086
+ isTestnet;
2087
+ constructor(chainId, isTestnet = false) {
2088
+ this._chainId = chainId;
2089
+ this.isTestnet = isTestnet;
2090
+ }
2091
+ /**
2092
+ * Get a swap quote
2093
+ */
2094
+ async getQuote(tokenIn, tokenOut, amountIn) {
2095
+ if (amountIn <= 0n) {
2096
+ throw new Error("Amount must be greater than 0");
2097
+ }
2098
+ return {
2099
+ tokenIn,
2100
+ tokenOut,
2101
+ amountIn,
2102
+ amountOut: BigInt(0),
2103
+ priceImpact: 0,
2104
+ route: [tokenIn, tokenOut],
2105
+ estimatedGas: BigInt(0)
2106
+ };
2107
+ }
2108
+ /**
2109
+ * Execute a swap with slippage protection
2110
+ */
2111
+ async executeSwap(quote, slippageToleranceBps = PLATFORM_CONFIG.defaultSlippageBps) {
2112
+ quote.amountOut - quote.amountOut * BigInt(slippageToleranceBps) / BigInt(1e4);
2113
+ Math.floor(Date.now() / 1e3) + PLATFORM_CONFIG.swapDeadlineSecs;
2114
+ if (quote.priceImpact > 5) {
2115
+ console.warn(`High price impact: ${quote.priceImpact}%`);
2116
+ }
2117
+ return {
2118
+ hash: "",
2119
+ network: "ethereum",
2120
+ status: "pending"
2121
+ };
2122
+ }
2123
+ /**
2124
+ * Convert earnings to USDT, keeping some ETH for gas
2125
+ */
2126
+ async convertEarningsToStable(ethBalance, reserveForGas = BigInt("10000000000000000")) {
2127
+ const amountToSwap = ethBalance - reserveForGas;
2128
+ if (amountToSwap <= 0n) {
2129
+ throw new Error("Insufficient balance after gas reserve");
2130
+ }
2131
+ const contracts = getContractAddresses(this.isTestnet ? "testnet" : "mainnet");
2132
+ const quote = await this.getQuote(
2133
+ "0x0000000000000000000000000000000000000000",
2134
+ // ETH
2135
+ contracts.usdt,
2136
+ // USDT on Ethereum
2137
+ amountToSwap
2138
+ );
2139
+ return this.executeSwap(quote);
2140
+ }
2141
+ /**
2142
+ * Check if a swap route exists
2143
+ */
2144
+ async hasRoute(tokenIn, tokenOut) {
2145
+ try {
2146
+ const quote = await this.getQuote(tokenIn, tokenOut, BigInt(1));
2147
+ return quote.amountOut > 0n;
2148
+ } catch {
2149
+ return false;
2150
+ }
2151
+ }
2152
+ /**
2153
+ * Get supported tokens for swapping
2154
+ */
2155
+ async getSupportedTokens() {
2156
+ return [];
2157
+ }
2158
+ };
2159
+
2160
+ // src/types/index.ts
2161
+ var ZubariError = class extends Error {
2162
+ constructor(code, message, details) {
2163
+ super(message);
2164
+ this.code = code;
2165
+ this.details = details;
2166
+ this.name = "ZubariError";
2167
+ }
2168
+ };
2169
+ function useWalletManager(options = {}) {
2170
+ const { autoCheckWallet = true, ...config } = options;
2171
+ const manager = useMemo(() => new WalletManager(config), [
2172
+ config.network,
2173
+ config.rpcUrl
2174
+ ]);
2175
+ const [state, setState] = useState({
2176
+ isInitialized: false,
2177
+ isLocked: true,
2178
+ address: null,
2179
+ balance: null
2180
+ });
2181
+ const [isLoading, setIsLoading] = useState(false);
2182
+ const [error, setError] = useState(null);
2183
+ const [selectedChain, setSelectedChainState] = useState("ethereum");
2184
+ const [chainBalances, setChainBalances] = useState([]);
2185
+ const updateState = useCallback(() => {
2186
+ setState(manager.getExtendedState());
2187
+ }, [manager]);
2188
+ useEffect(() => {
2189
+ if (autoCheckWallet) {
2190
+ manager.hasWallet().then((exists) => {
2191
+ if (exists) {
2192
+ setState((prev) => ({
2193
+ ...prev,
2194
+ isInitialized: true,
2195
+ isLocked: true
2196
+ }));
2197
+ }
2198
+ });
2199
+ }
2200
+ }, [manager, autoCheckWallet]);
2201
+ const createWallet = useCallback(
2202
+ async (password) => {
2203
+ setIsLoading(true);
2204
+ setError(null);
2205
+ try {
2206
+ await manager.initializeStorage(password);
2207
+ const result = await manager.createWallet(password);
2208
+ try {
2209
+ await manager.deriveAllAddressesAsync();
2210
+ } catch {
2211
+ manager.deriveAllAddresses();
2212
+ }
2213
+ updateState();
2214
+ return result;
2215
+ } catch (err) {
2216
+ const message = err instanceof Error ? err.message : "Failed to create wallet";
2217
+ setError(message);
2218
+ throw err;
2219
+ } finally {
2220
+ setIsLoading(false);
2221
+ }
2222
+ },
2223
+ [manager, updateState]
2224
+ );
2225
+ const importWallet = useCallback(
2226
+ async (seed, password) => {
2227
+ setIsLoading(true);
2228
+ setError(null);
2229
+ try {
2230
+ await manager.initializeStorage(password);
2231
+ await manager.importWallet(seed, password);
2232
+ try {
2233
+ await manager.deriveAllAddressesAsync();
2234
+ } catch {
2235
+ manager.deriveAllAddresses();
2236
+ }
2237
+ updateState();
2238
+ } catch (err) {
2239
+ const message = err instanceof Error ? err.message : "Failed to import wallet";
2240
+ setError(message);
2241
+ throw err;
2242
+ } finally {
2243
+ setIsLoading(false);
2244
+ }
2245
+ },
2246
+ [manager, updateState]
2247
+ );
2248
+ const unlock = useCallback(
2249
+ async (password) => {
2250
+ setIsLoading(true);
2251
+ setError(null);
2252
+ try {
2253
+ await manager.initializeStorage(password);
2254
+ await manager.unlock(password);
2255
+ try {
2256
+ await manager.deriveAllAddressesAsync();
2257
+ } catch {
2258
+ manager.deriveAllAddresses();
2259
+ }
2260
+ updateState();
2261
+ } catch (err) {
2262
+ const message = err instanceof Error ? err.message : "Invalid password";
2263
+ setError(message);
2264
+ throw err;
2265
+ } finally {
2266
+ setIsLoading(false);
2267
+ }
2268
+ },
2269
+ [manager, updateState]
2270
+ );
2271
+ const lock = useCallback(() => {
2272
+ manager.lock();
2273
+ setChainBalances([]);
2274
+ updateState();
2275
+ }, [manager, updateState]);
2276
+ const deleteWallet = useCallback(async () => {
2277
+ setIsLoading(true);
2278
+ setError(null);
2279
+ try {
2280
+ await manager.deleteWallet();
2281
+ setChainBalances([]);
2282
+ setState({
2283
+ isInitialized: false,
2284
+ isLocked: true,
2285
+ address: null,
2286
+ balance: null
2287
+ });
2288
+ } catch (err) {
2289
+ const message = err instanceof Error ? err.message : "Failed to delete wallet";
2290
+ setError(message);
2291
+ throw err;
2292
+ } finally {
2293
+ setIsLoading(false);
2294
+ }
2295
+ }, [manager]);
2296
+ const fetchBalance = useCallback(async () => {
2297
+ setIsLoading(true);
2298
+ try {
2299
+ const balance = await manager.fetchBalance();
2300
+ setState((prev) => ({ ...prev, balance }));
2301
+ return balance;
2302
+ } catch (err) {
2303
+ console.warn("Failed to fetch balance:", err);
2304
+ setState((prev) => ({ ...prev, balance: "0" }));
2305
+ return "0";
2306
+ } finally {
2307
+ setIsLoading(false);
2308
+ }
2309
+ }, [manager]);
2310
+ const fetchAllBalances = useCallback(async () => {
2311
+ setIsLoading(true);
2312
+ try {
2313
+ const balances = await manager.fetchAllBalances();
2314
+ setChainBalances(balances);
2315
+ return balances;
2316
+ } catch (err) {
2317
+ console.warn("Failed to fetch all balances:", err);
2318
+ return [];
2319
+ } finally {
2320
+ setIsLoading(false);
2321
+ }
2322
+ }, [manager]);
2323
+ const setSelectedChain = useCallback((chain) => {
2324
+ manager.setSelectedChain(chain);
2325
+ setSelectedChainState(chain);
2326
+ }, [manager]);
2327
+ const getAddressForChain = useCallback(
2328
+ (chain) => manager.getAddressForChain(chain),
2329
+ [manager]
2330
+ );
2331
+ const getAllAddresses = useCallback(
2332
+ () => manager.getAllAddresses(),
2333
+ [manager]
2334
+ );
2335
+ const hasWallet = useCallback(() => manager.hasWallet(), [manager]);
2336
+ const getSeed = useCallback(() => manager.getSeed(), [manager]);
2337
+ return {
2338
+ state,
2339
+ isLoading,
2340
+ error,
2341
+ createWallet,
2342
+ importWallet,
2343
+ unlock,
2344
+ lock,
2345
+ deleteWallet,
2346
+ fetchBalance,
2347
+ // Multi-chain
2348
+ selectedChain,
2349
+ setSelectedChain,
2350
+ chainBalances,
2351
+ fetchAllBalances,
2352
+ getAddressForChain,
2353
+ getAllAddresses,
2354
+ supportedChains: SUPPORTED_CHAINS,
2355
+ // Utilities
2356
+ hasWallet,
2357
+ getSeed,
2358
+ manager
2359
+ };
2360
+ }
2361
+
2362
+ // src/utils/index.ts
2363
+ function formatAddress(address, chars = 4) {
2364
+ if (!address || address.length < 10) return address;
2365
+ return `${address.slice(0, chars + 2)}...${address.slice(-chars)}`;
2366
+ }
2367
+ function formatBalance(balance, decimals = 18, precision = 4) {
2368
+ const divisor = BigInt(10 ** decimals);
2369
+ const integerPart = balance / divisor;
2370
+ const fractionalPart = balance % divisor;
2371
+ const fractionalStr = fractionalPart.toString().padStart(decimals, "0").slice(0, precision);
2372
+ return `${integerPart}.${fractionalStr}`;
2373
+ }
2374
+ function isValidAddress(address) {
2375
+ return /^0x[a-fA-F0-9]{40}$/.test(address);
2376
+ }
2377
+ function normalizeAddress(address) {
2378
+ if (!isValidAddress(address)) {
2379
+ throw new Error("Invalid Ethereum address");
2380
+ }
2381
+ return address.toLowerCase();
2382
+ }
2383
+
2384
+ export { DERIVATION_PATHS, KeyManager, MemoryStorageAdapter, NETWORKS, PLATFORM_CONFIG, SwapService, TESTNET_NETWORKS, WalletManager, WebEncryptedStorageAdapter, ZUBARI_CONTRACTS, ZubariError, ZubariNFTProtocol, ZubariPayoutsProtocol, ZubariSubscriptionProtocol, ZubariTipsProtocol, ZubariWallet, createSecureStorage, formatAddress, formatBalance, getContractAddresses, getNetworkConfig, isValidAddress, normalizeAddress, useWalletManager };
2385
+ //# sourceMappingURL=index.mjs.map
2386
+ //# sourceMappingURL=index.mjs.map