@enclave-hq/wallet-sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2130 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var EventEmitter = require('eventemitter3');
6
+ var viem = require('viem');
7
+ var accounts = require('viem/accounts');
8
+
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
+
11
+ var EventEmitter__default = /*#__PURE__*/_interopDefault(EventEmitter);
12
+
13
+ // src/core/events.ts
14
+ var TypedEventEmitter = class {
15
+ constructor() {
16
+ this.emitter = new EventEmitter__default.default();
17
+ }
18
+ on(event, handler) {
19
+ this.emitter.on(event, handler);
20
+ return this;
21
+ }
22
+ once(event, handler) {
23
+ this.emitter.once(event, handler);
24
+ return this;
25
+ }
26
+ off(event, handler) {
27
+ this.emitter.off(event, handler);
28
+ return this;
29
+ }
30
+ emit(event, ...args) {
31
+ return this.emitter.emit(event, ...args);
32
+ }
33
+ removeAllListeners(event) {
34
+ if (event !== void 0) {
35
+ this.emitter.removeAllListeners(event);
36
+ } else {
37
+ this.emitter.removeAllListeners();
38
+ }
39
+ return this;
40
+ }
41
+ };
42
+
43
+ // src/core/types.ts
44
+ var ChainType = /* @__PURE__ */ ((ChainType4) => {
45
+ ChainType4["EVM"] = "evm";
46
+ ChainType4["TRON"] = "tron";
47
+ ChainType4["SOLANA"] = "solana";
48
+ ChainType4["COSMOS"] = "cosmos";
49
+ return ChainType4;
50
+ })(ChainType || {});
51
+ var WalletType = /* @__PURE__ */ ((WalletType3) => {
52
+ WalletType3["METAMASK"] = "metamask";
53
+ WalletType3["WALLETCONNECT"] = "walletconnect";
54
+ WalletType3["COINBASE_WALLET"] = "coinbase-wallet";
55
+ WalletType3["TRONLINK"] = "tronlink";
56
+ WalletType3["WALLETCONNECT_TRON"] = "walletconnect-tron";
57
+ WalletType3["PRIVATE_KEY"] = "private-key";
58
+ return WalletType3;
59
+ })(WalletType || {});
60
+ var WalletState = /* @__PURE__ */ ((WalletState2) => {
61
+ WalletState2["DISCONNECTED"] = "disconnected";
62
+ WalletState2["CONNECTING"] = "connecting";
63
+ WalletState2["CONNECTED"] = "connected";
64
+ WalletState2["ERROR"] = "error";
65
+ return WalletState2;
66
+ })(WalletState || {});
67
+
68
+ // src/core/errors.ts
69
+ var WalletSDKError = class _WalletSDKError extends Error {
70
+ constructor(message, code, details) {
71
+ super(message);
72
+ this.code = code;
73
+ this.details = details;
74
+ this.name = "WalletSDKError";
75
+ Object.setPrototypeOf(this, _WalletSDKError.prototype);
76
+ }
77
+ };
78
+ var WalletNotConnectedError = class extends WalletSDKError {
79
+ constructor(walletType) {
80
+ super(
81
+ walletType ? `Wallet ${walletType} is not connected` : "No wallet is connected",
82
+ "WALLET_NOT_CONNECTED",
83
+ { walletType }
84
+ );
85
+ this.name = "WalletNotConnectedError";
86
+ }
87
+ };
88
+ var WalletNotAvailableError = class extends WalletSDKError {
89
+ constructor(walletType, downloadUrl) {
90
+ super(
91
+ `Wallet ${walletType} is not available. Please install it first.`,
92
+ "WALLET_NOT_AVAILABLE",
93
+ { walletType, downloadUrl }
94
+ );
95
+ this.name = "WalletNotAvailableError";
96
+ }
97
+ };
98
+ var ConnectionRejectedError = class extends WalletSDKError {
99
+ constructor(walletType) {
100
+ super(
101
+ `Connection to ${walletType} was rejected by user`,
102
+ "CONNECTION_REJECTED",
103
+ { walletType }
104
+ );
105
+ this.name = "ConnectionRejectedError";
106
+ }
107
+ };
108
+ var ChainNotSupportedError = class extends WalletSDKError {
109
+ constructor(chainId, walletType) {
110
+ super(
111
+ `Chain ${chainId} is not supported by ${walletType}`,
112
+ "CHAIN_NOT_SUPPORTED",
113
+ { chainId, walletType }
114
+ );
115
+ this.name = "ChainNotSupportedError";
116
+ }
117
+ };
118
+ var SignatureRejectedError = class extends WalletSDKError {
119
+ constructor(message) {
120
+ super(
121
+ message || "Signature was rejected by user",
122
+ "SIGNATURE_REJECTED"
123
+ );
124
+ this.name = "SignatureRejectedError";
125
+ }
126
+ };
127
+ var TransactionFailedError = class extends WalletSDKError {
128
+ constructor(txHash, reason) {
129
+ super(
130
+ `Transaction ${txHash} failed${reason ? `: ${reason}` : ""}`,
131
+ "TRANSACTION_FAILED",
132
+ { txHash, reason }
133
+ );
134
+ this.name = "TransactionFailedError";
135
+ }
136
+ };
137
+ var MethodNotSupportedError = class extends WalletSDKError {
138
+ constructor(method, walletType) {
139
+ super(
140
+ `Method ${method} is not supported by ${walletType}`,
141
+ "METHOD_NOT_SUPPORTED",
142
+ { method, walletType }
143
+ );
144
+ this.name = "MethodNotSupportedError";
145
+ }
146
+ };
147
+ var ConfigurationError = class extends WalletSDKError {
148
+ constructor(message, details) {
149
+ super(message, "CONFIGURATION_ERROR", details);
150
+ this.name = "ConfigurationError";
151
+ }
152
+ };
153
+ var NetworkError = class extends WalletSDKError {
154
+ constructor(message, details) {
155
+ super(message, "NETWORK_ERROR", details);
156
+ this.name = "NetworkError";
157
+ }
158
+ };
159
+
160
+ // src/adapters/base/wallet-adapter.ts
161
+ var WalletAdapter = class extends EventEmitter__default.default {
162
+ constructor() {
163
+ super(...arguments);
164
+ // 状态
165
+ this.state = "disconnected" /* DISCONNECTED */;
166
+ this.currentAccount = null;
167
+ }
168
+ signTransaction(_transaction) {
169
+ throw new MethodNotSupportedError("signTransaction", this.type);
170
+ }
171
+ signTypedData(_typedData) {
172
+ throw new MethodNotSupportedError("signTypedData", this.type);
173
+ }
174
+ // 链切换(默认不支持)
175
+ switchChain(_chainId) {
176
+ throw new MethodNotSupportedError("switchChain", this.type);
177
+ }
178
+ addChain(_chainConfig) {
179
+ throw new MethodNotSupportedError("addChain", this.type);
180
+ }
181
+ // 合约调用(默认不支持)
182
+ async readContract(_params) {
183
+ throw new MethodNotSupportedError("readContract", this.type);
184
+ }
185
+ async writeContract(_params) {
186
+ throw new MethodNotSupportedError("writeContract", this.type);
187
+ }
188
+ async estimateGas(_params) {
189
+ throw new MethodNotSupportedError("estimateGas", this.type);
190
+ }
191
+ async waitForTransaction(_txHash, _confirmations) {
192
+ throw new MethodNotSupportedError("waitForTransaction", this.type);
193
+ }
194
+ getSigner() {
195
+ throw new MethodNotSupportedError("getSigner", this.type);
196
+ }
197
+ // 工具方法
198
+ ensureConnected() {
199
+ if (this.state !== "connected" /* CONNECTED */ || !this.currentAccount) {
200
+ throw new WalletNotConnectedError(this.type);
201
+ }
202
+ }
203
+ setState(state) {
204
+ this.state = state;
205
+ }
206
+ setAccount(account) {
207
+ this.currentAccount = account;
208
+ }
209
+ emitAccountChanged(account) {
210
+ this.emit("accountChanged", account);
211
+ }
212
+ emitChainChanged(chainId) {
213
+ this.emit("chainChanged", chainId);
214
+ }
215
+ emitDisconnected() {
216
+ this.emit("disconnected");
217
+ }
218
+ emitError(error) {
219
+ this.emit("error", error);
220
+ }
221
+ // EventEmitter 方法(从 EventEmitter3 继承)
222
+ // removeAllListeners 已经由 EventEmitter 提供
223
+ };
224
+
225
+ // src/adapters/base/browser-wallet-adapter.ts
226
+ var BrowserWalletAdapter = class extends WalletAdapter {
227
+ /**
228
+ * 检查钱包是否可用
229
+ */
230
+ async isAvailable() {
231
+ if (typeof window === "undefined") {
232
+ return false;
233
+ }
234
+ return this.getBrowserProvider() !== void 0;
235
+ }
236
+ /**
237
+ * 确保钱包已安装
238
+ */
239
+ async ensureAvailable() {
240
+ const isAvailable = await this.isAvailable();
241
+ if (!isAvailable) {
242
+ throw new WalletNotAvailableError(
243
+ this.type,
244
+ this.getDownloadUrl()
245
+ );
246
+ }
247
+ }
248
+ /**
249
+ * 断开连接时清理
250
+ */
251
+ async disconnect() {
252
+ this.removeEventListeners();
253
+ this.setState("disconnected" /* DISCONNECTED */);
254
+ this.setAccount(null);
255
+ this.emitDisconnected();
256
+ }
257
+ };
258
+
259
+ // src/utils/address/universal-address.ts
260
+ function createUniversalAddress(chainId, address) {
261
+ return `${chainId}:${address}`;
262
+ }
263
+ function parseUniversalAddress(universalAddress) {
264
+ const parts = universalAddress.split(":");
265
+ if (parts.length !== 2) {
266
+ return null;
267
+ }
268
+ const chainId = parseInt(parts[0], 10);
269
+ if (isNaN(chainId)) {
270
+ return null;
271
+ }
272
+ return {
273
+ chainId,
274
+ address: parts[1]
275
+ };
276
+ }
277
+ function isValidUniversalAddress(universalAddress) {
278
+ return parseUniversalAddress(universalAddress) !== null;
279
+ }
280
+ function getChainIdFromUniversalAddress(universalAddress) {
281
+ const parsed = parseUniversalAddress(universalAddress);
282
+ return parsed ? parsed.chainId : null;
283
+ }
284
+ function getAddressFromUniversalAddress(universalAddress) {
285
+ const parsed = parseUniversalAddress(universalAddress);
286
+ return parsed ? parsed.address : null;
287
+ }
288
+ function compareUniversalAddresses(a, b) {
289
+ return a.toLowerCase() === b.toLowerCase();
290
+ }
291
+ function isValidEVMAddress(address) {
292
+ return viem.isAddress(address);
293
+ }
294
+ function formatEVMAddress(address) {
295
+ if (!viem.isAddress(address)) {
296
+ throw new Error(`Invalid EVM address: ${address}`);
297
+ }
298
+ return viem.getAddress(address);
299
+ }
300
+ function compareEVMAddresses(a, b) {
301
+ try {
302
+ return viem.getAddress(a) === viem.getAddress(b);
303
+ } catch {
304
+ return false;
305
+ }
306
+ }
307
+ function shortenAddress(address, chars = 4) {
308
+ if (!viem.isAddress(address)) {
309
+ return address;
310
+ }
311
+ const formatted = viem.getAddress(address);
312
+ return `${formatted.substring(0, chars + 2)}...${formatted.substring(42 - chars)}`;
313
+ }
314
+
315
+ // src/utils/chain-info.ts
316
+ var CHAIN_INFO = {
317
+ // EVM Mainnet
318
+ 1: {
319
+ id: 1,
320
+ name: "Ethereum Mainnet",
321
+ chainType: "evm" /* EVM */,
322
+ nativeCurrency: {
323
+ name: "Ether",
324
+ symbol: "ETH",
325
+ decimals: 18
326
+ },
327
+ rpcUrls: ["https://eth.llamarpc.com"],
328
+ blockExplorerUrls: ["https://etherscan.io"]
329
+ },
330
+ // EVM Testnets
331
+ 11155111: {
332
+ id: 11155111,
333
+ name: "Sepolia Testnet",
334
+ chainType: "evm" /* EVM */,
335
+ nativeCurrency: {
336
+ name: "Sepolia Ether",
337
+ symbol: "ETH",
338
+ decimals: 18
339
+ },
340
+ rpcUrls: ["https://rpc.sepolia.org"],
341
+ blockExplorerUrls: ["https://sepolia.etherscan.io"]
342
+ },
343
+ // Binance Smart Chain
344
+ 56: {
345
+ id: 56,
346
+ name: "BNB Smart Chain",
347
+ chainType: "evm" /* EVM */,
348
+ nativeCurrency: {
349
+ name: "BNB",
350
+ symbol: "BNB",
351
+ decimals: 18
352
+ },
353
+ rpcUrls: ["https://bsc-dataseed.binance.org"],
354
+ blockExplorerUrls: ["https://bscscan.com"]
355
+ },
356
+ 97: {
357
+ id: 97,
358
+ name: "BNB Smart Chain Testnet",
359
+ chainType: "evm" /* EVM */,
360
+ nativeCurrency: {
361
+ name: "BNB",
362
+ symbol: "BNB",
363
+ decimals: 18
364
+ },
365
+ rpcUrls: ["https://data-seed-prebsc-1-s1.binance.org:8545"],
366
+ blockExplorerUrls: ["https://testnet.bscscan.com"]
367
+ },
368
+ // Polygon
369
+ 137: {
370
+ id: 137,
371
+ name: "Polygon Mainnet",
372
+ chainType: "evm" /* EVM */,
373
+ nativeCurrency: {
374
+ name: "MATIC",
375
+ symbol: "MATIC",
376
+ decimals: 18
377
+ },
378
+ rpcUrls: ["https://polygon-rpc.com"],
379
+ blockExplorerUrls: ["https://polygonscan.com"]
380
+ },
381
+ 80002: {
382
+ id: 80002,
383
+ name: "Polygon Amoy Testnet",
384
+ chainType: "evm" /* EVM */,
385
+ nativeCurrency: {
386
+ name: "MATIC",
387
+ symbol: "MATIC",
388
+ decimals: 18
389
+ },
390
+ rpcUrls: ["https://rpc-amoy.polygon.technology"],
391
+ blockExplorerUrls: ["https://www.oklink.com/amoy"]
392
+ },
393
+ // Tron
394
+ 195: {
395
+ id: 195,
396
+ name: "Tron Mainnet",
397
+ chainType: "tron" /* TRON */,
398
+ nativeCurrency: {
399
+ name: "TRX",
400
+ symbol: "TRX",
401
+ decimals: 6
402
+ },
403
+ rpcUrls: ["https://api.trongrid.io"],
404
+ blockExplorerUrls: ["https://tronscan.org"]
405
+ },
406
+ // Arbitrum
407
+ 42161: {
408
+ id: 42161,
409
+ name: "Arbitrum One",
410
+ chainType: "evm" /* EVM */,
411
+ nativeCurrency: {
412
+ name: "Ether",
413
+ symbol: "ETH",
414
+ decimals: 18
415
+ },
416
+ rpcUrls: ["https://arb1.arbitrum.io/rpc"],
417
+ blockExplorerUrls: ["https://arbiscan.io"]
418
+ },
419
+ // Optimism
420
+ 10: {
421
+ id: 10,
422
+ name: "Optimism",
423
+ chainType: "evm" /* EVM */,
424
+ nativeCurrency: {
425
+ name: "Ether",
426
+ symbol: "ETH",
427
+ decimals: 18
428
+ },
429
+ rpcUrls: ["https://mainnet.optimism.io"],
430
+ blockExplorerUrls: ["https://optimistic.etherscan.io"]
431
+ },
432
+ // Avalanche
433
+ 43114: {
434
+ id: 43114,
435
+ name: "Avalanche C-Chain",
436
+ chainType: "evm" /* EVM */,
437
+ nativeCurrency: {
438
+ name: "AVAX",
439
+ symbol: "AVAX",
440
+ decimals: 18
441
+ },
442
+ rpcUrls: ["https://api.avax.network/ext/bc/C/rpc"],
443
+ blockExplorerUrls: ["https://snowtrace.io"]
444
+ }
445
+ };
446
+ function getChainInfo(chainId) {
447
+ return CHAIN_INFO[chainId];
448
+ }
449
+ function getChainType(chainId) {
450
+ return CHAIN_INFO[chainId]?.chainType;
451
+ }
452
+ function isEVMChain(chainId) {
453
+ return getChainType(chainId) === "evm" /* EVM */;
454
+ }
455
+ function isTronChain(chainId) {
456
+ return getChainType(chainId) === "tron" /* TRON */;
457
+ }
458
+
459
+ // src/adapters/evm/metamask.ts
460
+ var MetaMaskAdapter = class extends BrowserWalletAdapter {
461
+ constructor() {
462
+ super(...arguments);
463
+ this.type = "metamask" /* METAMASK */;
464
+ this.chainType = "evm" /* EVM */;
465
+ this.name = "MetaMask";
466
+ this.icon = "https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg";
467
+ this.walletClient = null;
468
+ this.publicClient = null;
469
+ /**
470
+ * 处理账户变化
471
+ */
472
+ this.handleAccountsChanged = (accounts) => {
473
+ if (accounts.length === 0) {
474
+ this.setState("disconnected" /* DISCONNECTED */);
475
+ this.setAccount(null);
476
+ this.emitAccountChanged(null);
477
+ } else {
478
+ const address = formatEVMAddress(accounts[0]);
479
+ const account = {
480
+ universalAddress: createUniversalAddress(this.currentAccount.chainId, address),
481
+ nativeAddress: address,
482
+ chainId: this.currentAccount.chainId,
483
+ chainType: "evm" /* EVM */,
484
+ isActive: true
485
+ };
486
+ this.setAccount(account);
487
+ this.emitAccountChanged(account);
488
+ }
489
+ };
490
+ /**
491
+ * 处理链变化
492
+ */
493
+ this.handleChainChanged = (chainIdHex) => {
494
+ const chainId = parseInt(chainIdHex, 16);
495
+ if (this.currentAccount) {
496
+ const account = {
497
+ ...this.currentAccount,
498
+ chainId,
499
+ universalAddress: createUniversalAddress(chainId, this.currentAccount.nativeAddress)
500
+ };
501
+ this.setAccount(account);
502
+ this.emitChainChanged(chainId);
503
+ }
504
+ };
505
+ /**
506
+ * 处理断开连接
507
+ */
508
+ this.handleDisconnect = () => {
509
+ this.setState("disconnected" /* DISCONNECTED */);
510
+ this.setAccount(null);
511
+ this.emitDisconnected();
512
+ };
513
+ }
514
+ /**
515
+ * 连接钱包
516
+ */
517
+ async connect(chainId) {
518
+ await this.ensureAvailable();
519
+ try {
520
+ this.setState("connecting" /* CONNECTING */);
521
+ const provider = this.getBrowserProvider();
522
+ const accounts = await provider.request({
523
+ method: "eth_requestAccounts"
524
+ });
525
+ if (!accounts || accounts.length === 0) {
526
+ throw new ConnectionRejectedError(this.type);
527
+ }
528
+ const currentChainId = await provider.request({
529
+ method: "eth_chainId"
530
+ });
531
+ const parsedChainId = parseInt(currentChainId, 16);
532
+ if (chainId && chainId !== parsedChainId) {
533
+ await this.switchChain(chainId);
534
+ }
535
+ this.walletClient = viem.createWalletClient({
536
+ account: accounts[0],
537
+ transport: viem.custom(provider)
538
+ });
539
+ const finalChainId = chainId || parsedChainId;
540
+ this.publicClient = viem.createPublicClient({
541
+ chain: this.getViemChain(finalChainId),
542
+ transport: viem.http()
543
+ });
544
+ const address = formatEVMAddress(accounts[0]);
545
+ const account = {
546
+ universalAddress: createUniversalAddress(finalChainId, address),
547
+ nativeAddress: address,
548
+ chainId: finalChainId,
549
+ chainType: "evm" /* EVM */,
550
+ isActive: true
551
+ };
552
+ this.setState("connected" /* CONNECTED */);
553
+ this.setAccount(account);
554
+ this.setupEventListeners();
555
+ return account;
556
+ } catch (error) {
557
+ this.setState("error" /* ERROR */);
558
+ this.setAccount(null);
559
+ if (error.code === 4001) {
560
+ throw new ConnectionRejectedError(this.type);
561
+ }
562
+ throw error;
563
+ }
564
+ }
565
+ /**
566
+ * 签名消息
567
+ */
568
+ async signMessage(message) {
569
+ this.ensureConnected();
570
+ try {
571
+ const provider = this.getBrowserProvider();
572
+ const signature = await provider.request({
573
+ method: "personal_sign",
574
+ params: [message, this.currentAccount.nativeAddress]
575
+ });
576
+ return signature;
577
+ } catch (error) {
578
+ if (error.code === 4001) {
579
+ throw new SignatureRejectedError();
580
+ }
581
+ throw error;
582
+ }
583
+ }
584
+ /**
585
+ * 签名 TypedData (EIP-712)
586
+ */
587
+ async signTypedData(typedData) {
588
+ this.ensureConnected();
589
+ try {
590
+ const provider = this.getBrowserProvider();
591
+ const signature = await provider.request({
592
+ method: "eth_signTypedData_v4",
593
+ params: [this.currentAccount.nativeAddress, JSON.stringify(typedData)]
594
+ });
595
+ return signature;
596
+ } catch (error) {
597
+ if (error.code === 4001) {
598
+ throw new SignatureRejectedError();
599
+ }
600
+ throw error;
601
+ }
602
+ }
603
+ /**
604
+ * 切换链
605
+ */
606
+ async switchChain(chainId) {
607
+ this.ensureConnected();
608
+ const provider = this.getBrowserProvider();
609
+ try {
610
+ await provider.request({
611
+ method: "wallet_switchEthereumChain",
612
+ params: [{ chainId: `0x${chainId.toString(16)}` }]
613
+ });
614
+ if (this.currentAccount) {
615
+ const updatedAccount = {
616
+ ...this.currentAccount,
617
+ chainId,
618
+ universalAddress: createUniversalAddress(chainId, this.currentAccount.nativeAddress)
619
+ };
620
+ this.setAccount(updatedAccount);
621
+ this.emitChainChanged(chainId);
622
+ }
623
+ } catch (error) {
624
+ if (error.code === 4902) {
625
+ const chainInfo = getChainInfo(chainId);
626
+ if (chainInfo) {
627
+ await this.addChain({
628
+ chainId: chainInfo.id,
629
+ chainName: chainInfo.name,
630
+ nativeCurrency: chainInfo.nativeCurrency,
631
+ rpcUrls: chainInfo.rpcUrls,
632
+ blockExplorerUrls: chainInfo.blockExplorerUrls
633
+ });
634
+ await this.switchChain(chainId);
635
+ } else {
636
+ throw new Error(`Chain ${chainId} not supported`);
637
+ }
638
+ } else {
639
+ throw error;
640
+ }
641
+ }
642
+ }
643
+ /**
644
+ * 添加链
645
+ */
646
+ async addChain(chainConfig) {
647
+ const provider = this.getBrowserProvider();
648
+ await provider.request({
649
+ method: "wallet_addEthereumChain",
650
+ params: [{
651
+ chainId: `0x${chainConfig.chainId.toString(16)}`,
652
+ chainName: chainConfig.chainName,
653
+ nativeCurrency: chainConfig.nativeCurrency,
654
+ rpcUrls: chainConfig.rpcUrls,
655
+ blockExplorerUrls: chainConfig.blockExplorerUrls
656
+ }]
657
+ });
658
+ }
659
+ /**
660
+ * 读取合约
661
+ */
662
+ async readContract(params) {
663
+ if (!this.publicClient) {
664
+ throw new Error("Public client not initialized");
665
+ }
666
+ const result = await this.publicClient.readContract({
667
+ address: params.address,
668
+ abi: params.abi,
669
+ functionName: params.functionName,
670
+ ...params.args ? { args: params.args } : {}
671
+ });
672
+ return result;
673
+ }
674
+ /**
675
+ * 写入合约
676
+ */
677
+ async writeContract(params) {
678
+ this.ensureConnected();
679
+ if (!this.walletClient) {
680
+ throw new Error("Wallet client not initialized");
681
+ }
682
+ try {
683
+ const txHash = await this.walletClient.writeContract({
684
+ address: params.address,
685
+ abi: params.abi,
686
+ functionName: params.functionName,
687
+ ...params.args ? { args: params.args } : {},
688
+ value: params.value ? BigInt(params.value) : void 0,
689
+ gas: params.gas ? BigInt(params.gas) : void 0,
690
+ gasPrice: params.gasPrice ? BigInt(params.gasPrice) : void 0
691
+ });
692
+ return txHash;
693
+ } catch (error) {
694
+ if (error.code === 4001) {
695
+ throw new SignatureRejectedError("Transaction was rejected by user");
696
+ }
697
+ throw error;
698
+ }
699
+ }
700
+ /**
701
+ * 估算 gas
702
+ */
703
+ async estimateGas(params) {
704
+ if (!this.publicClient) {
705
+ throw new Error("Public client not initialized");
706
+ }
707
+ const gas = await this.publicClient.estimateContractGas({
708
+ address: params.address,
709
+ abi: params.abi,
710
+ functionName: params.functionName,
711
+ ...params.args ? { args: params.args } : {},
712
+ value: params.value ? BigInt(params.value) : void 0,
713
+ account: this.currentAccount.nativeAddress
714
+ });
715
+ return gas;
716
+ }
717
+ /**
718
+ * 等待交易确认
719
+ */
720
+ async waitForTransaction(txHash, confirmations = 1) {
721
+ if (!this.publicClient) {
722
+ throw new Error("Public client not initialized");
723
+ }
724
+ const receipt = await this.publicClient.waitForTransactionReceipt({
725
+ hash: txHash,
726
+ confirmations
727
+ });
728
+ if (receipt.status === "reverted") {
729
+ throw new TransactionFailedError(txHash, "Transaction reverted");
730
+ }
731
+ return {
732
+ transactionHash: receipt.transactionHash,
733
+ blockNumber: Number(receipt.blockNumber),
734
+ blockHash: receipt.blockHash,
735
+ from: receipt.from,
736
+ to: receipt.to || void 0,
737
+ status: receipt.status === "success" ? "success" : "failed",
738
+ gasUsed: receipt.gasUsed.toString(),
739
+ effectiveGasPrice: receipt.effectiveGasPrice?.toString(),
740
+ logs: receipt.logs
741
+ };
742
+ }
743
+ /**
744
+ * 获取 Provider
745
+ */
746
+ getProvider() {
747
+ return this.getBrowserProvider();
748
+ }
749
+ /**
750
+ * 获取 Signer
751
+ */
752
+ getSigner() {
753
+ return this.walletClient;
754
+ }
755
+ /**
756
+ * 获取浏览器中的 MetaMask provider
757
+ */
758
+ getBrowserProvider() {
759
+ if (typeof window === "undefined") {
760
+ return void 0;
761
+ }
762
+ const w = window;
763
+ return w.ethereum && w.ethereum.isMetaMask ? w.ethereum : void 0;
764
+ }
765
+ /**
766
+ * 获取下载链接
767
+ */
768
+ getDownloadUrl() {
769
+ return "https://metamask.io/download/";
770
+ }
771
+ /**
772
+ * 设置事件监听
773
+ */
774
+ setupEventListeners() {
775
+ const provider = this.getBrowserProvider();
776
+ if (!provider) return;
777
+ provider.on("accountsChanged", this.handleAccountsChanged);
778
+ provider.on("chainChanged", this.handleChainChanged);
779
+ provider.on("disconnect", this.handleDisconnect);
780
+ }
781
+ /**
782
+ * 移除事件监听
783
+ */
784
+ removeEventListeners() {
785
+ const provider = this.getBrowserProvider();
786
+ if (!provider) return;
787
+ provider.removeListener("accountsChanged", this.handleAccountsChanged);
788
+ provider.removeListener("chainChanged", this.handleChainChanged);
789
+ provider.removeListener("disconnect", this.handleDisconnect);
790
+ }
791
+ /**
792
+ * 获取 viem chain 配置(简化版)
793
+ */
794
+ getViemChain(chainId) {
795
+ const chainInfo = getChainInfo(chainId);
796
+ if (chainInfo) {
797
+ return {
798
+ id: chainId,
799
+ name: chainInfo.name,
800
+ network: chainInfo.name.toLowerCase().replace(/\s+/g, "-"),
801
+ nativeCurrency: chainInfo.nativeCurrency,
802
+ rpcUrls: {
803
+ default: { http: chainInfo.rpcUrls },
804
+ public: { http: chainInfo.rpcUrls }
805
+ },
806
+ blockExplorers: chainInfo.blockExplorerUrls ? {
807
+ default: { name: "Explorer", url: chainInfo.blockExplorerUrls[0] }
808
+ } : void 0
809
+ };
810
+ }
811
+ return {
812
+ id: chainId,
813
+ name: `Chain ${chainId}`,
814
+ network: `chain-${chainId}`,
815
+ nativeCurrency: {
816
+ name: "ETH",
817
+ symbol: "ETH",
818
+ decimals: 18
819
+ },
820
+ rpcUrls: {
821
+ default: { http: [] },
822
+ public: { http: [] }
823
+ }
824
+ };
825
+ }
826
+ };
827
+
828
+ // src/adapters/tron/tronlink.ts
829
+ var _TronLinkAdapter = class _TronLinkAdapter extends BrowserWalletAdapter {
830
+ constructor() {
831
+ super(...arguments);
832
+ this.type = "tronlink" /* TRONLINK */;
833
+ this.chainType = "tron" /* TRON */;
834
+ this.name = "TronLink";
835
+ this.icon = "https://www.tronlink.org/static/logoIcon.svg";
836
+ /**
837
+ * 处理账户变化
838
+ */
839
+ this.handleAccountsChanged = (data) => {
840
+ if (!data || !data.address) {
841
+ this.setState("disconnected" /* DISCONNECTED */);
842
+ this.setAccount(null);
843
+ this.emitAccountChanged(null);
844
+ } else {
845
+ const address = data.address.base58 || data.address;
846
+ const account = {
847
+ universalAddress: createUniversalAddress(this.currentAccount.chainId, address),
848
+ nativeAddress: address,
849
+ chainId: this.currentAccount.chainId,
850
+ chainType: "tron" /* TRON */,
851
+ isActive: true
852
+ };
853
+ this.setAccount(account);
854
+ this.emitAccountChanged(account);
855
+ }
856
+ };
857
+ /**
858
+ * 处理断开连接
859
+ */
860
+ this.handleDisconnect = () => {
861
+ this.setState("disconnected" /* DISCONNECTED */);
862
+ this.setAccount(null);
863
+ this.emitDisconnected();
864
+ };
865
+ }
866
+ /**
867
+ * 连接钱包
868
+ */
869
+ async connect(chainId) {
870
+ await this.ensureAvailable();
871
+ try {
872
+ this.setState("connecting" /* CONNECTING */);
873
+ const tronWeb = this.getTronWeb();
874
+ const result = await tronWeb.request({
875
+ method: "tron_requestAccounts"
876
+ });
877
+ if (!result || !result.code || result.code !== 200) {
878
+ throw new ConnectionRejectedError(this.type);
879
+ }
880
+ const address = tronWeb.defaultAddress?.base58;
881
+ if (!address) {
882
+ throw new Error("Failed to get Tron address");
883
+ }
884
+ const tronChainId = chainId || _TronLinkAdapter.TRON_MAINNET_CHAIN_ID;
885
+ const account = {
886
+ universalAddress: createUniversalAddress(tronChainId, address),
887
+ nativeAddress: address,
888
+ chainId: tronChainId,
889
+ chainType: "tron" /* TRON */,
890
+ isActive: true
891
+ };
892
+ this.setState("connected" /* CONNECTED */);
893
+ this.setAccount(account);
894
+ this.setupEventListeners();
895
+ return account;
896
+ } catch (error) {
897
+ this.setState("error" /* ERROR */);
898
+ this.setAccount(null);
899
+ if (error.code === 4001 || error.message?.includes("User rejected")) {
900
+ throw new ConnectionRejectedError(this.type);
901
+ }
902
+ throw error;
903
+ }
904
+ }
905
+ /**
906
+ * 签名消息
907
+ */
908
+ async signMessage(message) {
909
+ this.ensureConnected();
910
+ try {
911
+ const tronWeb = this.getTronWeb();
912
+ const signature = await tronWeb.trx.sign(message);
913
+ return signature;
914
+ } catch (error) {
915
+ if (error.message?.includes("User rejected") || error.message?.includes("Confirmation declined")) {
916
+ throw new SignatureRejectedError();
917
+ }
918
+ throw error;
919
+ }
920
+ }
921
+ /**
922
+ * 获取 Provider
923
+ */
924
+ getProvider() {
925
+ return this.getTronWeb();
926
+ }
927
+ /**
928
+ * 获取浏览器中的 TronWeb
929
+ */
930
+ getBrowserProvider() {
931
+ if (typeof window === "undefined") {
932
+ return void 0;
933
+ }
934
+ const w = window;
935
+ return w.tronWeb || w.tronLink?.tronWeb;
936
+ }
937
+ /**
938
+ * 获取 TronWeb 实例
939
+ */
940
+ getTronWeb() {
941
+ const provider = this.getBrowserProvider();
942
+ if (!provider) {
943
+ throw new Error("TronWeb not found");
944
+ }
945
+ return provider;
946
+ }
947
+ /**
948
+ * 获取下载链接
949
+ */
950
+ getDownloadUrl() {
951
+ return "https://www.tronlink.org/";
952
+ }
953
+ /**
954
+ * 设置事件监听
955
+ */
956
+ setupEventListeners() {
957
+ if (typeof window === "undefined") return;
958
+ const w = window;
959
+ if (w.tronLink) {
960
+ w.tronLink.on("accountsChanged", this.handleAccountsChanged);
961
+ w.tronLink.on("disconnect", this.handleDisconnect);
962
+ }
963
+ }
964
+ /**
965
+ * 移除事件监听
966
+ */
967
+ removeEventListeners() {
968
+ if (typeof window === "undefined") return;
969
+ const w = window;
970
+ if (w.tronLink) {
971
+ w.tronLink.off("accountsChanged", this.handleAccountsChanged);
972
+ w.tronLink.off("disconnect", this.handleDisconnect);
973
+ }
974
+ }
975
+ };
976
+ // Tron 主网链 ID
977
+ _TronLinkAdapter.TRON_MAINNET_CHAIN_ID = 195;
978
+ var TronLinkAdapter = _TronLinkAdapter;
979
+ var EVMPrivateKeyAdapter = class extends WalletAdapter {
980
+ constructor() {
981
+ super(...arguments);
982
+ this.type = "private-key" /* PRIVATE_KEY */;
983
+ this.chainType = "evm" /* EVM */;
984
+ this.name = "Private Key (EVM)";
985
+ this.privateKey = null;
986
+ this.walletClient = null;
987
+ this.publicClient = null;
988
+ }
989
+ /**
990
+ * 连接(导入私钥)
991
+ */
992
+ async connect(chainId = 1) {
993
+ if (!this.privateKey) {
994
+ throw new Error("Private key not set. Call setPrivateKey() first.");
995
+ }
996
+ try {
997
+ this.setState("connecting" /* CONNECTING */);
998
+ const account = accounts.privateKeyToAccount(this.privateKey);
999
+ this.walletClient = viem.createWalletClient({
1000
+ account,
1001
+ chain: this.getViemChain(chainId),
1002
+ transport: viem.http()
1003
+ });
1004
+ this.publicClient = viem.createPublicClient({
1005
+ chain: this.getViemChain(chainId),
1006
+ transport: viem.http()
1007
+ });
1008
+ const address = formatEVMAddress(account.address);
1009
+ const accountInfo = {
1010
+ universalAddress: createUniversalAddress(chainId, address),
1011
+ nativeAddress: address,
1012
+ chainId,
1013
+ chainType: "evm" /* EVM */,
1014
+ isActive: true
1015
+ };
1016
+ this.setState("connected" /* CONNECTED */);
1017
+ this.setAccount(accountInfo);
1018
+ return accountInfo;
1019
+ } catch (error) {
1020
+ this.setState("error" /* ERROR */);
1021
+ this.setAccount(null);
1022
+ throw error;
1023
+ }
1024
+ }
1025
+ /**
1026
+ * 断开连接
1027
+ */
1028
+ async disconnect() {
1029
+ this.privateKey = null;
1030
+ this.walletClient = null;
1031
+ this.publicClient = null;
1032
+ this.setState("disconnected" /* DISCONNECTED */);
1033
+ this.setAccount(null);
1034
+ this.emitDisconnected();
1035
+ }
1036
+ /**
1037
+ * 检查是否可用(私钥钱包总是可用)
1038
+ */
1039
+ async isAvailable() {
1040
+ return true;
1041
+ }
1042
+ /**
1043
+ * 设置私钥
1044
+ */
1045
+ setPrivateKey(privateKey) {
1046
+ this.privateKey = privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
1047
+ }
1048
+ /**
1049
+ * 签名消息
1050
+ */
1051
+ async signMessage(message) {
1052
+ this.ensureConnected();
1053
+ if (!this.walletClient || !this.walletClient.account) {
1054
+ throw new Error("Wallet client not initialized");
1055
+ }
1056
+ const signature = await this.walletClient.signMessage({
1057
+ message,
1058
+ account: this.walletClient.account
1059
+ });
1060
+ return signature;
1061
+ }
1062
+ /**
1063
+ * 签名 TypedData
1064
+ */
1065
+ async signTypedData(typedData) {
1066
+ this.ensureConnected();
1067
+ if (!this.walletClient || !this.walletClient.account) {
1068
+ throw new Error("Wallet client not initialized");
1069
+ }
1070
+ const signature = await this.walletClient.signTypedData({
1071
+ ...typedData,
1072
+ account: this.walletClient.account
1073
+ });
1074
+ return signature;
1075
+ }
1076
+ /**
1077
+ * 切换链
1078
+ */
1079
+ async switchChain(chainId) {
1080
+ this.ensureConnected();
1081
+ const account = this.walletClient.account;
1082
+ this.walletClient = viem.createWalletClient({
1083
+ account,
1084
+ chain: this.getViemChain(chainId),
1085
+ transport: viem.http()
1086
+ });
1087
+ this.publicClient = viem.createPublicClient({
1088
+ chain: this.getViemChain(chainId),
1089
+ transport: viem.http()
1090
+ });
1091
+ const updatedAccount = {
1092
+ ...this.currentAccount,
1093
+ chainId,
1094
+ universalAddress: createUniversalAddress(chainId, this.currentAccount.nativeAddress)
1095
+ };
1096
+ this.setAccount(updatedAccount);
1097
+ this.emitChainChanged(chainId);
1098
+ }
1099
+ /**
1100
+ * 读取合约
1101
+ */
1102
+ async readContract(params) {
1103
+ if (!this.publicClient) {
1104
+ throw new Error("Public client not initialized");
1105
+ }
1106
+ const result = await this.publicClient.readContract({
1107
+ address: params.address,
1108
+ abi: params.abi,
1109
+ functionName: params.functionName,
1110
+ ...params.args ? { args: params.args } : {}
1111
+ });
1112
+ return result;
1113
+ }
1114
+ /**
1115
+ * 写入合约
1116
+ */
1117
+ async writeContract(params) {
1118
+ this.ensureConnected();
1119
+ if (!this.walletClient) {
1120
+ throw new Error("Wallet client not initialized");
1121
+ }
1122
+ const txHash = await this.walletClient.writeContract({
1123
+ address: params.address,
1124
+ abi: params.abi,
1125
+ functionName: params.functionName,
1126
+ ...params.args ? { args: params.args } : {},
1127
+ value: params.value ? BigInt(params.value) : void 0,
1128
+ gas: params.gas ? BigInt(params.gas) : void 0,
1129
+ gasPrice: params.gasPrice ? BigInt(params.gasPrice) : void 0
1130
+ });
1131
+ return txHash;
1132
+ }
1133
+ /**
1134
+ * 估算 gas
1135
+ */
1136
+ async estimateGas(params) {
1137
+ if (!this.publicClient || !this.currentAccount) {
1138
+ throw new Error("Client not initialized");
1139
+ }
1140
+ const gas = await this.publicClient.estimateContractGas({
1141
+ address: params.address,
1142
+ abi: params.abi,
1143
+ functionName: params.functionName,
1144
+ ...params.args ? { args: params.args } : {},
1145
+ value: params.value ? BigInt(params.value) : void 0,
1146
+ account: this.currentAccount.nativeAddress
1147
+ });
1148
+ return gas;
1149
+ }
1150
+ /**
1151
+ * 等待交易确认
1152
+ */
1153
+ async waitForTransaction(txHash, confirmations = 1) {
1154
+ if (!this.publicClient) {
1155
+ throw new Error("Public client not initialized");
1156
+ }
1157
+ const receipt = await this.publicClient.waitForTransactionReceipt({
1158
+ hash: txHash,
1159
+ confirmations
1160
+ });
1161
+ if (receipt.status === "reverted") {
1162
+ throw new TransactionFailedError(txHash, "Transaction reverted");
1163
+ }
1164
+ return {
1165
+ transactionHash: receipt.transactionHash,
1166
+ blockNumber: Number(receipt.blockNumber),
1167
+ blockHash: receipt.blockHash,
1168
+ from: receipt.from,
1169
+ to: receipt.to || void 0,
1170
+ status: receipt.status === "success" ? "success" : "failed",
1171
+ gasUsed: receipt.gasUsed.toString(),
1172
+ effectiveGasPrice: receipt.effectiveGasPrice?.toString(),
1173
+ logs: receipt.logs
1174
+ };
1175
+ }
1176
+ /**
1177
+ * 获取 Provider
1178
+ */
1179
+ getProvider() {
1180
+ return this.publicClient;
1181
+ }
1182
+ /**
1183
+ * 获取 Signer
1184
+ */
1185
+ getSigner() {
1186
+ return this.walletClient;
1187
+ }
1188
+ /**
1189
+ * 获取 viem chain 配置
1190
+ */
1191
+ getViemChain(chainId) {
1192
+ const chainInfo = getChainInfo(chainId);
1193
+ if (chainInfo) {
1194
+ return {
1195
+ id: chainId,
1196
+ name: chainInfo.name,
1197
+ network: chainInfo.name.toLowerCase().replace(/\s+/g, "-"),
1198
+ nativeCurrency: chainInfo.nativeCurrency,
1199
+ rpcUrls: {
1200
+ default: { http: chainInfo.rpcUrls },
1201
+ public: { http: chainInfo.rpcUrls }
1202
+ },
1203
+ blockExplorers: chainInfo.blockExplorerUrls ? {
1204
+ default: { name: "Explorer", url: chainInfo.blockExplorerUrls[0] }
1205
+ } : void 0
1206
+ };
1207
+ }
1208
+ return {
1209
+ id: chainId,
1210
+ name: `Chain ${chainId}`,
1211
+ network: `chain-${chainId}`,
1212
+ nativeCurrency: {
1213
+ name: "ETH",
1214
+ symbol: "ETH",
1215
+ decimals: 18
1216
+ },
1217
+ rpcUrls: {
1218
+ default: { http: [] },
1219
+ public: { http: [] }
1220
+ }
1221
+ };
1222
+ }
1223
+ };
1224
+
1225
+ // src/core/adapter-registry.ts
1226
+ var AdapterRegistry = class {
1227
+ constructor() {
1228
+ this.adapters = /* @__PURE__ */ new Map();
1229
+ this.registerDefaultAdapters();
1230
+ }
1231
+ /**
1232
+ * 注册默认适配器
1233
+ */
1234
+ registerDefaultAdapters() {
1235
+ this.register("metamask" /* METAMASK */, () => new MetaMaskAdapter());
1236
+ this.register("private-key" /* PRIVATE_KEY */, () => new EVMPrivateKeyAdapter());
1237
+ this.register("tronlink" /* TRONLINK */, () => new TronLinkAdapter());
1238
+ }
1239
+ /**
1240
+ * 注册适配器
1241
+ */
1242
+ register(type, factory) {
1243
+ this.adapters.set(type, factory);
1244
+ }
1245
+ /**
1246
+ * 获取适配器
1247
+ */
1248
+ getAdapter(type) {
1249
+ const factory = this.adapters.get(type);
1250
+ if (!factory) {
1251
+ return null;
1252
+ }
1253
+ return factory();
1254
+ }
1255
+ /**
1256
+ * 判断适配器是否已注册
1257
+ */
1258
+ has(type) {
1259
+ return this.adapters.has(type);
1260
+ }
1261
+ /**
1262
+ * 获取所有已注册的适配器类型
1263
+ */
1264
+ getRegisteredTypes() {
1265
+ return Array.from(this.adapters.keys());
1266
+ }
1267
+ /**
1268
+ * 根据链类型获取适配器类型列表
1269
+ */
1270
+ getAdapterTypesByChainType(chainType) {
1271
+ const types = [];
1272
+ for (const type of this.adapters.keys()) {
1273
+ const adapter = this.getAdapter(type);
1274
+ if (adapter && adapter.chainType === chainType) {
1275
+ types.push(type);
1276
+ }
1277
+ }
1278
+ return types;
1279
+ }
1280
+ };
1281
+
1282
+ // src/core/wallet-manager.ts
1283
+ var WalletManager = class extends TypedEventEmitter {
1284
+ constructor(config = {}) {
1285
+ super();
1286
+ // 主钱包
1287
+ this.primaryWallet = null;
1288
+ // 已连接钱包池
1289
+ this.connectedWallets = /* @__PURE__ */ new Map();
1290
+ this.config = {
1291
+ enableStorage: config.enableStorage ?? true,
1292
+ storagePrefix: config.storagePrefix ?? "enclave_wallet_",
1293
+ defaultChainId: config.defaultChainId ?? 1,
1294
+ defaultTronChainId: config.defaultTronChainId ?? 195,
1295
+ walletConnectProjectId: config.walletConnectProjectId ?? ""
1296
+ };
1297
+ this.registry = new AdapterRegistry();
1298
+ if (this.config.enableStorage) {
1299
+ this.restoreFromStorage();
1300
+ }
1301
+ }
1302
+ // ===== 连接管理 =====
1303
+ /**
1304
+ * 连接主钱包
1305
+ */
1306
+ async connect(type, chainId) {
1307
+ const adapter = this.registry.getAdapter(type);
1308
+ if (!adapter) {
1309
+ throw new WalletNotAvailableError(type);
1310
+ }
1311
+ const isAvailable = await adapter.isAvailable();
1312
+ if (!isAvailable) {
1313
+ throw new WalletNotAvailableError(type);
1314
+ }
1315
+ const account = await adapter.connect(chainId);
1316
+ this.setPrimaryWallet(adapter);
1317
+ this.connectedWallets.set(adapter.chainType, adapter);
1318
+ this.setupAdapterListeners(adapter, true);
1319
+ if (this.config.enableStorage) {
1320
+ this.saveToStorage();
1321
+ }
1322
+ return account;
1323
+ }
1324
+ /**
1325
+ * 连接额外的钱包(不改变主钱包)
1326
+ */
1327
+ async connectAdditional(type, chainId) {
1328
+ const adapter = this.registry.getAdapter(type);
1329
+ if (!adapter) {
1330
+ throw new WalletNotAvailableError(type);
1331
+ }
1332
+ const isAvailable = await adapter.isAvailable();
1333
+ if (!isAvailable) {
1334
+ throw new WalletNotAvailableError(type);
1335
+ }
1336
+ const account = await adapter.connect(chainId);
1337
+ this.connectedWallets.set(adapter.chainType, adapter);
1338
+ this.setupAdapterListeners(adapter, false);
1339
+ if (this.config.enableStorage) {
1340
+ this.saveToStorage();
1341
+ }
1342
+ return account;
1343
+ }
1344
+ /**
1345
+ * 使用私钥连接(仅用于开发/测试)
1346
+ */
1347
+ async connectWithPrivateKey(privateKey, chainId) {
1348
+ const adapter = new EVMPrivateKeyAdapter();
1349
+ adapter.setPrivateKey(privateKey);
1350
+ const account = await adapter.connect(chainId || this.config.defaultChainId);
1351
+ this.setPrimaryWallet(adapter);
1352
+ this.connectedWallets.set(adapter.chainType, adapter);
1353
+ this.setupAdapterListeners(adapter, true);
1354
+ return account;
1355
+ }
1356
+ /**
1357
+ * 断开主钱包
1358
+ */
1359
+ async disconnect() {
1360
+ if (!this.primaryWallet) {
1361
+ return;
1362
+ }
1363
+ await this.primaryWallet.disconnect();
1364
+ this.removeAdapterListeners(this.primaryWallet);
1365
+ this.connectedWallets.delete(this.primaryWallet.chainType);
1366
+ this.primaryWallet = null;
1367
+ if (this.config.enableStorage) {
1368
+ this.saveToStorage();
1369
+ }
1370
+ this.emit("disconnected");
1371
+ }
1372
+ /**
1373
+ * 断开所有钱包
1374
+ */
1375
+ async disconnectAll() {
1376
+ const wallets = Array.from(this.connectedWallets.values());
1377
+ for (const wallet of wallets) {
1378
+ await wallet.disconnect();
1379
+ this.removeAdapterListeners(wallet);
1380
+ }
1381
+ this.primaryWallet = null;
1382
+ this.connectedWallets.clear();
1383
+ if (this.config.enableStorage) {
1384
+ this.clearStorage();
1385
+ }
1386
+ this.emit("disconnected");
1387
+ }
1388
+ // ===== 主钱包管理 =====
1389
+ /**
1390
+ * 切换主钱包
1391
+ */
1392
+ async switchPrimaryWallet(chainType) {
1393
+ const adapter = this.connectedWallets.get(chainType);
1394
+ if (!adapter || !adapter.currentAccount) {
1395
+ throw new WalletNotConnectedError(`Wallet for chain type ${chainType} not connected`);
1396
+ }
1397
+ const oldPrimary = this.primaryWallet?.currentAccount || null;
1398
+ if (this.primaryWallet) {
1399
+ this.removeAdapterListeners(this.primaryWallet);
1400
+ }
1401
+ this.setPrimaryWallet(adapter);
1402
+ this.setupAdapterListeners(adapter, true);
1403
+ if (this.config.enableStorage) {
1404
+ this.saveToStorage();
1405
+ }
1406
+ this.emit("primaryWalletSwitched", adapter.currentAccount, oldPrimary, chainType);
1407
+ return adapter.currentAccount;
1408
+ }
1409
+ /**
1410
+ * 获取主钱包账户
1411
+ */
1412
+ getPrimaryAccount() {
1413
+ return this.primaryWallet?.currentAccount || null;
1414
+ }
1415
+ /**
1416
+ * 获取所有已连接的钱包
1417
+ */
1418
+ getConnectedWallets() {
1419
+ return Array.from(this.connectedWallets.values()).map((adapter) => ({
1420
+ account: adapter.currentAccount,
1421
+ walletType: adapter.type,
1422
+ chainType: adapter.chainType,
1423
+ isPrimary: adapter === this.primaryWallet,
1424
+ canSwitchChain: this.canSwitchChain(adapter),
1425
+ adapter
1426
+ }));
1427
+ }
1428
+ /**
1429
+ * 根据链类型获取钱包
1430
+ */
1431
+ getWalletByChainType(chainType) {
1432
+ return this.connectedWallets.get(chainType) || null;
1433
+ }
1434
+ // ===== 签名 =====
1435
+ /**
1436
+ * 使用主钱包签名
1437
+ */
1438
+ async signMessage(message) {
1439
+ if (!this.primaryWallet) {
1440
+ throw new WalletNotConnectedError();
1441
+ }
1442
+ return this.primaryWallet.signMessage(message);
1443
+ }
1444
+ /**
1445
+ * 使用指定链类型的钱包签名
1446
+ */
1447
+ async signMessageWithChainType(message, chainType) {
1448
+ if (!chainType) {
1449
+ return this.signMessage(message);
1450
+ }
1451
+ const adapter = this.connectedWallets.get(chainType);
1452
+ if (!adapter) {
1453
+ throw new WalletNotConnectedError(`Wallet for chain type ${chainType}`);
1454
+ }
1455
+ return adapter.signMessage(message);
1456
+ }
1457
+ /**
1458
+ * 签名 TypedData(仅 EVM)
1459
+ */
1460
+ async signTypedData(typedData, chainType) {
1461
+ const adapter = chainType ? this.connectedWallets.get(chainType) : this.primaryWallet;
1462
+ if (!adapter) {
1463
+ throw new WalletNotConnectedError();
1464
+ }
1465
+ if (!adapter.signTypedData) {
1466
+ throw new Error(`signTypedData not supported by ${adapter.type}`);
1467
+ }
1468
+ return adapter.signTypedData(typedData);
1469
+ }
1470
+ // ===== 链切换 =====
1471
+ /**
1472
+ * 请求切换链(仅 EVM)
1473
+ */
1474
+ async requestSwitchChain(chainId, options) {
1475
+ if (!this.primaryWallet) {
1476
+ throw new WalletNotConnectedError();
1477
+ }
1478
+ if (!this.primaryWallet.switchChain) {
1479
+ throw new Error(`Chain switching not supported by ${this.primaryWallet.type}`);
1480
+ }
1481
+ try {
1482
+ await this.primaryWallet.switchChain(chainId);
1483
+ return this.primaryWallet.currentAccount;
1484
+ } catch (error) {
1485
+ if (options?.addChainIfNotExists && options.chainConfig && this.primaryWallet.addChain) {
1486
+ await this.primaryWallet.addChain(options.chainConfig);
1487
+ await this.primaryWallet.switchChain(chainId);
1488
+ return this.primaryWallet.currentAccount;
1489
+ }
1490
+ throw error;
1491
+ }
1492
+ }
1493
+ // ===== 合约调用 =====
1494
+ /**
1495
+ * 读取合约
1496
+ */
1497
+ async readContract(address, abi, functionName, args, chainType) {
1498
+ const adapter = chainType ? this.connectedWallets.get(chainType) : this.primaryWallet;
1499
+ if (!adapter) {
1500
+ throw new WalletNotConnectedError();
1501
+ }
1502
+ if (!adapter.readContract) {
1503
+ throw new Error(`readContract not supported by ${adapter.type}`);
1504
+ }
1505
+ return adapter.readContract({ address, abi, functionName, args });
1506
+ }
1507
+ /**
1508
+ * 写入合约
1509
+ */
1510
+ async writeContract(address, abi, functionName, args, options, chainType) {
1511
+ const adapter = chainType ? this.connectedWallets.get(chainType) : this.primaryWallet;
1512
+ if (!adapter) {
1513
+ throw new WalletNotConnectedError();
1514
+ }
1515
+ if (!adapter.writeContract) {
1516
+ throw new Error(`writeContract not supported by ${adapter.type}`);
1517
+ }
1518
+ return adapter.writeContract({
1519
+ address,
1520
+ abi,
1521
+ functionName,
1522
+ args,
1523
+ ...options
1524
+ });
1525
+ }
1526
+ /**
1527
+ * 估算 Gas
1528
+ */
1529
+ async estimateGas(address, abi, functionName, args, chainType) {
1530
+ const adapter = chainType ? this.connectedWallets.get(chainType) : this.primaryWallet;
1531
+ if (!adapter) {
1532
+ throw new WalletNotConnectedError();
1533
+ }
1534
+ if (!adapter.estimateGas) {
1535
+ throw new Error(`estimateGas not supported by ${adapter.type}`);
1536
+ }
1537
+ return adapter.estimateGas({ address, abi, functionName, args });
1538
+ }
1539
+ /**
1540
+ * 等待交易确认
1541
+ */
1542
+ async waitForTransaction(txHash, confirmations, chainType) {
1543
+ const adapter = chainType ? this.connectedWallets.get(chainType) : this.primaryWallet;
1544
+ if (!adapter) {
1545
+ throw new WalletNotConnectedError();
1546
+ }
1547
+ if (!adapter.waitForTransaction) {
1548
+ throw new Error(`waitForTransaction not supported by ${adapter.type}`);
1549
+ }
1550
+ return adapter.waitForTransaction(txHash, confirmations);
1551
+ }
1552
+ // ===== Provider 访问 =====
1553
+ /**
1554
+ * 获取主钱包 Provider
1555
+ */
1556
+ getProvider() {
1557
+ if (!this.primaryWallet) {
1558
+ throw new WalletNotConnectedError();
1559
+ }
1560
+ return this.primaryWallet.getProvider();
1561
+ }
1562
+ /**
1563
+ * 获取指定链类型的 Provider
1564
+ */
1565
+ getProviderByChainType(chainType) {
1566
+ const adapter = this.connectedWallets.get(chainType);
1567
+ if (!adapter) {
1568
+ throw new WalletNotConnectedError(`Wallet for chain type ${chainType}`);
1569
+ }
1570
+ return adapter.getProvider();
1571
+ }
1572
+ // ===== 私有方法 =====
1573
+ /**
1574
+ * 设置主钱包
1575
+ */
1576
+ setPrimaryWallet(adapter) {
1577
+ this.primaryWallet = adapter;
1578
+ }
1579
+ /**
1580
+ * 判断钱包是否支持链切换
1581
+ */
1582
+ canSwitchChain(adapter) {
1583
+ return !!adapter.switchChain;
1584
+ }
1585
+ /**
1586
+ * 设置适配器事件监听
1587
+ */
1588
+ setupAdapterListeners(adapter, isPrimary) {
1589
+ adapter.on("accountChanged", (account) => {
1590
+ if (isPrimary) {
1591
+ this.emit("accountChanged", account);
1592
+ }
1593
+ this.emit("walletAccountChanged", adapter.chainType, account, isPrimary);
1594
+ if (this.config.enableStorage) {
1595
+ this.saveToStorage();
1596
+ }
1597
+ });
1598
+ adapter.on("chainChanged", (chainId) => {
1599
+ if (isPrimary && adapter.currentAccount) {
1600
+ this.emit("chainChanged", chainId, adapter.currentAccount);
1601
+ }
1602
+ if (adapter.currentAccount) {
1603
+ this.emit("walletChainChanged", adapter.chainType, chainId, adapter.currentAccount, isPrimary);
1604
+ }
1605
+ if (this.config.enableStorage) {
1606
+ this.saveToStorage();
1607
+ }
1608
+ });
1609
+ adapter.on("disconnected", () => {
1610
+ if (isPrimary) {
1611
+ this.emit("disconnected");
1612
+ }
1613
+ this.emit("walletDisconnected", adapter.chainType, isPrimary);
1614
+ this.connectedWallets.delete(adapter.chainType);
1615
+ if (adapter === this.primaryWallet) {
1616
+ this.primaryWallet = null;
1617
+ }
1618
+ if (this.config.enableStorage) {
1619
+ this.saveToStorage();
1620
+ }
1621
+ });
1622
+ adapter.on("error", (error) => {
1623
+ this.emit("error", error);
1624
+ });
1625
+ }
1626
+ /**
1627
+ * 移除适配器事件监听
1628
+ */
1629
+ removeAdapterListeners(adapter) {
1630
+ adapter.removeAllListeners();
1631
+ }
1632
+ // ===== 存储 =====
1633
+ /**
1634
+ * 保存到存储
1635
+ */
1636
+ saveToStorage() {
1637
+ if (typeof window === "undefined" || !this.config.enableStorage) {
1638
+ return;
1639
+ }
1640
+ const data = {
1641
+ current: this.primaryWallet?.currentAccount?.universalAddress || null,
1642
+ history: this.getHistoryRecords()
1643
+ };
1644
+ try {
1645
+ localStorage.setItem(
1646
+ `${this.config.storagePrefix}data`,
1647
+ JSON.stringify(data)
1648
+ );
1649
+ } catch (error) {
1650
+ console.error("Failed to save wallet data to storage:", error);
1651
+ }
1652
+ }
1653
+ /**
1654
+ * 从存储恢复
1655
+ */
1656
+ restoreFromStorage() {
1657
+ }
1658
+ /**
1659
+ * 清除存储
1660
+ */
1661
+ clearStorage() {
1662
+ if (typeof window === "undefined") {
1663
+ return;
1664
+ }
1665
+ try {
1666
+ localStorage.removeItem(`${this.config.storagePrefix}data`);
1667
+ } catch (error) {
1668
+ console.error("Failed to clear wallet data from storage:", error);
1669
+ }
1670
+ }
1671
+ /**
1672
+ * 获取历史记录
1673
+ */
1674
+ getHistoryRecords() {
1675
+ const records = [];
1676
+ for (const adapter of this.connectedWallets.values()) {
1677
+ if (adapter.currentAccount) {
1678
+ records.push({
1679
+ universalAddress: adapter.currentAccount.universalAddress,
1680
+ nativeAddress: adapter.currentAccount.nativeAddress,
1681
+ chainId: adapter.currentAccount.chainId,
1682
+ chainType: adapter.chainType,
1683
+ walletType: adapter.type,
1684
+ lastConnected: Date.now(),
1685
+ name: adapter.currentAccount.name
1686
+ });
1687
+ }
1688
+ }
1689
+ return records;
1690
+ }
1691
+ };
1692
+
1693
+ // src/auth/message-generator.ts
1694
+ var AuthMessageGenerator = class {
1695
+ constructor(domain) {
1696
+ this.domain = domain;
1697
+ }
1698
+ /**
1699
+ * 生成认证消息
1700
+ */
1701
+ generateAuthMessage(chainType, nonce, chainId, timestamp = Date.now(), statement) {
1702
+ switch (chainType) {
1703
+ case "evm" /* EVM */:
1704
+ return this.generateEIP191Message({
1705
+ domain: this.domain,
1706
+ nonce,
1707
+ chainId,
1708
+ timestamp,
1709
+ statement
1710
+ });
1711
+ case "tron" /* TRON */:
1712
+ return this.generateTIP191Message({
1713
+ domain: this.domain,
1714
+ nonce,
1715
+ chainId,
1716
+ timestamp,
1717
+ statement
1718
+ });
1719
+ default:
1720
+ throw new Error(`Unsupported chain type: ${chainType}`);
1721
+ }
1722
+ }
1723
+ /**
1724
+ * 生成 EIP-191 格式的认证消息
1725
+ */
1726
+ generateEIP191Message(params) {
1727
+ const lines = [
1728
+ `${params.domain} wants you to sign in.`,
1729
+ ""
1730
+ ];
1731
+ if (params.statement) {
1732
+ lines.push(params.statement, "");
1733
+ }
1734
+ lines.push(
1735
+ `Nonce: ${params.nonce}`,
1736
+ `Chain ID: ${params.chainId}`,
1737
+ `Issued At: ${new Date(params.timestamp).toISOString()}`
1738
+ );
1739
+ return lines.join("\n");
1740
+ }
1741
+ /**
1742
+ * 生成 TIP-191 格式的认证消息
1743
+ */
1744
+ generateTIP191Message(params) {
1745
+ const lines = [
1746
+ `${params.domain} wants you to sign in with your Tron account.`,
1747
+ ""
1748
+ ];
1749
+ if (params.statement) {
1750
+ lines.push(params.statement, "");
1751
+ }
1752
+ lines.push(
1753
+ `Nonce: ${params.nonce}`,
1754
+ `Chain ID: ${params.chainId}`,
1755
+ `Issued At: ${new Date(params.timestamp).toISOString()}`
1756
+ );
1757
+ return lines.join("\n");
1758
+ }
1759
+ /**
1760
+ * 生成随机 nonce
1761
+ */
1762
+ static generateNonce() {
1763
+ const array = new Uint8Array(16);
1764
+ crypto.getRandomValues(array);
1765
+ return Array.from(array, (byte) => byte.toString(16).padStart(2, "0")).join("");
1766
+ }
1767
+ };
1768
+ var SignatureVerifier = class {
1769
+ /**
1770
+ * 验证签名
1771
+ */
1772
+ async verifySignature(message, signature, expectedAddress, chainType) {
1773
+ switch (chainType) {
1774
+ case "evm" /* EVM */:
1775
+ return this.verifyEIP191Signature(message, signature, expectedAddress);
1776
+ case "tron" /* TRON */:
1777
+ return this.verifyTIP191Signature(message, signature, expectedAddress);
1778
+ default:
1779
+ throw new Error(`Unsupported chain type: ${chainType}`);
1780
+ }
1781
+ }
1782
+ /**
1783
+ * 验证 EIP-191 签名
1784
+ */
1785
+ async verifyEIP191Signature(message, signature, expectedAddress) {
1786
+ try {
1787
+ const isValid = await viem.verifyMessage({
1788
+ address: expectedAddress,
1789
+ message,
1790
+ signature
1791
+ });
1792
+ return isValid;
1793
+ } catch (error) {
1794
+ console.error("EIP-191 signature verification failed:", error);
1795
+ return false;
1796
+ }
1797
+ }
1798
+ /**
1799
+ * 验证 TIP-191 签名
1800
+ * 注意:这里需要 TronWeb 或类似库来验证 Tron 签名
1801
+ * 这是一个占位实现
1802
+ */
1803
+ async verifyTIP191Signature(_message, _signature, _expectedAddress) {
1804
+ console.warn("TIP-191 signature verification not implemented yet");
1805
+ return false;
1806
+ }
1807
+ };
1808
+
1809
+ // src/detection/supported-wallets.ts
1810
+ var SUPPORTED_WALLETS = {
1811
+ ["metamask" /* METAMASK */]: {
1812
+ type: "metamask" /* METAMASK */,
1813
+ name: "MetaMask",
1814
+ chainType: "evm" /* EVM */,
1815
+ icon: "https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg",
1816
+ downloadUrl: "https://metamask.io/download/",
1817
+ description: "The most popular Ethereum wallet"
1818
+ },
1819
+ ["walletconnect" /* WALLETCONNECT */]: {
1820
+ type: "walletconnect" /* WALLETCONNECT */,
1821
+ name: "WalletConnect",
1822
+ chainType: "evm" /* EVM */,
1823
+ icon: "https://avatars.githubusercontent.com/u/37784886",
1824
+ downloadUrl: "https://walletconnect.com/",
1825
+ description: "Connect to 170+ wallets"
1826
+ },
1827
+ ["coinbase-wallet" /* COINBASE_WALLET */]: {
1828
+ type: "coinbase-wallet" /* COINBASE_WALLET */,
1829
+ name: "Coinbase Wallet",
1830
+ chainType: "evm" /* EVM */,
1831
+ icon: "https://www.coinbase.com/img/favicon/favicon-96x96.png",
1832
+ downloadUrl: "https://www.coinbase.com/wallet",
1833
+ description: "Coinbase self-custody wallet"
1834
+ },
1835
+ ["tronlink" /* TRONLINK */]: {
1836
+ type: "tronlink" /* TRONLINK */,
1837
+ name: "TronLink",
1838
+ chainType: "tron" /* TRON */,
1839
+ icon: "https://www.tronlink.org/static/logoIcon.svg",
1840
+ downloadUrl: "https://www.tronlink.org/",
1841
+ description: "The official Tron wallet"
1842
+ },
1843
+ ["walletconnect-tron" /* WALLETCONNECT_TRON */]: {
1844
+ type: "walletconnect-tron" /* WALLETCONNECT_TRON */,
1845
+ name: "WalletConnect (Tron)",
1846
+ chainType: "tron" /* TRON */,
1847
+ downloadUrl: "https://walletconnect.com/",
1848
+ description: "WalletConnect for Tron"
1849
+ },
1850
+ ["private-key" /* PRIVATE_KEY */]: {
1851
+ type: "private-key" /* PRIVATE_KEY */,
1852
+ name: "Private Key",
1853
+ chainType: "evm" /* EVM */,
1854
+ // 可以用于任何链
1855
+ description: "Import wallet using private key (for development)"
1856
+ }
1857
+ };
1858
+ function getWalletMetadata(type) {
1859
+ return SUPPORTED_WALLETS[type];
1860
+ }
1861
+ function getEVMWallets() {
1862
+ return Object.values(SUPPORTED_WALLETS).filter(
1863
+ (wallet) => wallet.chainType === "evm" /* EVM */
1864
+ );
1865
+ }
1866
+ function getTronWallets() {
1867
+ return Object.values(SUPPORTED_WALLETS).filter(
1868
+ (wallet) => wallet.chainType === "tron" /* TRON */
1869
+ );
1870
+ }
1871
+
1872
+ // src/detection/detector.ts
1873
+ var WalletDetector = class {
1874
+ /**
1875
+ * 检测所有钱包可用性
1876
+ */
1877
+ async detectAllWallets() {
1878
+ const walletTypes = Object.values(WalletType).filter(
1879
+ (type) => type !== "private-key" /* PRIVATE_KEY */
1880
+ // 私钥钱包不需要检测
1881
+ );
1882
+ const results = await Promise.all(
1883
+ walletTypes.map((type) => this.detectWallet(type))
1884
+ );
1885
+ return results;
1886
+ }
1887
+ /**
1888
+ * 检测特定钱包
1889
+ */
1890
+ async detectWallet(walletType) {
1891
+ const metadata = SUPPORTED_WALLETS[walletType];
1892
+ if (!metadata) {
1893
+ return {
1894
+ walletType,
1895
+ chainType: "evm" /* EVM */,
1896
+ // 默认
1897
+ isAvailable: false,
1898
+ detected: false
1899
+ };
1900
+ }
1901
+ const isAvailable = await this.isWalletAvailable(walletType);
1902
+ return {
1903
+ walletType,
1904
+ chainType: metadata.chainType,
1905
+ isAvailable,
1906
+ downloadUrl: metadata.downloadUrl,
1907
+ detected: isAvailable
1908
+ };
1909
+ }
1910
+ /**
1911
+ * 判断钱包是否可用
1912
+ */
1913
+ async isWalletAvailable(walletType) {
1914
+ if (typeof window === "undefined") {
1915
+ return false;
1916
+ }
1917
+ switch (walletType) {
1918
+ case "metamask" /* METAMASK */:
1919
+ return this.isMetaMaskAvailable();
1920
+ case "tronlink" /* TRONLINK */:
1921
+ return this.isTronLinkAvailable();
1922
+ case "coinbase-wallet" /* COINBASE_WALLET */:
1923
+ return this.isCoinbaseWalletAvailable();
1924
+ case "walletconnect" /* WALLETCONNECT */:
1925
+ case "walletconnect-tron" /* WALLETCONNECT_TRON */:
1926
+ return true;
1927
+ case "private-key" /* PRIVATE_KEY */:
1928
+ return true;
1929
+ default:
1930
+ return false;
1931
+ }
1932
+ }
1933
+ /**
1934
+ * 检测 MetaMask
1935
+ */
1936
+ isMetaMaskAvailable() {
1937
+ const w = window;
1938
+ return !!(w.ethereum && w.ethereum.isMetaMask);
1939
+ }
1940
+ /**
1941
+ * 检测 TronLink
1942
+ */
1943
+ isTronLinkAvailable() {
1944
+ const w = window;
1945
+ return !!(w.tronLink || w.tronWeb);
1946
+ }
1947
+ /**
1948
+ * 检测 Coinbase Wallet
1949
+ */
1950
+ isCoinbaseWalletAvailable() {
1951
+ const w = window;
1952
+ return !!(w.ethereum && w.ethereum.isCoinbaseWallet);
1953
+ }
1954
+ /**
1955
+ * 等待钱包加载(有些钱包可能延迟注入)
1956
+ */
1957
+ async waitForWallet(walletType, timeout = 3e3) {
1958
+ const startTime = Date.now();
1959
+ while (Date.now() - startTime < timeout) {
1960
+ if (await this.isWalletAvailable(walletType)) {
1961
+ return true;
1962
+ }
1963
+ await new Promise((resolve) => setTimeout(resolve, 100));
1964
+ }
1965
+ return false;
1966
+ }
1967
+ };
1968
+
1969
+ // src/utils/address/tron-converter.ts
1970
+ function isValidTronAddress(address) {
1971
+ if (!address || typeof address !== "string") {
1972
+ return false;
1973
+ }
1974
+ if (address.length !== 34 || !address.startsWith("T")) {
1975
+ return false;
1976
+ }
1977
+ const base58Regex = /^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]+$/;
1978
+ return base58Regex.test(address);
1979
+ }
1980
+ function isValidTronHexAddress(address) {
1981
+ if (!address || typeof address !== "string") {
1982
+ return false;
1983
+ }
1984
+ if (address.length !== 42 || !address.startsWith("41")) {
1985
+ return false;
1986
+ }
1987
+ const hexRegex = /^[0-9a-fA-F]+$/;
1988
+ return hexRegex.test(address.substring(2));
1989
+ }
1990
+ function compareTronAddresses(a, b) {
1991
+ return a === b;
1992
+ }
1993
+ function shortenTronAddress(address, chars = 4) {
1994
+ if (!isValidTronAddress(address)) {
1995
+ return address;
1996
+ }
1997
+ return `${address.substring(0, chars + 1)}...${address.substring(34 - chars)}`;
1998
+ }
1999
+
2000
+ // src/utils/validation.ts
2001
+ function validateAddress(address, chainType) {
2002
+ switch (chainType) {
2003
+ case "evm" /* EVM */:
2004
+ return isValidEVMAddress(address);
2005
+ case "tron" /* TRON */:
2006
+ return isValidTronAddress(address);
2007
+ default:
2008
+ return false;
2009
+ }
2010
+ }
2011
+ function validateAddressForChain(address, chainId) {
2012
+ const chainType = getChainType(chainId);
2013
+ if (!chainType) {
2014
+ return false;
2015
+ }
2016
+ return validateAddress(address, chainType);
2017
+ }
2018
+ function isValidChainId(chainId) {
2019
+ return Number.isInteger(chainId) && chainId > 0;
2020
+ }
2021
+ function isValidSignature(signature) {
2022
+ return /^0x[0-9a-fA-F]{130}$/.test(signature);
2023
+ }
2024
+ function isValidTransactionHash(txHash, chainType) {
2025
+ switch (chainType) {
2026
+ case "evm" /* EVM */:
2027
+ return /^0x[0-9a-fA-F]{64}$/.test(txHash);
2028
+ case "tron" /* TRON */:
2029
+ return /^[0-9a-fA-F]{64}$/.test(txHash);
2030
+ default:
2031
+ return false;
2032
+ }
2033
+ }
2034
+
2035
+ // src/utils/hex.ts
2036
+ function isHex(value) {
2037
+ return /^0x[0-9a-fA-F]*$/.test(value);
2038
+ }
2039
+ function toHex(value) {
2040
+ let hex = "";
2041
+ for (let i = 0; i < value.length; i++) {
2042
+ hex += value.charCodeAt(i).toString(16);
2043
+ }
2044
+ return `0x${hex}`;
2045
+ }
2046
+ function fromHex(hex) {
2047
+ const hexString = hex.startsWith("0x") ? hex.slice(2) : hex;
2048
+ let str = "";
2049
+ for (let i = 0; i < hexString.length; i += 2) {
2050
+ str += String.fromCharCode(parseInt(hexString.substr(i, 2), 16));
2051
+ }
2052
+ return str;
2053
+ }
2054
+ function numberToHex(value) {
2055
+ return `0x${value.toString(16)}`;
2056
+ }
2057
+ function hexToNumber(hex) {
2058
+ return parseInt(hex, 16);
2059
+ }
2060
+ function ensureHexPrefix(value) {
2061
+ return value.startsWith("0x") ? value : `0x${value}`;
2062
+ }
2063
+ function removeHexPrefix(value) {
2064
+ return value.startsWith("0x") ? value.slice(2) : value;
2065
+ }
2066
+
2067
+ // src/index.ts
2068
+ var index_default = WalletManager;
2069
+
2070
+ exports.AdapterRegistry = AdapterRegistry;
2071
+ exports.AuthMessageGenerator = AuthMessageGenerator;
2072
+ exports.BrowserWalletAdapter = BrowserWalletAdapter;
2073
+ exports.CHAIN_INFO = CHAIN_INFO;
2074
+ exports.ChainNotSupportedError = ChainNotSupportedError;
2075
+ exports.ChainType = ChainType;
2076
+ exports.ConfigurationError = ConfigurationError;
2077
+ exports.ConnectionRejectedError = ConnectionRejectedError;
2078
+ exports.EVMPrivateKeyAdapter = EVMPrivateKeyAdapter;
2079
+ exports.MetaMaskAdapter = MetaMaskAdapter;
2080
+ exports.MethodNotSupportedError = MethodNotSupportedError;
2081
+ exports.NetworkError = NetworkError;
2082
+ exports.SUPPORTED_WALLETS = SUPPORTED_WALLETS;
2083
+ exports.SignatureRejectedError = SignatureRejectedError;
2084
+ exports.SignatureVerifier = SignatureVerifier;
2085
+ exports.TransactionFailedError = TransactionFailedError;
2086
+ exports.TronLinkAdapter = TronLinkAdapter;
2087
+ exports.WalletAdapter = WalletAdapter;
2088
+ exports.WalletDetector = WalletDetector;
2089
+ exports.WalletManager = WalletManager;
2090
+ exports.WalletNotAvailableError = WalletNotAvailableError;
2091
+ exports.WalletNotConnectedError = WalletNotConnectedError;
2092
+ exports.WalletSDKError = WalletSDKError;
2093
+ exports.WalletState = WalletState;
2094
+ exports.WalletType = WalletType;
2095
+ exports.compareEVMAddresses = compareEVMAddresses;
2096
+ exports.compareTronAddresses = compareTronAddresses;
2097
+ exports.compareUniversalAddresses = compareUniversalAddresses;
2098
+ exports.createUniversalAddress = createUniversalAddress;
2099
+ exports.default = index_default;
2100
+ exports.ensureHexPrefix = ensureHexPrefix;
2101
+ exports.formatEVMAddress = formatEVMAddress;
2102
+ exports.fromHex = fromHex;
2103
+ exports.getAddressFromUniversalAddress = getAddressFromUniversalAddress;
2104
+ exports.getChainIdFromUniversalAddress = getChainIdFromUniversalAddress;
2105
+ exports.getChainInfo = getChainInfo;
2106
+ exports.getChainType = getChainType;
2107
+ exports.getEVMWallets = getEVMWallets;
2108
+ exports.getTronWallets = getTronWallets;
2109
+ exports.getWalletMetadata = getWalletMetadata;
2110
+ exports.hexToNumber = hexToNumber;
2111
+ exports.isEVMChain = isEVMChain;
2112
+ exports.isHex = isHex;
2113
+ exports.isTronChain = isTronChain;
2114
+ exports.isValidChainId = isValidChainId;
2115
+ exports.isValidEVMAddress = isValidEVMAddress;
2116
+ exports.isValidSignature = isValidSignature;
2117
+ exports.isValidTransactionHash = isValidTransactionHash;
2118
+ exports.isValidTronAddress = isValidTronAddress;
2119
+ exports.isValidTronHexAddress = isValidTronHexAddress;
2120
+ exports.isValidUniversalAddress = isValidUniversalAddress;
2121
+ exports.numberToHex = numberToHex;
2122
+ exports.parseUniversalAddress = parseUniversalAddress;
2123
+ exports.removeHexPrefix = removeHexPrefix;
2124
+ exports.shortenAddress = shortenAddress;
2125
+ exports.shortenTronAddress = shortenTronAddress;
2126
+ exports.toHex = toHex;
2127
+ exports.validateAddress = validateAddress;
2128
+ exports.validateAddressForChain = validateAddressForChain;
2129
+ //# sourceMappingURL=index.js.map
2130
+ //# sourceMappingURL=index.js.map