@enclave-hq/wallet-sdk 1.2.4 → 1.2.5

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/tron.js ADDED
@@ -0,0 +1,852 @@
1
+ 'use strict';
2
+
3
+ var walletconnectTron = require('@tronweb3/walletconnect-tron');
4
+ var EventEmitter = require('eventemitter3');
5
+ var chainUtils = require('@enclave-hq/chain-utils');
6
+
7
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
+
9
+ var EventEmitter__default = /*#__PURE__*/_interopDefault(EventEmitter);
10
+
11
+ // src/adapters/tron/wallet-connect.ts
12
+ var ChainType = chainUtils.ChainType;
13
+
14
+ // src/core/errors.ts
15
+ var WalletSDKError = class _WalletSDKError extends Error {
16
+ constructor(message, code, details) {
17
+ super(message);
18
+ this.code = code;
19
+ this.details = details;
20
+ this.name = "WalletSDKError";
21
+ Object.setPrototypeOf(this, _WalletSDKError.prototype);
22
+ }
23
+ };
24
+ var WalletNotConnectedError = class extends WalletSDKError {
25
+ constructor(walletType) {
26
+ super(
27
+ walletType ? `Wallet ${walletType} is not connected` : "No wallet is connected",
28
+ "WALLET_NOT_CONNECTED",
29
+ { walletType }
30
+ );
31
+ this.name = "WalletNotConnectedError";
32
+ }
33
+ };
34
+ var ConnectionRejectedError = class extends WalletSDKError {
35
+ constructor(walletType) {
36
+ super(
37
+ `Connection to ${walletType} was rejected by user`,
38
+ "CONNECTION_REJECTED",
39
+ { walletType }
40
+ );
41
+ this.name = "ConnectionRejectedError";
42
+ }
43
+ };
44
+ var SignatureRejectedError = class extends WalletSDKError {
45
+ constructor(message) {
46
+ super(
47
+ message || "Signature was rejected by user",
48
+ "SIGNATURE_REJECTED"
49
+ );
50
+ this.name = "SignatureRejectedError";
51
+ }
52
+ };
53
+ var MethodNotSupportedError = class extends WalletSDKError {
54
+ constructor(method, walletType) {
55
+ super(
56
+ `Method ${method} is not supported by ${walletType}`,
57
+ "METHOD_NOT_SUPPORTED",
58
+ { method, walletType }
59
+ );
60
+ this.name = "MethodNotSupportedError";
61
+ }
62
+ };
63
+ var ConfigurationError = class extends WalletSDKError {
64
+ constructor(message, details) {
65
+ super(message, "CONFIGURATION_ERROR", details);
66
+ this.name = "ConfigurationError";
67
+ }
68
+ };
69
+
70
+ // src/adapters/base/wallet-adapter.ts
71
+ var WalletAdapter = class extends EventEmitter__default.default {
72
+ constructor() {
73
+ super(...arguments);
74
+ // 状态
75
+ this.state = "disconnected" /* DISCONNECTED */;
76
+ this.currentAccount = null;
77
+ }
78
+ /**
79
+ * Check if the wallet is currently connected
80
+ * @returns true if the wallet is connected (state is CONNECTED and has an account)
81
+ */
82
+ isConnected() {
83
+ return this.state === "connected" /* CONNECTED */ && this.currentAccount !== null;
84
+ }
85
+ /**
86
+ * Get the signer's address (implements ISigner interface)
87
+ * Returns the native address of the current account
88
+ */
89
+ async getAddress() {
90
+ this.ensureConnected();
91
+ if (!this.currentAccount) {
92
+ throw new WalletNotConnectedError(this.type);
93
+ }
94
+ return this.currentAccount.nativeAddress;
95
+ }
96
+ signTransaction(_transaction) {
97
+ throw new MethodNotSupportedError("signTransaction", this.type);
98
+ }
99
+ signTypedData(_typedData) {
100
+ throw new MethodNotSupportedError("signTypedData", this.type);
101
+ }
102
+ // 链切换(默认不支持)
103
+ switchChain(_chainId) {
104
+ throw new MethodNotSupportedError("switchChain", this.type);
105
+ }
106
+ addChain(_chainConfig) {
107
+ throw new MethodNotSupportedError("addChain", this.type);
108
+ }
109
+ // 合约调用(默认不支持)
110
+ async readContract(_params) {
111
+ throw new MethodNotSupportedError("readContract", this.type);
112
+ }
113
+ async writeContract(_params) {
114
+ throw new MethodNotSupportedError("writeContract", this.type);
115
+ }
116
+ async estimateGas(_params) {
117
+ throw new MethodNotSupportedError("estimateGas", this.type);
118
+ }
119
+ async waitForTransaction(_txHash, _confirmations) {
120
+ throw new MethodNotSupportedError("waitForTransaction", this.type);
121
+ }
122
+ getSigner() {
123
+ throw new MethodNotSupportedError("getSigner", this.type);
124
+ }
125
+ // 工具方法
126
+ ensureConnected() {
127
+ if (this.state !== "connected" /* CONNECTED */ || !this.currentAccount) {
128
+ throw new WalletNotConnectedError(this.type);
129
+ }
130
+ }
131
+ setState(state) {
132
+ this.state = state;
133
+ }
134
+ setAccount(account) {
135
+ this.currentAccount = account;
136
+ }
137
+ emitAccountChanged(account) {
138
+ this.emit("accountChanged", account);
139
+ }
140
+ emitChainChanged(chainId) {
141
+ this.emit("chainChanged", chainId);
142
+ }
143
+ emitDisconnected() {
144
+ this.emit("disconnected");
145
+ }
146
+ emitError(error) {
147
+ this.emit("error", error);
148
+ }
149
+ // EventEmitter 方法(从 EventEmitter3 继承)
150
+ // removeAllListeners 已经由 EventEmitter 提供
151
+ };
152
+
153
+ // src/utils/address/universal-address.ts
154
+ function createUniversalAddress(chainId, address) {
155
+ return `${chainId}:${address}`;
156
+ }
157
+
158
+ // src/adapters/tron/wallet-connect.ts
159
+ var _WalletConnectTronAdapter = class _WalletConnectTronAdapter extends WalletAdapter {
160
+ constructor(projectId) {
161
+ super();
162
+ this.type = "walletconnect-tron" /* WALLETCONNECT_TRON */;
163
+ this.chainType = ChainType.TRON;
164
+ this.name = "WalletConnect (Tron)";
165
+ this.icon = "https://avatars.githubusercontent.com/u/37784886";
166
+ this.wallet = null;
167
+ this.currentAddress = null;
168
+ if (!projectId) {
169
+ throw new ConfigurationError("WalletConnect projectId is required");
170
+ }
171
+ this.projectId = projectId;
172
+ }
173
+ /**
174
+ * Check if WalletConnect is available
175
+ */
176
+ async isAvailable() {
177
+ return typeof window !== "undefined";
178
+ }
179
+ /**
180
+ * Check if running in Telegram environment (Mini App or Web)
181
+ * Both Telegram Mini App (in client) and Telegram Web (web.telegram.org)
182
+ * provide window.Telegram.WebApp API, so they are treated the same way.
183
+ */
184
+ isTelegramMiniApp() {
185
+ if (typeof window === "undefined") return false;
186
+ const tg = window.Telegram?.WebApp;
187
+ if (!tg) return false;
188
+ const platform = tg.platform || "unknown";
189
+ console.log("[WalletConnect Tron] Telegram environment detected:", {
190
+ platform,
191
+ version: tg.version,
192
+ isMiniApp: platform !== "web",
193
+ // Mini App if not web platform
194
+ isWeb: platform === "web"
195
+ // Telegram Web if web platform
196
+ });
197
+ return true;
198
+ }
199
+ /**
200
+ * Restore session from existing wallet (for storage restoration)
201
+ */
202
+ async restoreSession(chainId) {
203
+ if (typeof window === "undefined") {
204
+ return null;
205
+ }
206
+ try {
207
+ const targetChainId = Array.isArray(chainId) ? chainId[0] || _WalletConnectTronAdapter.TRON_MAINNET_CHAIN_ID : chainId || _WalletConnectTronAdapter.TRON_MAINNET_CHAIN_ID;
208
+ if (!_WalletConnectTronAdapter.walletInstance || _WalletConnectTronAdapter.walletProjectId !== this.projectId) {
209
+ this.initializeWallet(targetChainId);
210
+ }
211
+ this.wallet = _WalletConnectTronAdapter.walletInstance;
212
+ if (!this.wallet) {
213
+ return null;
214
+ }
215
+ const status = await this.wallet.checkConnectStatus();
216
+ if (status && status.address) {
217
+ this.currentAddress = status.address;
218
+ const account = {
219
+ universalAddress: createUniversalAddress(targetChainId, status.address),
220
+ nativeAddress: status.address,
221
+ chainId: targetChainId,
222
+ chainType: ChainType.TRON,
223
+ isActive: true
224
+ };
225
+ this.setState("connected" /* CONNECTED */);
226
+ this.setAccount(account);
227
+ this.setupEventListeners();
228
+ return account;
229
+ }
230
+ return null;
231
+ } catch (error) {
232
+ console.debug("[WalletConnect Tron] Restore session failed:", error);
233
+ return null;
234
+ }
235
+ }
236
+ /**
237
+ * Initialize WalletConnect wallet instance
238
+ * @param chainId - Optional chain ID to determine network (default: Mainnet)
239
+ */
240
+ initializeWallet(chainId) {
241
+ if (_WalletConnectTronAdapter.walletInstance && _WalletConnectTronAdapter.walletProjectId === this.projectId) {
242
+ return;
243
+ }
244
+ let appUrl = "";
245
+ if (typeof window !== "undefined") {
246
+ try {
247
+ if (window.location && window.location.origin) {
248
+ appUrl = window.location.origin;
249
+ } else if (window.location && window.location.href) {
250
+ const url = new URL(window.location.href);
251
+ appUrl = url.origin;
252
+ }
253
+ } catch (error) {
254
+ console.warn("[WalletConnect Tron] Failed to get origin from window.location:", error);
255
+ }
256
+ if (appUrl && (appUrl.includes("serveo.net") || appUrl.includes("loca.lt") || appUrl.includes("ngrok.io") || appUrl.includes("ngrok-free.app") || appUrl.includes("cloudflared.io"))) {
257
+ console.log("[WalletConnect Tron] Detected tunnel service URL:", appUrl);
258
+ console.log("[WalletConnect Tron] \u26A0\uFE0F Make sure this URL is added to WalletConnect Cloud project allowlist");
259
+ }
260
+ if (!appUrl) {
261
+ const tg = window.Telegram?.WebApp;
262
+ if (tg && tg.initDataUnsafe?.start_param) {
263
+ appUrl = "https://enclave.network";
264
+ } else {
265
+ appUrl = "https://enclave.network";
266
+ }
267
+ }
268
+ } else {
269
+ appUrl = "https://enclave.network";
270
+ }
271
+ if (!appUrl || !appUrl.startsWith("http://") && !appUrl.startsWith("https://")) {
272
+ appUrl = "https://enclave.network";
273
+ }
274
+ const icons = [
275
+ "https://walletconnect.com/walletconnect-logo.svg",
276
+ "https://avatars.githubusercontent.com/u/37784886"
277
+ // WalletConnect GitHub avatar
278
+ ];
279
+ let network = walletconnectTron.WalletConnectChainID.Mainnet;
280
+ if (chainId !== void 0) {
281
+ if (chainId === 195 || chainId === _WalletConnectTronAdapter.TRON_MAINNET_CHAIN_ID) {
282
+ network = walletconnectTron.WalletConnectChainID.Mainnet;
283
+ } else if (chainId === 201910292) {
284
+ network = walletconnectTron.WalletConnectChainID.Shasta;
285
+ } else if (chainId === 2494104990) {
286
+ network = walletconnectTron.WalletConnectChainID.Nile;
287
+ }
288
+ }
289
+ const metadataInfo = {
290
+ name: "Enclave Wallet SDK",
291
+ description: "Multi-chain wallet adapter for Enclave",
292
+ url: appUrl,
293
+ icons,
294
+ network,
295
+ chainId,
296
+ isTelegram: this.isTelegramMiniApp(),
297
+ projectId: this.projectId,
298
+ urlValid: appUrl && (appUrl.startsWith("http://") || appUrl.startsWith("https://")),
299
+ iconsValid: icons && icons.length > 0 && icons.every((icon) => icon && icon.startsWith("http")),
300
+ currentLocation: typeof window !== "undefined" ? window.location.href : "N/A",
301
+ telegramPlatform: typeof window !== "undefined" && window.Telegram?.WebApp?.platform || "N/A"
302
+ };
303
+ console.log("[WalletConnect Tron] Initializing with metadata:", metadataInfo);
304
+ if (!metadataInfo.urlValid) {
305
+ console.warn("[WalletConnect Tron] \u26A0\uFE0F Invalid URL in metadata:", appUrl);
306
+ }
307
+ if (!metadataInfo.iconsValid) {
308
+ console.warn("[WalletConnect Tron] \u26A0\uFE0F Invalid icons in metadata:", icons);
309
+ }
310
+ console.log("[WalletConnect Tron] Initializing wallet...", {
311
+ network,
312
+ chainId,
313
+ note: "If no wallets are in WalletConnect Explorer for TRON, QR code will be displayed for scanning"
314
+ });
315
+ _WalletConnectTronAdapter.walletInstance = new walletconnectTron.WalletConnectWallet({
316
+ network,
317
+ options: {
318
+ projectId: this.projectId,
319
+ metadata: {
320
+ name: "Enclave Wallet SDK",
321
+ description: "Multi-chain wallet adapter for Enclave",
322
+ url: appUrl,
323
+ icons
324
+ }
325
+ },
326
+ // Theme configuration
327
+ themeMode: "light",
328
+ themeVariables: {
329
+ "--w3m-z-index": 1e4
330
+ // Ensure modal appears above Telegram UI
331
+ },
332
+ // Web3Modal configuration for recommended wallets
333
+ // According to official docs: https://developers.tron.network/docs/walletconnect-tron
334
+ // Note: If no wallets are registered in WalletConnect Explorer for TRON,
335
+ // explorerRecommendedWalletIds will have no effect, and QR code will be shown instead.
336
+ // @ts-ignore - web3ModalConfig is supported but may not be in TypeScript types
337
+ web3ModalConfig: {
338
+ themeMode: "light",
339
+ themeVariables: {
340
+ "--w3m-z-index": 1e4
341
+ },
342
+ /**
343
+ * Recommended Wallets are fetched from WalletConnect explore api:
344
+ * https://walletconnect.com/explorer?type=wallet&version=2
345
+ *
346
+ * IMPORTANT: If wallets are not registered in Explorer for TRON, this list will be ignored.
347
+ * The AppKit will show a QR code instead, which users can scan with any WalletConnect-compatible wallet.
348
+ *
349
+ * Wallet IDs (for reference, may not work if not in Explorer):
350
+ * - TokenPocket: 20459438007b75f4f4acb98bf29aa3b800550309646d375da5fd4aac6c2a2c66
351
+ * - TronLink: 1ae92b26df02f0abca6304df07debccd18262fdf5fe82daa81593582dac9a369
352
+ */
353
+ explorerRecommendedWalletIds: [
354
+ // These IDs are kept for when wallets register in WalletConnect Explorer
355
+ // Currently, if no TRON wallets are in Explorer, QR code will be shown
356
+ "20459438007b75f4f4acb98bf29aa3b800550309646d375da5fd4aac6c2a2c66",
357
+ // TokenPocket
358
+ "1ae92b26df02f0abca6304df07debccd18262fdf5fe82daa81593582dac9a369",
359
+ // TronLink
360
+ "4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0"
361
+ // TokenPocket (backup)
362
+ ]
363
+ }
364
+ });
365
+ _WalletConnectTronAdapter.walletProjectId = this.projectId;
366
+ }
367
+ /**
368
+ * Connect wallet
369
+ */
370
+ async connect(chainId) {
371
+ if (typeof window === "undefined") {
372
+ throw new Error("WalletConnect requires a browser environment");
373
+ }
374
+ const currentState = this.state;
375
+ if (currentState === "connecting" /* CONNECTING */) {
376
+ console.warn("[WalletConnect Tron] Connection already in progress, waiting...");
377
+ let attempts = 0;
378
+ while (this.state === "connecting" /* CONNECTING */ && attempts < 50) {
379
+ await new Promise((resolve) => setTimeout(resolve, 100));
380
+ attempts++;
381
+ }
382
+ if (this.state === "connected" /* CONNECTED */ && this.currentAccount) {
383
+ return this.currentAccount;
384
+ }
385
+ if (this.state === "connecting" /* CONNECTING */) {
386
+ throw new Error("Connection timeout - previous connection attempt is still pending");
387
+ }
388
+ }
389
+ if (this.state === "connected" /* CONNECTED */ && this.currentAccount) {
390
+ return this.currentAccount;
391
+ }
392
+ try {
393
+ this.setState("connecting" /* CONNECTING */);
394
+ const targetChainId = Array.isArray(chainId) ? chainId[0] || _WalletConnectTronAdapter.TRON_MAINNET_CHAIN_ID : chainId || _WalletConnectTronAdapter.TRON_MAINNET_CHAIN_ID;
395
+ if (!_WalletConnectTronAdapter.walletInstance || _WalletConnectTronAdapter.walletProjectId !== this.projectId) {
396
+ this.initializeWallet(targetChainId);
397
+ }
398
+ this.wallet = _WalletConnectTronAdapter.walletInstance;
399
+ if (!this.wallet) {
400
+ throw new Error("Failed to initialize WalletConnect wallet");
401
+ }
402
+ let network = walletconnectTron.WalletConnectChainID.Mainnet;
403
+ if (targetChainId === 195) {
404
+ network = walletconnectTron.WalletConnectChainID.Mainnet;
405
+ } else if (targetChainId === 201910292) {
406
+ network = walletconnectTron.WalletConnectChainID.Shasta;
407
+ } else if (targetChainId === 2494104990) {
408
+ network = walletconnectTron.WalletConnectChainID.Nile;
409
+ }
410
+ let address;
411
+ try {
412
+ console.log("[WalletConnect Tron] Attempting to connect...", {
413
+ network,
414
+ chainId: targetChainId,
415
+ isTelegram: this.isTelegramMiniApp(),
416
+ projectId: this.projectId
417
+ });
418
+ const result = await this.wallet.connect();
419
+ address = result.address;
420
+ if (!address) {
421
+ throw new ConnectionRejectedError(this.type);
422
+ }
423
+ console.log("[WalletConnect Tron] Connection successful:", {
424
+ address,
425
+ network,
426
+ chainId: targetChainId,
427
+ isTelegram: this.isTelegramMiniApp()
428
+ });
429
+ } catch (error) {
430
+ const errorMessage = error.message || String(error);
431
+ const errorCode = error.code || error.error?.code;
432
+ const origin = typeof window !== "undefined" && window.location ? window.location.origin : "";
433
+ let detailedError = errorMessage;
434
+ if (error.error) {
435
+ if (typeof error.error === "string") {
436
+ detailedError = error.error;
437
+ } else if (error.error.message) {
438
+ detailedError = error.error.message;
439
+ } else if (error.error.data) {
440
+ detailedError = JSON.stringify(error.error.data);
441
+ }
442
+ }
443
+ const isNoWalletFound = errorMessage.includes("\u6CA1\u6709\u627E\u5230\u652F\u6301\u7684\u94B1\u5305") || errorMessage.includes("No matching wallet") || errorMessage.includes("No wallet found") || errorMessage.includes("\u627E\u4E0D\u5230\u94B1\u5305") || errorMessage.includes("not found") || errorMessage.includes("no matching");
444
+ const isTimeout = errorMessage.includes("timeout") || errorMessage.includes("\u8D85\u65F6") || errorCode === "TIMEOUT";
445
+ const isRejected = errorMessage.includes("rejected") || errorMessage.includes("\u62D2\u7EDD") || errorCode === 4001;
446
+ const isOriginNotAllowed = errorCode === 3e3 || /origin not allowed/i.test(errorMessage) || /Unauthorized:\s*origin not allowed/i.test(errorMessage);
447
+ const currentMetadata = this.wallet ? {
448
+ // Try to get metadata from wallet instance if available
449
+ projectId: this.projectId,
450
+ network
451
+ } : null;
452
+ const errorDetails = {
453
+ error: errorMessage,
454
+ detailedError,
455
+ code: errorCode,
456
+ isTelegram: this.isTelegramMiniApp(),
457
+ network,
458
+ chainId: targetChainId,
459
+ projectId: this.projectId,
460
+ metadata: currentMetadata,
461
+ // Get URL from window.location if available
462
+ currentUrl: typeof window !== "undefined" ? window.location.href : "N/A",
463
+ telegramPlatform: typeof window !== "undefined" && window.Telegram?.WebApp?.platform || "N/A",
464
+ errorType: isNoWalletFound ? "NO_WALLET_FOUND" : isTimeout ? "TIMEOUT" : isRejected ? "REJECTED" : "UNKNOWN"
465
+ };
466
+ console.error("[WalletConnect Tron] Connection error - Full details:", errorDetails);
467
+ console.error("[WalletConnect Tron] Error object:", error);
468
+ console.error("[WalletConnect Tron] Error stack:", error.stack);
469
+ if (isNoWalletFound) {
470
+ const noWalletErrorDetails = [
471
+ `
472
+ === WalletConnect Tron: No Matching Wallet Found ===`,
473
+ `Error: ${errorMessage}`,
474
+ `Detailed: ${detailedError}`,
475
+ `Code: ${errorCode || "N/A"}`,
476
+ ``,
477
+ `Environment:`,
478
+ ` - Telegram Mini App: ${this.isTelegramMiniApp() ? "Yes" : "No"}`,
479
+ ` - Platform: ${errorDetails.telegramPlatform}`,
480
+ ` - Current URL: ${errorDetails.currentUrl}`,
481
+ ``,
482
+ `Configuration:`,
483
+ ` - Project ID: ${this.projectId ? "Set" : "Missing"}`,
484
+ ` - Network: ${network}`,
485
+ ` - Chain ID: ${targetChainId}`,
486
+ ` - Metadata URL: ${typeof window !== "undefined" ? window.location.origin : "N/A"}`,
487
+ ``,
488
+ `Possible Causes:`,
489
+ ` 1. No WalletConnect-compatible wallet (TokenPocket, etc.) installed on device`,
490
+ ` 2. Wallet app not opened or not responding to deep link (wc://)`,
491
+ ` 3. Deep link handling issue in Telegram Mini App environment`,
492
+ ` 4. WalletConnect session timeout (user took too long to approve)`,
493
+ ` 5. Network connectivity issue preventing WalletConnect relay connection`,
494
+ ``,
495
+ `Solutions:`,
496
+ ` 1. Ensure TokenPocket or other WalletConnect-compatible wallet is installed`,
497
+ ` 2. Try opening the wallet app manually before connecting`,
498
+ ` 3. In Telegram Mini App, ensure the deep link popup is not blocked`,
499
+ ` 4. Try connecting again (may need to wait a few seconds)`,
500
+ ` 5. Check network connection and WalletConnect relay server accessibility`,
501
+ ``,
502
+ `For more details, see the error object logged above.`,
503
+ `===========================================
504
+ `
505
+ ].join("\n");
506
+ console.error(noWalletErrorDetails);
507
+ throw new ConnectionRejectedError(
508
+ `WalletConnect Tron: \u6CA1\u6709\u627E\u5230\u652F\u6301\u7684\u94B1\u5305 (No matching wallet found)
509
+
510
+ \u53EF\u80FD\u7684\u539F\u56E0\uFF1A
511
+ 1. \u8BBE\u5907\u4E0A\u672A\u5B89\u88C5\u652F\u6301 WalletConnect \u7684\u94B1\u5305\uFF08\u5982 TokenPocket\uFF09
512
+ 2. \u94B1\u5305\u5E94\u7528\u672A\u6253\u5F00\u6216\u672A\u54CD\u5E94 deep link (wc://)
513
+ 3. \u5728 Telegram Mini App \u4E2D\uFF0Cdeep link \u5904\u7406\u53EF\u80FD\u6709\u95EE\u9898
514
+ 4. \u8FDE\u63A5\u8D85\u65F6\uFF08\u7528\u6237\u672A\u53CA\u65F6\u6279\u51C6\uFF09
515
+ 5. \u7F51\u7EDC\u8FDE\u63A5\u95EE\u9898
516
+
517
+ \u89E3\u51B3\u65B9\u6848\uFF1A
518
+ 1. \u786E\u4FDD\u5DF2\u5B89\u88C5 TokenPocket \u6216\u5176\u4ED6\u652F\u6301 WalletConnect \u7684\u94B1\u5305
519
+ 2. \u5C1D\u8BD5\u624B\u52A8\u6253\u5F00\u94B1\u5305\u5E94\u7528\u540E\u518D\u8FDE\u63A5
520
+ 3. \u5728 Telegram Mini App \u4E2D\uFF0C\u786E\u4FDD deep link \u5F39\u7A97\u672A\u88AB\u963B\u6B62
521
+ 4. \u7A0D\u7B49\u51E0\u79D2\u540E\u91CD\u8BD5\u8FDE\u63A5
522
+ 5. \u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u548C WalletConnect \u4E2D\u7EE7\u670D\u52A1\u5668\u53EF\u8BBF\u95EE\u6027
523
+
524
+ \u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F\u8BF7\u67E5\u770B\u63A7\u5236\u53F0\u65E5\u5FD7\u3002`
525
+ );
526
+ }
527
+ if (errorMessage.includes("Invalid") || errorMessage.includes("Configuration") || errorMessage.includes("App Config") || errorMessage.includes("Invalid App")) {
528
+ const configErrorDetails = [
529
+ `
530
+ === WalletConnect Tron Configuration Error ===`,
531
+ `Error: ${errorMessage}`,
532
+ `Detailed: ${detailedError}`,
533
+ `Code: ${errorCode || "N/A"}`,
534
+ `
535
+ Environment:`,
536
+ ` - Telegram Mini App: ${this.isTelegramMiniApp() ? "Yes" : "No"}`,
537
+ ` - Platform: ${errorDetails.telegramPlatform}`,
538
+ ` - Current URL: ${errorDetails.currentUrl}`,
539
+ `
540
+ Configuration:`,
541
+ ` - Project ID: ${this.projectId ? "Set" : "Missing"}`,
542
+ ` - Network: ${network}`,
543
+ ` - Chain ID: ${targetChainId}`,
544
+ `
545
+ Possible Causes:`,
546
+ ` 1. Deep link (wc://) handling issue in Telegram Mini App`,
547
+ ` 2. Invalid metadata configuration (URL or icons not accessible)`,
548
+ ` 3. Network/chainId mismatch`,
549
+ ` 4. WalletConnect project ID not configured correctly`,
550
+ ` 5. Domain not added to WalletConnect Cloud allowlist`,
551
+ `
552
+ Please check:`,
553
+ ` - WalletConnect Project ID is valid and active`,
554
+ ` - Domain is added to WalletConnect Cloud allowlist (for serveo.net, etc.)`,
555
+ ` - Metadata URL is accessible: Check console for metadata logs`,
556
+ ` - Icons are accessible: Check console for icon URLs`,
557
+ ` - Network matches chainId: Expected ${network} for chainId ${targetChainId}`,
558
+ `
559
+ For more details, see the error object logged above.`,
560
+ `===========================================
561
+ `
562
+ ].join("\n");
563
+ console.error(configErrorDetails);
564
+ throw new ConfigurationError(
565
+ `WalletConnect Tron connection failed: ${errorMessage}
566
+
567
+ Configuration Details:
568
+ - Telegram Mini App: ${this.isTelegramMiniApp() ? "Yes" : "No"}
569
+ - Platform: ${errorDetails.telegramPlatform}
570
+ - Origin: ${origin || "(unknown)"}
571
+ - Project ID: ${this.projectId ? "Set" : "Missing"}
572
+ - Network: ${network}
573
+ - Chain ID: ${targetChainId}
574
+
575
+ This "Invalid App Configuration" error may be caused by:
576
+ 1. Deep link (wc://) handling issue in Telegram Mini App
577
+ 2. Invalid metadata configuration (URL or icons)
578
+ 3. Network/chainId mismatch
579
+ 4. Domain not added to WalletConnect Cloud allowlist
580
+
581
+ Please check the console for detailed error information.`
582
+ );
583
+ }
584
+ if (isOriginNotAllowed) {
585
+ throw new ConfigurationError(
586
+ `WalletConnect Tron relayer rejected this origin (code 3000: Unauthorized: origin not allowed).
587
+
588
+ Fix:
589
+ 1) Open WalletConnect Cloud \u2192 your project (${this.projectId})
590
+ 2) Add this site origin to the allowlist:
591
+ - ${origin || "(unknown origin)"}
592
+
593
+ Common dev origins to allow:
594
+ - http://localhost:5173
595
+ - http://192.168.0.221:5173 (your LAN dev URL)
596
+ - https://wallet-test.enclave-hq.com (your Cloudflare Tunnel/custom domain)
597
+
598
+ Original error: ${errorMessage}`
599
+ );
600
+ }
601
+ if (isTimeout) {
602
+ throw new ConnectionRejectedError(
603
+ `WalletConnect Tron connection timeout. Please try again and ensure your wallet app is open and ready.`
604
+ );
605
+ }
606
+ if (isRejected) {
607
+ throw new ConnectionRejectedError(this.type);
608
+ }
609
+ throw error;
610
+ }
611
+ this.currentAddress = address;
612
+ const account = {
613
+ universalAddress: createUniversalAddress(targetChainId, address),
614
+ nativeAddress: address,
615
+ chainId: targetChainId,
616
+ chainType: ChainType.TRON,
617
+ isActive: true
618
+ };
619
+ this.setState("connected" /* CONNECTED */);
620
+ this.setAccount(account);
621
+ this.setupEventListeners();
622
+ return account;
623
+ } catch (error) {
624
+ this.setState("error" /* ERROR */);
625
+ this.setAccount(null);
626
+ this.currentAddress = null;
627
+ if (error.message?.includes("rejected") || error.code === 4001) {
628
+ throw new ConnectionRejectedError(this.type);
629
+ }
630
+ throw error;
631
+ }
632
+ }
633
+ /**
634
+ * Disconnect wallet
635
+ */
636
+ async disconnect() {
637
+ this.removeEventListeners();
638
+ if (this.wallet) {
639
+ try {
640
+ await this.wallet.disconnect();
641
+ } catch (error) {
642
+ console.warn("[WalletConnect Tron] Error during disconnect:", error);
643
+ }
644
+ }
645
+ this.wallet = null;
646
+ this.currentAddress = null;
647
+ this.setState("disconnected" /* DISCONNECTED */);
648
+ this.setAccount(null);
649
+ this.emitDisconnected();
650
+ }
651
+ /**
652
+ * Sign message
653
+ */
654
+ async signMessage(message) {
655
+ this.ensureConnected();
656
+ try {
657
+ if (!this.wallet) {
658
+ throw new Error("Wallet not initialized");
659
+ }
660
+ const signature = await this.wallet.signMessage(message);
661
+ if (typeof signature === "string") {
662
+ return signature;
663
+ } else if (signature && typeof signature === "object") {
664
+ if ("signature" in signature) {
665
+ return signature.signature;
666
+ } else if ("result" in signature) {
667
+ return signature.result;
668
+ } else {
669
+ return JSON.stringify(signature);
670
+ }
671
+ }
672
+ throw new Error("Invalid signature format returned from wallet");
673
+ } catch (error) {
674
+ console.error("[WalletConnect Tron] Sign message error:", error);
675
+ let errorMessage = "Unknown error";
676
+ if (typeof error === "string") {
677
+ errorMessage = error;
678
+ } else if (error?.message) {
679
+ errorMessage = error.message;
680
+ } else if (error?.error?.message) {
681
+ errorMessage = error.error.message;
682
+ } else {
683
+ try {
684
+ errorMessage = JSON.stringify(error);
685
+ } catch {
686
+ errorMessage = String(error);
687
+ }
688
+ }
689
+ if (errorMessage?.includes("rejected") || errorMessage?.includes("declined") || errorMessage?.includes("User rejected") || error?.code === 4001 || error?.code === "USER_REJECTED" || error?.error?.code === 4001) {
690
+ throw new SignatureRejectedError();
691
+ }
692
+ if (errorMessage?.includes("not supported") || errorMessage?.includes("method not found") || errorMessage?.includes("Method not found") || error?.code === -32601 || error?.error?.code === -32601) {
693
+ throw new Error("tron_signMessage is not supported by the connected wallet. Please use a wallet that supports WalletConnect Tron signing, or use TronLink extension for browser-based signing.");
694
+ }
695
+ throw new Error(`WalletConnect Tron sign message failed: ${errorMessage}`);
696
+ }
697
+ }
698
+ /**
699
+ * Sign transaction
700
+ *
701
+ * @param transaction - Tron transaction object
702
+ * Can be created using TronWeb (if available) or any TRON transaction builder
703
+ * Format: { raw_data: {...}, raw_data_hex: "...", txID: "..." }
704
+ * @returns Signed transaction object or signature
705
+ */
706
+ async signTransaction(transaction) {
707
+ this.ensureConnected();
708
+ try {
709
+ if (!this.wallet) {
710
+ throw new Error("Wallet not initialized");
711
+ }
712
+ if (!transaction) {
713
+ throw new Error("Transaction object is required");
714
+ }
715
+ console.log("[WalletConnect Tron] Signing transaction:", {
716
+ hasRawData: !!transaction.raw_data,
717
+ hasRawDataHex: !!transaction.raw_data_hex,
718
+ hasTxID: !!transaction.txID
719
+ });
720
+ const result = await this.wallet.signTransaction(transaction);
721
+ if (typeof result === "string") {
722
+ return result;
723
+ } else if (result && typeof result === "object") {
724
+ if ("txID" in result && typeof result.txID === "string") {
725
+ return result.txID;
726
+ } else if ("txid" in result && typeof result.txid === "string") {
727
+ return result.txid;
728
+ } else if ("signature" in result) {
729
+ return JSON.stringify(result);
730
+ } else {
731
+ return JSON.stringify(result);
732
+ }
733
+ }
734
+ throw new Error("Invalid signature format returned from wallet");
735
+ } catch (error) {
736
+ console.error("[WalletConnect Tron] Sign transaction error:", error);
737
+ let errorMessage = "Unknown error";
738
+ if (typeof error === "string") {
739
+ errorMessage = error;
740
+ } else if (error?.message) {
741
+ errorMessage = error.message;
742
+ } else if (error?.error?.message) {
743
+ errorMessage = error.error.message;
744
+ } else if (error?.data?.message) {
745
+ errorMessage = error.data.message;
746
+ } else {
747
+ try {
748
+ errorMessage = JSON.stringify(error);
749
+ } catch {
750
+ errorMessage = String(error);
751
+ }
752
+ }
753
+ if (errorMessage?.includes("rejected") || errorMessage?.includes("declined") || errorMessage?.includes("User rejected") || error?.code === 4001 || error?.code === "USER_REJECTED" || error?.error?.code === 4001) {
754
+ throw new SignatureRejectedError("Transaction signature was rejected by user");
755
+ }
756
+ if (errorMessage?.includes("not supported") || errorMessage?.includes("method not found") || errorMessage?.includes("Method not found") || errorMessage?.includes("Not support") || error?.code === -32601 || error?.error?.code === -32601) {
757
+ throw new Error("tron_signTransaction is not supported by the connected wallet. Please use a wallet that supports WalletConnect Tron signing, or use TronLink extension for browser-based signing.");
758
+ }
759
+ throw new Error(`WalletConnect Tron sign transaction failed: ${errorMessage}`);
760
+ }
761
+ }
762
+ /**
763
+ * Read contract (not supported by WalletConnect)
764
+ */
765
+ async readContract(_params) {
766
+ this.ensureConnected();
767
+ throw new Error("WalletConnect Tron does not support direct contract reading. Please use direct Tron RPC calls or a wallet extension (like TronLink) for read operations.");
768
+ }
769
+ /**
770
+ * Write contract (not yet implemented)
771
+ */
772
+ async writeContract(_params) {
773
+ throw new Error("Contract write not yet implemented for WalletConnect Tron");
774
+ }
775
+ /**
776
+ * Estimate gas (not yet implemented)
777
+ */
778
+ async estimateGas(_params) {
779
+ throw new Error("Gas estimation not yet implemented for WalletConnect Tron");
780
+ }
781
+ /**
782
+ * Wait for transaction (not yet implemented)
783
+ */
784
+ async waitForTransaction(_txHash, _confirmations) {
785
+ throw new Error("Transaction waiting not yet implemented for WalletConnect Tron");
786
+ }
787
+ /**
788
+ * Setup event listeners
789
+ */
790
+ setupEventListeners() {
791
+ if (!this.wallet) {
792
+ return;
793
+ }
794
+ this.wallet.on("accountsChanged", (accounts) => {
795
+ if (accounts && accounts.length > 0 && accounts[0] !== this.currentAddress) {
796
+ const newAddress = accounts[0];
797
+ this.currentAddress = newAddress;
798
+ if (this.currentAccount) {
799
+ const newAccount = {
800
+ ...this.currentAccount,
801
+ nativeAddress: newAddress,
802
+ universalAddress: createUniversalAddress(this.currentAccount.chainId, newAddress)
803
+ };
804
+ this.setAccount(newAccount);
805
+ this.emit("accountChanged", newAccount);
806
+ }
807
+ } else if (!accounts || accounts.length === 0) {
808
+ this.disconnect();
809
+ }
810
+ });
811
+ this.wallet.on("disconnect", () => {
812
+ this.disconnect();
813
+ });
814
+ }
815
+ /**
816
+ * Remove event listeners
817
+ */
818
+ removeEventListeners() {
819
+ if (!this.wallet) {
820
+ return;
821
+ }
822
+ this.wallet.removeAllListeners("accountsChanged");
823
+ this.wallet.removeAllListeners("disconnect");
824
+ }
825
+ /**
826
+ * Get provider (returns wallet instance)
827
+ */
828
+ getProvider() {
829
+ return this.wallet;
830
+ }
831
+ /**
832
+ * Clear static wallet instance (for complete cleanup)
833
+ */
834
+ static clearWalletInstance() {
835
+ if (_WalletConnectTronAdapter.walletInstance) {
836
+ _WalletConnectTronAdapter.walletInstance.disconnect().catch(() => {
837
+ });
838
+ _WalletConnectTronAdapter.walletInstance = null;
839
+ _WalletConnectTronAdapter.walletProjectId = null;
840
+ }
841
+ }
842
+ };
843
+ // Tron 主网链 ID
844
+ _WalletConnectTronAdapter.TRON_MAINNET_CHAIN_ID = 195;
845
+ // Static wallet instance to avoid multiple initializations
846
+ _WalletConnectTronAdapter.walletInstance = null;
847
+ _WalletConnectTronAdapter.walletProjectId = null;
848
+ var WalletConnectTronAdapter = _WalletConnectTronAdapter;
849
+
850
+ exports.WalletConnectTronAdapter = WalletConnectTronAdapter;
851
+ //# sourceMappingURL=tron.js.map
852
+ //# sourceMappingURL=tron.js.map